Compare commits

...
Author SHA1 Message Date
Swastick Chowdhury d6189ae3ea loader: group interpreter instruction prefixes into a typed struct (#62)
Replace the #[allow(clippy::too_many_arguments)] on execute_mov_rm with a
Prefixes struct that carries rex_w, rex_r, rex_b, seg_gs and seg_fs. The
interpreter decodes the prefixes once per instruction and passes the struct to
the helpers that need them, so the lint is satisfied by construction instead
of suppressed.

Add a regression test module that pins the prefix and register-extension
behaviour of the interpreter: REX.R and REX.B selecting the expected ModRM
reg and rm registers, the two bits extending independent fields, a move
without REX.W staying 32-bit wide, and the FS prefix adding the FS base.
The test was run against unmodified main first and passed there, so the
refactor is shown to preserve semantics.

Closes #62

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:02:10 +05:30
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
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
elforeign b041952437 Merge remote-tracking branch 'origin/main' into task/191-depth-attachment
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:29:02 -06:00
Ranveer Soni ae80d7fd8f Merge pull request #238 from elforeign/fix/vop3-interp-length
isa: VOP3 interpolation attribute fields never select a literal
2026-11-24 13:58:26 +05:30
Ranveer Soni d57e9c031c Merge pull request #239 from elforeign/feat/vopc-compare
shader: Wave32 VOPC integer compares with VCC/EXEC rules
2026-11-24 13:58:02 +05:30
elforeign 924d68afbc metal: take the BC1 upload type in depth passes, gate BC per case
An independent review found that DepthPass accepted a Bc1Subresource, whose
public fields let a caller pair a short slice with a larger pitch before
replaceRegion. Take the validated Bc1Upload instead. Supply the texture only
to the textured case so a device without BC support fails that case alone.
The CPU reference now rejects depth outside 0..=1 since it does not clip,
and checks the texture size with checked arithmetic.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:27:43 -06:00
elforeign 840eca0a29 metal: depth attachment known-answer rendering (#191)
Draw ordered triangles with an optional Depth32Float attachment, per-draw
compare function and write enable, and read back colour and stored depth,
so depth compare, clear, write enable and disabled depth can each be
checked against independently derived values. One draw samples an original
BC1 texture through the native BC1 path, so the BC upload is exercised by
rendering, not only by compute readback.

Also adds the missing changelog lines for PR #224 (BC7) and PR #231 (#172).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:23:31 -06:00
elforeign 0749330868 shader: Wave32 VOPC integer compares with VCC/EXEC rules
Adds v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 across the chain: opcodes
generated from the pinned AMD XML, one typed VectorCompare instruction
(relation + signedness, table-driven decode), the reference interpreter,
the independent semantic-review interpreter, typed IR and MSL.

Rules (RDNA 2 ISA guide 3.9, 2.1, 3.3; contract in
docs/shaders/vector-compare.md): VCC_LO[n] = EXEC_LO[n] & test(lane n),
always fully written, so empty EXEC gives 0 and reads no source; VCC_HI
becomes unknown; EXEC, SCC and VGPRs are unchanged. A lane-derived
VCC_LO may feed only s_cbranch_vccz, v_mov_b32 vN, vcc_lo and another
compare's SRC0, so EXEC never becomes data-dependent. A runtime
s_cbranch_vccz is wave-uniform: the skipped code may hold only integer
vector ALU instructions with initialized destinations, checked whether
or not it is taken, and lowers to selects at the join.

The Metal kernel makes no SIMD-group, threadgroup or barrier assumption:
each thread rebuilds its RDNA wave's mask by recomputing the 32 lanes'
operands from their input words, bounded by threads_per_grid. The
reference now runs lockstep Wave32 waves; absent lanes of a final
partial wave contribute 0.

Verified with an original LLVM-assembled fixture and 251 programs
(every form on 10 boundary values in both operand orders, partial and
empty EXEC, both runtime branch edges in one dispatch, mask chains,
32 pinned rejections) against exact integer definitions. Translator,
reference and second interpreter agree on CPU; all 252 programs match
on native Metal with validation; LLVM agrees on every encoding.
Breaking any implementation (signedness, EXEC masking, empty EXEC,
absent-lane bound, join polarity or uniformity) fails the tests.

Fixes #186

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:22:19 -06:00
elforeign 2ddd2a2485 isa: VOP3 interpolation attribute fields never select a literal
identify() treated SRC0 = 255 as the literal selector in every VOP3 form
with the LITERAL extension, so six interpolation forms (v_interp_p1_f32,
v_interp_p2_f32, v_interp_mov_f32 in VOP3, v_interp_p1ll_f16,
v_interp_p1lv_f16, v_interp_p2_f16) were read as 12 bytes. In these
forms SRC0 is not an operand selector: the RDNA 2 ISA guide, section
10.4.2, says SRC0 "is treated as a set of bit-fields" {attr_word,
attr_chan, attr}, and the XML gives its operand type as OPR_ATTR. LLVM
23.1.6 decodes all six as 8 bytes.

Fields typed OPR_ATTR are now skipped when looking for a literal. VGPR-
only sources are unchanged: LLVM still reads v_permlane16_b32 and
v_movrels_b32 with selector 255 as 12 bytes (invalid operand), and the
new test pins that too. The corpus check's six pinned mismatch rows
are gone: v_interp_mov_f32 now agrees fully and the other five are
operand_flagged (same form and length, LLVM flags the operand).

The new test fails on the old rule.

Fixes #235

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:20:01 -06:00
Ranveer Soni 0e7fa4aa93 Merge pull request #234 from elforeign/task/209-llvm-corpus
test(isa): independent LLVM corpus check of gfx1030 identification (#209)
2026-11-24 13:38:57 +05:30
Ranveer Soni 1ee557bdc4 Merge pull request #233 from atesahmet0/task/197-bswap
Implement 32-bit and 64-bit BSWAP in both CPU engines
2026-11-24 13:38:32 +05:30
elforeign fa4d4b9d71 Merge remote-tracking branch 'origin/main' into task/209-llvm-corpus 2026-11-24 02:06:03 -06:00
elforeign bf3cca0718 isa: independent LLVM corpus check of gfx1030 identification (#209)
Issue #209 asks for LLVM-generated original samples beyond the existing
oracle cases, with measured coverage and unresolved differences. The
corpus has 317 original instructions assembled by llvm-mc and 6,574 byte
probes built from every metadata form's identifying bits: one with zero
operands, one per extension selector its family can carry, and two with
random operand bits. llvm-objdump decodes each probe, giving LLVM's
instruction and the bytes its decoder consumed (llvm-mc --disassemble
re-encodes, which hides consumed length for MIMG NSA).

The test compares identify with every row and pins per-source class
counts, the 130 disagreeing rows and a digest of the random probes, so
any metadata change fails until reviewed. Disagreements are reported, not
fixed: 18 MIMG names LLVM does not know, 6 VOP3 interpolation forms whose
attribute field 255 is read as a literal, and 21 extension cases on
operand-less or SGPR-pair instructions.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:05:58 -06:00
Ranveer Soni a86100c00d Merge pull request #231 from elforeign/task/172-extension-word-negative
test(isa): gfx1030 extension-word negative tests (#172)
2026-11-24 13:33:40 +05:30
ates 044f036ea5 Implement 32-bit and 64-bit BSWAP in both CPU engines
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:57:26 +03:00
elforeign 79947ec998 Merge remote-tracking branch 'origin/main' into task/172-extension-word-negative 2026-11-24 01:55:01 -06:00
Ranveer Soni 17fe880bdc Merge pull request #230 from elforeign/feat/sop2-signed-add-sub
shader: add s_add_i32 and s_sub_i32 with signed-overflow SCC (follow-up to #185)
2026-11-24 13:24:39 +05:30
elforeign e93e4e1e2a isa: negative tests for gfx1030 extension words (#172)
Issue #172 asks for independent truncated and invalid literal, SDWA, DPP
and NSA cases, and for length recognition to be kept apart from semantic
validity. Every case starts from bytes llvm-mc assembled from an original
instruction; expected results come from LLVM's disassembly of the cut or
altered bytes, not from the decoder.

Covers 62 proper prefixes of 18 literal/SDWA/DPP/NSA instructions with the
exact length each needs, 7 extension selectors on forms that do not allow
them, two reserved control values that keep their trailer length, and 8
back-to-back pairs whose second instruction starts after the trailer. An
ignored test re-checks every source encoding with LLVM.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:54:22 -06:00
elforeign 425327a0f2 shader: add s_add_i32 and s_sub_i32 with signed-overflow SCC
#185 left both forms unsupported because the pinned XML says only
"carry-out" for them. The AMD RDNA 2 ISA reference guide (GPUOpen,
section 12.1 SOP2 Instructions, p. 101-102, and section 5.3 Scalar
Condition Code, p. 33) defines SCC for both as signed overflow:
add overflows when the operands share a sign that the result lacks;
subtract when the operands' signs differ and the result's sign differs
from S0's. The guide also confirms the unsigned rules used in #185.

Adds both forms to the generated opcodes, the decoder, the reference
(exact signed result must fit in i32), the independent interpreter (the
guide's sign-bit rule over its ripple adder) and the translator, plus
400 boundary programs, eight hand-worked overflow and no-overflow cases
(-1 + 1 and 0 - 1 carry or borrow but do not overflow) and two signed
overflows in the scalar ALU fixture. Inverting the overflow rule in any
one implementation fails three tests. s_min_i32 and the other SOP2
forms stay unsupported.

Refs #185

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:48:52 -06:00
Ranveer Soni 1212280ab8 Merge pull request #224 from elforeign/task/171-bc7-decoder
feat(texture): BC7 block decoder, all eight modes, with independent vectors (#171)
2026-11-24 13:13:55 +05:30
Ranveer Soni c6665ebfb4 Merge pull request #229 from elforeign/feat/sop2-scalar-alu
shader: SOP2 scalar add, subtract and bitwise forms with SCC (fixes #185)
2026-11-24 13:13:32 +05:30
elforeign 96e2baeb75 Merge remote-tracking branch 'origin/main' into feat/sop2-scalar-alu
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:40:26 -06:00
Ranveer Soni b9be341dfc Merge pull request #227 from elforeign/feat/test-inventory
audit: compare Cargo test inventories between two commits
2026-11-24 13:09:55 +05:30
elforeign b2391b4de4 Merge remote-tracking branch 'origin/main' into feat/sop2-scalar-alu
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:39:50 -06:00
Ranveer Soni ecc109a7e2 Merge pull request #225 from elforeign/ci/pr-template-check
ci: require pull requests to follow the PR template
2026-11-24 13:09:07 +05:30
Ranveer Soni 67e6565fc2 Merge branch 'main' into ci/pr-template-check 2026-11-24 13:08:58 +05:30
elforeign 994efd38f9 shader: decode and execute SOP2 scalar add, subtract and bitwise forms
Adds s_add_u32, s_sub_u32, s_addc_u32, s_subb_u32, s_and_b32, s_or_b32
and s_xor_b32 across the chain: generated opcodes from the pinned AMD
XML, a typed ScalarAlu instruction, decoding, the reference interpreter,
the independent semantic-review interpreter and the translator, which
resolves scalar state and SCC as it already does for s_mov/s_cmp.
v_mov_b32_e32 may now read a normal SGPR, so results reach vector code
as constants.

SCC: the XML states carry-out for additions, carry-in for ADDC/SUBB and
nonzero results for bitwise forms. For subtraction it says carry-out
without fixing the polarity; LLVM's lowering of usubo and of 64-bit
subtraction to s_sub_u32/s_subb_u32 requires SCC to be the borrow.
s_add_i32/s_sub_i32 stay unsupported: no pinned source settles whether
their SCC is the carry or signed overflow.

Verified with an original LLVM-assembled fixture and 1,400 boundary
programs (every form, 10x10 operands, SCC clear and set) against exact
integer definitions; translator, reference (exact integers) and
independent interpreter (bit-serial ripple adder) all agree, and all
1,401 programs match on native Metal with validation. LLVM agrees on
every encoding. Breaking any one implementation fails the tests.

Fixes #185
Independent review fixes: both interpreters now require a known SGPR
for v_mov_b32 from an SGPR even in an inactive lane, as translation
does; alias, literal and inline cases also assert the translated result
and run on Metal; rejections are pinned to the SOP2 word's offset; GPU
status is recorded as local evidence with acceptance pending.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:38:54 -06:00
Ranveer Soni aac0f31b93 Merge pull request #226 from elforeign/docs/readme-contributors
docs: add contributors section to README
2026-11-24 13:08:35 +05:30
elforeign ef0e472d5d docs: add contributors section to README
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:37:56 -06:00
elforeign 1784836639 audit: compare Cargo test inventories between two commits
Testing the old #166 and #165 heads silently ran without 12 BC texture
tests that main already had, because those heads predated the merge
that added them; nothing flagged the smaller inventory.

scripts/audit/test_inventory.py lists every test (and the ignored set)
of a base and a candidate commit, each in a temporary detached worktree
it always removes, and reports removed, added, newly ignored and newly
un-ignored tests keyed by package, target and name. Unexplained losses
exit 1; an --allow file with a reason per key explains intended ones.

951189c -> 5450612: removed 12 (all xenora-texture bc_formats), exit 1.
0cac6c4 -> 0cac6c4: 219 tests each side, no change, exit 0.

Fixes #208

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:37:54 -06:00
Ranveer Soni 68fc4e25dc Merge branch 'main' into task/171-bc7-decoder 2026-11-24 13:07:25 +05:30
Ranveer Soni cdaff0a391 Merge pull request #223 from elforeign/task/169-metal-bc4-bc5
feat(metal): native BC4 and BC5 UNORM/SNORM upload and readback (#169)
2026-11-24 13:06:51 +05:30
Ranveer Soni 184149561a Merge pull request #222 from elforeign/docs/plain-reply-claims
docs: claim by plain reply, one-week stale rule
2026-11-24 13:06:34 +05:30
Ranveer Soni e83475be17 Merge pull request #216 from elforeign/feat/gpu-compatibility-expansion
isa: fix isolated-branch inspection and verified form count (follow-up to #166)
2026-11-24 13:06:13 +05:30
elforeign fa55066699 ci: fail pull requests whose description skips the PR template
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:35:54 -06:00
elforeign f25060e891 changelog: restore the gfx1030 metadata and shader inspection entries
The upstream merge of main into this branch (01deb3f) resolved the
CHANGELOG conflict by dropping this PR's three entries;
documented_form_counts_match_the_generated_table caught it.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:35:27 -06:00
elforeign 9318e68840 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:34:37 -06:00
elforeign abd6698a66 Merge remote-tracking branch 'origin/main' into task/171-bc7-decoder 2026-11-24 01:32:50 -06:00
elforeign 5f8867bd30 Merge remote-tracking branch 'origin/main' into task/169-metal-bc4-bc5 2026-11-24 01:32:50 -06:00
Ranveer Soni 5ca90bfac0 Merge pull request #221 from atesahmet0/task/177-probe-report-consistency
Test probe report consistency across JSON, Markdown, and CSV
2026-11-24 12:59:38 +05:30
elforeign 7cc35ffd41 Merge remote-tracking branch 'origin/main' into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:28:23 -06:00
elforeign 57f10c1d7c Merge remote-tracking branch 'origin/main' into task/171-bc7-decoder
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/texture/src/lib.rs
2026-11-24 01:26:50 -06:00
elforeign 76620e274b texture: iterate texels directly in the BC7 tests
Strict Clippy (needless_range_loop) rejects indexing the output by the
loop counter; the assertions are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:26:34 -06:00
elforeign 240302fabe texture: add a BC7 block decoder from the Khronos BPTC text (#171)
Issue #171 asks for bounded BC7 decoding with independent vectors for
partitions, endpoint precision and indices. All eight modes are decoded:
the partition and anchor tables are extracted mechanically from Khronos
Data Format Specification 1.3 section 20.1, and blocks with a zero low
byte decode to zero as that section requires.

Hand-derived tests cover each mode's distinctive field (P-bits, shared
P-bits, anchors, rotation, index selection, the section's own mode 2
bit-position example), and 430 known-answer vectors come from a separate
clean-room reference decoder. CPU only; no Metal BC7 path is claimed.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:25:45 -06:00
Ranveer Soni 01deb3f8a8 Merge branch 'main' into feat/gpu-compatibility-expansion 2026-11-24 12:55:06 +05:30
Ranveer Soni e6b9a27242 Merge pull request #218 from elforeign/task/168-bc23-audit
test(metal): BC2/BC3 edge blocks, invalid payloads and capability reporting (follow-up to #214)
2026-11-24 12:54:35 +05:30
elforeign 8fdb569052 docs: claim by plain reply, one-week stale rule
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:23:57 -06:00
Ranveer Soni e79bd1ccaf Merge pull request #220 from elforeign/task/170-bc6h-subset
feat(texture): bounded BC6H subset decoder (single-subset modes) (#170)
2026-11-24 12:51:55 +05:30
Ranveer Soni 066bc3fc83 Merge pull request #217 from elforeign/feat/agent-task-queue
agent queue: command-only triggers, durable claim replay and review fixes (follow-up to #165)
2026-11-24 12:47:00 +05:30
ates a533d8107e Test cross-format probe reports against fixture counts and offsets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:16:45 +03:00
elforeign 3109b620fd texture: decode the single-subset BC6H modes
#170 asks for a documented, bounded BC6H subset with explicit rejection
of what is not implemented. This adds a CPU decoder for the four
single-subset modes (Khronos 3, 7, 11 and 15; Microsoft 11 to 14) in
signed and unsigned form, written from the Khronos Data Format 1.3 text
(Tables 121 and 122, unquantization and final unquantization). Reserved
modes decode to zero as the specification requires; the ten two-subset
modes return Bc6hError::UnsupportedMode, and BC6H_SUPPORTED_MODES lists
coverage by mode.

Tests use hand-derived values (saturation to 65504 and -65504, the
11-bit transform wrap, both reversed-bit fields, signed -32768 to
negative infinity) and 128 known-answer vectors from a separate
clean-room reference decoder, 16 per supported and reserved mode.
Flipping the reversed bit order, dropping the wrap mask, using 31/64
for signed data, a 4-bit anchor, accepting mode 0 or not zeroing
reserved modes each fails the tests.

Refs #170

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:16:24 -06:00
elforeign 878f554dcd Merge task/168-bc23-audit into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/metal/tests/native/texture_bc_alpha.rs
2026-11-24 01:12:31 -06:00
elforeign 46e2d36064 metal: compare non-interpolated BC4/BC5 codes exactly
The full-texel check applied the two-code tolerance to every channel, so
an endpoint or six-value fixed code outside the anchors could be off by
two and still pass. Each texel's tolerance now comes from its own index:
zero for stored and fixed codes and constant channels, two only for
interpolated codes. A readback kernel that lowers near-maximum red by two
now fails the BC4 and BC5 UNORM tests.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:12:20 -06:00
elforeign d94121bbb0 metal: compare non-interpolated BC2/BC3 codes exactly
An independent review of the #214 tests found that the full-texel check
applied the two-code interpolation tolerance to every channel, so an
endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255 outside the anchors
could be off by two and still pass. The tolerance now comes from each
texel's own indices: zero for stored and fixed codes, two only for
interpolated ones. A readback kernel that lowers near-opaque alpha by two
now fails all three tests. The 1.14-code bound is stated as 8/7.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:11:43 -06:00
elforeign ef4fbba797 Merge upstream main into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:08:59 -06:00
elforeign 97ea2541bb metal: cover BC2/BC3 edge blocks and report missing BC support apart
The section 12 audit of #214 found three gaps: no level narrower than a
block row (Metal's zero-stride single-row upload) or of 1x1, no checks
for zero extents or oversized and block-count-mismatched payloads, and a
missing BC capability surfaced the same way as an implementation fault.

Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload
rejections, and MetalError::is_capability_unavailable; the GPU tests now
print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the
texture to whole blocks, accepting oversized payloads, or a device
without BC support each makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:08:34 -06:00
elforeign f1ec653b91 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:06:04 -06:00
elforeign b1ab08c09d agent queue: apply claim checks when /reassign creates a claim
/reassign turned a ready task into a claim without the dependency and
file-overlap checks /claim applies, so a maintainer reassignment could
grant two overlapping claims. Run the same checks for the new holder.

Refs #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:47 -06:00
elforeign 6b479a6617 agent queue: fix review findings in replies, verification and issue forms
From independent review of the queue follow-up:
- Bot replies echoed user text (/blocked reasons, /reassign logins,
  file patterns) verbatim. Markers count when the bot posts them, so a
  reason containing an approval or done marker became a bot marker and
  could approve an acceptance command or hide another user's claim.
  Echoed text now has angle brackets and backticks escaped.
- /verified accepted a 7-character prefix and ignored extra arguments;
  a commit with the same short prefix is cheap to make. Require exactly
  one full 40-character SHA, with one parser shared by decide and the
  check.
- After a verification, the job looked up the check run by the pull
  request head SHA, but pull_request_target runs carry the base branch
  SHA, so it found nothing and || true hid it. The verify job now
  evaluates the same advisory check itself and no longer needs
  actions: write.
- The issue form renders Files inside a ```text fence and the parser
  took "text" as a path, so any two form-created tasks overlapped.
  Fence lines are skipped.
- A command still unanswered after lease_hours now gets a "Not decided"
  reply (window 2 x lease_hours) instead of being dropped silently.

Each fix has a test shown to fail with the fix reverted.

Refs #210, #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:28 -06:00
elforeign 7a10d7eac8 metal: cover BC4/BC5 edge blocks and invalid payloads
Section 12's audit asks for levels that are not whole blocks and for
rejected payloads. Adds a 5x3 (single block row, zero Metal stride) and
1x1 GPU test over BC4/BC5 UNORM and SNORM with hand-derived anchors, the
zero-extent and wrong-length upload rejections, and routes the GPU reads
through the shared capability-aware unwrap. Rounding the texture to whole
blocks, accepting oversized payloads, or a device without BC support each
makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:03:48 -06:00
elforeign 0e51ddda76 Merge test/metal-bc2-bc3 into the BC4/BC5 branch
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:02:47 -06:00
elforeign b5a462fb54 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:02:17 -06:00
elforeign 09e0bea55d shaders, isa: tighten inspection wording and review-found test gaps
From independent review:
- The summary said "not executable" for instructions that merely have
  no semantic decoding; a decoded program can still fail compilation.
  Say "without semantic decoding".
- When identification stops early, a branch target past the identified
  prefix was reported invalid although its boundaries are unknown;
  report it as unverified.
- The VOP3 and VOP3P literal probes used 1.0, which LLVM encodes as an
  inline constant (8 bytes), so neither exercised a literal. Use
  0x3f800001 and 0x3c01 and assert the 12-byte encoding and trailer.
- The coverage JSON test now also checks the document's shape.

Refs #183, #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:01:38 -06:00
elforeign 1260e07ba1 metal: cover BC2/BC3 edge blocks and report missing BC support apart
The section 12 audit of #214 found three gaps: no level narrower than a
block row (Metal's zero-stride single-row upload) or of 1x1, no checks
for zero extents or oversized and block-count-mismatched payloads, and a
missing BC capability surfaced the same way as an implementation fault.

Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload
rejections, and MetalError::is_capability_unavailable; the GPU tests now
print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the
texture to whole blocks, accepting oversized payloads, or a device
without BC support each makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:01:26 -06:00
elforeign e70780f30a Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:00:40 -06:00
elforeign ef481368d6 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:00:40 -06:00
Ranveer Soni 0cac6c4fcf Merge pull request #214 from elforeign/test/metal-bc2-bc3
test(metal): BC2/BC3 upload and sampling conformance (#168)
2026-11-24 12:30:21 +05:30
elforeign 3a598a83e1 shaders: assert add.bin inspects as 7 semantic instructions
Refs #183

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:59:45 -06:00
Ranveer Soni b69d4b97c6 Merge pull request #166 from elforeign/feat/gpu-compatibility-expansion
isa: complete gfx1030 instruction metadata and identification
2026-11-24 12:26:27 +05:30
elforeign 9fda5aab18 agent queue: re-run the check only after an accepted verification
The verify job re-ran the pull request check after any /verified
comment, including refused ones: the author's own, a non-verifier's, a
stale or unknown head or a malformed SHA. decide now marks only an
accepted verification of the current head, and the job re-runs the check
only when should-rerun confirms it. A test checks that what re-runs the
check is exactly what the check counts.

Replay decides a comment listed twice only once. Tests cover duplicate
and out-of-order listings, and every arrival order of a five-claim burst
grants exactly one of two overlapping claims.

Fixes #210, fixes #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:56:00 -06:00
elforeign 6d7523f5d1 Merge upstream main into test/metal-bc2-bc3
Resolves the CHANGELOG.md conflict with the claim-rules entry; both
entries are kept.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:55:23 -06:00
elforeign cf2d0cfb0b isa, shaders: test that coverage totals and documented counts match FORMS
At 5450612 the generated table held 1,460 forms while the docs and PR
said 1,465; 1493dcf added the five literal-only forms the LLVM oracle
found, so the table, xenora shaders coverage (text and JSON) and docs
now agree on 1,465 across 21 families. Nothing checked that they stay
in step. Test the JSON and text totals and per-family sum against
FORMS and SEMANTIC_FORMS, and the counts stated in docs/research/rdna2.md
and CHANGELOG.md against FORMS.len().

The branch inspection fix for #183 is the previous commit 9640269.

Fixes #183, fixes #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:54:07 -06:00
elforeign 585edd313f metal: upload and read BC4 and BC5 blocks natively
BC4 and BC5 had CPU decoders (#167) but no native Metal path, so nothing
showed that single- and dual-channel blocks reach the GPU and decode as
the specifications describe, signed formats included. This adds a pitched
BcChannelUpload (8-byte BC4 or 16-byte BC5 blocks, sharing the pitch
rules) and NativeCompute::read_bc_channel_upload, which places the blocks
in BC4_R/BC5_RG UNORM or SNORM textures behind the BC capability check.
Signed texels are read back as channel * 127 in two's-complement bytes.

The GPU tests cover six- and eight-value interpolation, equal and extreme
endpoints (stored -128 reads as -1.0, as specified), red-green order,
padded row and slice pitches, two layers and two mips: 232 texels against
the CPU decoders and hand-derived anchors. On an Apple M5 Pro interpolated
codes lie within 1.71 codes of the exact values and two codes of the
truncating CPU reference, which set the tolerances. Uploading SNORM as
UNORM, BC5 as BC4, scaling signed readback by 128 or swapping red and
green each fails the tests.

Refs #169

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:53:30 -06:00
elforeign 69812d97c0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:52:10 -06:00
elforeign 59ee786a12 metal: upload and read BC2 and BC3 blocks natively
BC2 and BC3 had CPU decoders (#167) but no native Metal path, so nothing
showed that the original 16-byte blocks reach the GPU and decode as the
specifications describe. This adds a pitched BcAlphaUpload with the BC1
upload's validation (shared, now measured in 16-byte blocks) and
NativeCompute::read_bc_alpha_upload, which places the blocks in BC2_RGBA
or BC3_RGBA textures behind the existing BC capability check.

The GPU tests cover explicit 4-bit alpha, six- and eight-value
interpolated alpha (equal endpoints included), descending, ascending and
equal colour endpoints, padded row and slice pitches, two layers and two
mips. Texels are compared with the CPU decoders and hand-derived anchors.
On an Apple M5 Pro interpolated values lie within 1.14 codes of the exact
values, two codes at most from the truncating CPU reference, which sets
the tolerance. Uploading BC3 as BC2, BC2 as BC1, or ignoring the row
pitch each fails the tests.

Refs #168

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:49:17 -06:00
elforeign e37c8566c6 agent queue: start runs only for commands and replay cancelled claims
Every pull request comment started the verify job, which gathered state
and re-ran the pull request check, so ordinary review discussion re-ran
verification. Gate the verify job on comments that start with /verified
and the claim job on comments that start with /.

Claim runs share one concurrency group with cancel-in-progress: false.
GitHub keeps one waiting run per group and cancels it when a newer run
queues, so with the run deciding only its own comment, a /claim posted
while another claim was being decided could be dropped without a reply.
Each run now replays every command of the last lease_hours that has no
bot reply, oldest first, updating labels in memory between commands; the
hourly audit does the same, so a cancelled run's command is answered by
the run that replaced it at the latest within the hour. Replies carry a
done marker that counts only from the Actions bot.

The pull request check is advisory until a live smoke test and the
migration of existing issues: problems are a warning and the job passes.

Tests model the concurrency group (the old event-only design loses the
cancelled claim; replay answers all four commands), in-order overlap
decisions, bot-only markers and the workflow triggers.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:46:21 -06:00
elforeign 964026901f shaders: decode inspected instructions at their stream offset
xenora shaders inspect passed each identified instruction to decode() on
its own. decode() checks that every branch target lands on an instruction
in the stream it was given, and a lone branch has no other instruction to
land on, so every supported s_branch and s_cbranch_* was reported as
"unsupported operands" (3 of 15 rows in bitwise-branch.bin).

Add decode_at(), which decodes one instruction at its real stream offset
without the stream-wide target check, and DecodedInstruction::branch_target().
inspect now identifies the whole stream first and checks each branch
target against those boundaries, reporting a bad target separately.
decode() is rebuilt on decode_at() with unchanged behaviour.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:40:55 -06:00
elforeign 98bbe57471 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:58 -06:00
elforeign 5baa630ff0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:51 -06:00
elforeign 1493dcf83b isa: check identification against LLVM and add literal-only forms
The extension-word length rules were written by hand because the XML
gives none, so they needed an outside oracle. An LLVM test now compares
names and lengths for one instruction per family and extension word.
It found five instructions the XML lists only under a literal encoding,
which the first table omitted; they are now base forms that always carry
a literal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:20:26 -06:00
127 changed files with 28262 additions and 1441 deletions

No files matched your search

+1 -1
View File
@@ -25,7 +25,7 @@ Closes #<!-- the issue you claimed -->
## Checklist
- [ ] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
- [ ] I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
+1 -1
View File
@@ -1,5 +1,5 @@
{
"lease_hours": 24,
"lease_hours": 168,
"upstream": "ranveersoni98/Xenora",
"maintainers": ["ranveersoni98"],
"contributors": {
+20 -4
View File
@@ -4,6 +4,13 @@ name: Agent task claims
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
# text is only parsed as data by scripts/agent_queue; it is never executed and
# never interpolated into a shell. Not yet run on GitHub.
#
# Both jobs share one concurrency group, so decisions never race. GitHub keeps
# at most one pending run per group and cancels the older pending run when a
# newer one queues, so a run does not decide only its own comment: `replay`
# decides every command of the last lease_hours that has no bot reply yet,
# oldest first. The surviving run, or at the latest the hourly audit, answers
# the commands of cancelled runs. Comments that do not start with `/` start no run.
on:
issue_comment:
@@ -16,7 +23,7 @@ permissions: {}
jobs:
command:
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request && startsWith(github.event.comment.body, '/')
runs-on: ubuntu-24.04-arm
permissions:
contents: read
@@ -36,9 +43,8 @@ jobs:
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/state.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
audit:
@@ -54,6 +60,16 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide commands whose runs were cancelled
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/commands.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/commands.json" > "$RUNNER_TEMP/replay.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/replay.json"
- name: Lapse stale claims, flag invalid tasks, write summary
env:
GH_TOKEN: ${{ github.token }}
+32 -8
View File
@@ -4,6 +4,11 @@ name: Agent PR checks
# ownership, overlap with other open pull requests, and independent
# verification. Runs on the base branch only: pull request code is never checked
# out or executed; changed files come from the API. Not yet run on GitHub.
#
# Advisory: problems are reported as a warning and in the run summary, but the
# check does not fail until a live smoke test and the migration of existing
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
# with /verified starts the verify job; ordinary comments start nothing.
on:
pull_request_target:
@@ -43,17 +48,21 @@ jobs:
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
exit "$status"
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
verify:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
runs-on: ubuntu-24.04-arm
# issues: write posts the reply; actions: write re-runs the check after a recorded verification.
# issues: write posts the reply.
permissions:
contents: read
issues: write
pull-requests: read
actions: write
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
@@ -61,7 +70,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and re-run the check
- name: Record verification and check again
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
@@ -73,6 +82,21 @@ jobs:
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
sha=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["pr"]["head_sha"])' "$RUNNER_TEMP/state.json")
run=$(gh run list --workflow agent-pr-checks.yml --commit "$sha" --event pull_request_target --limit 1 --json databaseId -q '.[0].databaseId // empty')
if [ -n "$run" ]; then gh run rerun "$run" || true; fi
# Check again only after an accepted verification of the current head: refused, stale,
# malformed or unauthorized /verified comments get a reply and nothing else.
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
# pull_request_target runs are recorded against the base branch, not the pull request
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check after verification'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
+8
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
@@ -46,6 +48,12 @@ jobs:
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
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
+38
View File
@@ -0,0 +1,38 @@
name: PR template
# Fails when a pull request description does not follow
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
# is edited; comments never start it. Runs on the base branch: pull request
# code is never checked out or executed, and the description is read as data.
#
# To make it blocking, mark the "PR template / description" check as required
# in the branch protection rule for main.
on:
pull_request_target:
types: [opened, edited, reopened, synchronize]
permissions: {}
jobs:
description:
runs-on: ubuntu-24.04-arm
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the description against the template
run: |
set -u
status=0
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
cat "$RUNNER_TEMP/result.txt"
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -ne 0 ]; then
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
fi
exit "$status"
+8 -8
View File
@@ -47,16 +47,16 @@ Read docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
Several people and coding agents work on this repository at the same time. An issue with no visible claim is the only signal that a task is free, so claim before you edit anything.
Several people and coding agents work on this repository at the same time. Claim an issue before you edit anything, and never take work someone else has claimed.
1. **Check.** Read the issue's comments, assignees and labels, its linked pull requests, and open pull requests that touch the same files. If someone holds a live claim, pick another task. Do not start parallel work on a claimed task.
2. **Claim.** Comment `/claim` on the issue (or run `scripts/agent-queue.sh claim <n>`). Where the claim workflow is enabled, wait for its grant comment and the `claimed-by:<login>` label; a refusal names the reason. Where it is not enabled yet, your comment is the claim and the earliest valid claim comment wins. One issue per claim; claim follow-up tasks separately.
3. **Respect file ownership.** Two claimed tasks never edit the same files at the same time. If the issue lists files, edit only those; ask the maintainer before widening the list.
4. **Keep it alive.** A claim lapses 24 hours after the latest grant, `/progress <what changed>` comment, or push to the linked pull request. Post `/progress` at least once a day while you work. Lapsed tasks return to the queue and may be claimed by anyone.
5. **Release.** If you stop, comment `/release` so the task returns to the queue. Use `/blocked <reason>` instead if you are waiting on another task.
6. **Link.** Open the pull request from a branch named `task/<n>-<slug>` with `Closes #<n>` in its description.
1. **Check.** Read every comment on the issue and look for open pull requests that link it. A claim is any comment in which someone says they are taking the issue, in any words (for example "I'll take this" or `/claim`). If a claim exists and is not stale (step 4), pick another issue.
2. **Claim.** Reply on the issue in plain words, for example: "I'm taking this. Plan: …". No command, label or bot step is needed. The earliest claim wins. Claim one issue per comment.
3. **Stay in scope.** If the issue lists files, edit only those, and ask on the issue before widening the list. Do not start work that edits the same files as another claimed issue.
4. **Stale claims.** A claim is stale when the claimer has not opened a pull request for the issue within about one week (7 days) of the claim. Only then may someone else take it, by replying on the issue, for example: "Taking this over: @name's claim from <date> has no pull request after 7 days." A claim with an open pull request is never stale; ask the claimer or the maintainer instead.
5. **Release.** If you stop working on an issue, say so on the issue so others can take it.
6. **Link.** Put `Closes #<n>` in the pull request description.
An agent acting for a contributor claims in that contributor's name and must not claim work for areas that contributor may not claim (`.github/agent-queue.json`). Never remove, overwrite or ignore another person's claim; ask the maintainer to `/reassign` instead. See `docs/coordination/agent-tasks.md` when present.
A coding agent claims in the name of the person it works for and follows the same rules. It must read the comments before claiming, and must never claim over, remove or ignore another person's claim. The optional task-queue commands in `docs/coordination/agent-tasks.md` do not replace these rules: a plain-reply claim counts even though the bot does not track it.
## Changelog maintenance
+46
View File
@@ -11,7 +11,51 @@ remains unsupported.
### Added
- 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).
- Added the gfx1030 Wave32 VOPC compares `v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`. VCC_LO is EXEC_LO & the per-lane test, always fully written, so empty EXEC gives 0. A compare result can feed `s_cbranch_vccz`, `v_mov_b32_e32 vN, vcc_lo` and another compare's source; nothing else, so EXEC never becomes data-dependent. A data-dependent `s_cbranch_vccz` is a wave-uniform branch over integer vector ALU code, lowered to a select at the join. The Metal kernel builds each mask by recomputing the 32 lanes of its own RDNA wave, with no SIMD-group, threadgroup or barrier assumption. The reference now runs lockstep Wave32 waves. Verified on an LLVM-assembled fixture plus 251 original programs (boundary operands, partial and empty EXEC, both branch edges, a partial final wave) against exact integer definitions: translator, reference and second interpreter agree on CPU, and all 252 match on native Metal with validation. LLVM agrees on every encoding. VOP3, SDWA, DPP, `v_cmpx` and Wave64 stay rejected. See `docs/shaders/vector-compare.md`.
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: `SEMANTIC_FORMS` lists the forms with semantic decoding (46 as of the VOPC compares).
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
- Added a CPU decoder for a bounded subset of BC6H (signed and unsigned HDR) in
`xenora-texture`: the four single-subset modes (Khronos modes 3, 7, 11 and 15, Microsoft
modes 11 to 14), listed in `BC6H_SUPPORTED_MODES`, plus the reserved modes, which decode to
zero as specified. The ten two-subset modes are rejected with `Bc6hError::UnsupportedMode`
and are not implemented. Tests check hand-derived values and 128 known-answer vectors from a
separate clean-room reference decoder.
- Added native Metal upload and readback of BC4 and BC5 textures (UNORM and SNORM):
`xenora-texture` gains a pitched `BcChannelUpload`, and `NativeCompute::read_bc_channel_upload`
sends the original blocks to `BC4_R*` or `BC5_RG*` textures when the device reports BC
support, failing with `supportsBCTextureCompression` otherwise. GPU tests cover six- and
eight-value interpolation, equal and extreme endpoints (signed -128 reads as -1.0), red-green
channel order, padded row and slice pitches, two layers and two mips against the CPU decoders
and hand-derived anchors. On an Apple M5 Pro interpolated codes were within 1.71 codes of the
exact values and up to two codes from the truncating CPU reference.
Edge levels of 5×3 and 1×1 and invalid payloads (zero extents, short, oversized or
block-count-mismatched buffers) are covered.
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference.
Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents,
short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload,
and `MetalError::is_capability_unavailable` separates a device without BC support from an
implementation failure.
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
@@ -25,11 +69,13 @@ remains unsupported.
### Changed
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
native DBT.
### Fixed
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent
execution test above), so the probe reports no blocker for this program.
+2 -1
View File
@@ -6,7 +6,7 @@ Xenora is an experimental Xbox Series X|S recompilation framework for Apple Sili
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Claim an issue before working on it by commenting `/claim`, and check that nobody else holds a live claim first. Claims lapse after 24 hours without a `/progress` comment or a push; comment `/release` if you stop. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Claim an issue before working on it by replying on it in plain words, after checking its comments for an existing claim. Never claim over someone else. A claim with no pull request after about one week may be taken over with a reply saying so. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
@@ -44,6 +44,7 @@ Before incorporating third-party code, verify per-file license compatibility wit
## Pull requests
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
- Never include secrets, personal paths, credentials or private data in patches or logs.
+55 -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).
---
@@ -327,6 +364,10 @@ Compiling a shader is not equivalent to proving its GPU output is correct.
---
### Contributors
[![Contributors](https://contrib.rocks/image?repo=ranveersoni98/Xenora)](https://github.com/ranveersoni98/Xenora/graphs/contributors)
## License
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
+200 -28
View File
@@ -2,7 +2,7 @@
use std::process::ExitCode;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at};
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
@@ -34,12 +34,19 @@ fn semantic(family: EncodingFamily) -> usize {
/// with their length; "semantic" forms decode into executable instructions.
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
fn coverage(json: bool) -> ExitCode {
print!("{}", coverage_report(json));
ExitCode::SUCCESS
}
fn coverage_report(json: bool) -> String {
use std::fmt::Write as _;
let rows: Vec<_> = meta::inventory()
.into_iter()
.map(|(family, discovered)| (family, discovered, semantic(family)))
.collect();
let total: usize = rows.iter().map(|row| row.1).sum();
let supported: usize = rows.iter().map(|row| row.2).sum();
let mut out = String::new();
if json {
let families: Vec<String> = rows
.iter()
@@ -50,20 +57,31 @@ fn coverage(json: bool) -> ExitCode {
)
})
.collect();
println!(
writeln!(
out,
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
meta::SOURCE_SHA256,
families.join(",")
);
)
.unwrap();
} else {
println!("{:<10} {:>10} {:>9}", "family", "discovered", "semantic");
writeln!(
out,
"{:<10} {:>10} {:>9}",
"family", "discovered", "semantic"
)
.unwrap();
for (family, discovered, semantic) in &rows {
println!("{:<10} {discovered:>10} {semantic:>9}", family.name());
writeln!(out, "{:<10} {discovered:>10} {semantic:>9}", family.name()).unwrap();
}
println!("{:<10} {total:>10} {supported:>9}", "total");
println!("Semantic forms decode for the operand subsets in docs/status.toml only.");
writeln!(out, "{:<10} {total:>10} {supported:>9}", "total").unwrap();
writeln!(
out,
"Semantic forms decode for the operand subsets in docs/status.toml only."
)
.unwrap();
}
ExitCode::SUCCESS
out
}
fn inspect(path: &str) -> ExitCode {
@@ -74,43 +92,197 @@ fn inspect(path: &str) -> ExitCode {
return ExitCode::FAILURE;
}
};
let listing = listing(&bytes);
for row in &listing.rows {
println!("{row}");
}
if let Some(failure) = listing.failure {
println!("{failure}");
return ExitCode::FAILURE;
}
println!(
"{} instructions inspected against {} gfx1030 forms; {} without semantic decoding",
listing.rows.len(),
FORMS.len(),
listing.unsupported
);
ExitCode::SUCCESS
}
/// The printed rows of `xenora shaders inspect`, the number of rows that do
/// not decode into executable instructions and the identification failure
/// that ended the stream early, if any.
struct Listing {
rows: Vec<String>,
unsupported: usize,
failure: Option<String>,
}
fn listing(bytes: &[u8]) -> Listing {
let mut listing = Listing {
rows: Vec::new(),
unsupported: 0,
failure: None,
};
// Identify every instruction first: a branch target is valid only if it
// lands on one of these boundaries, which no single instruction can show.
let mut forms = Vec::new();
let mut offset = 0;
let mut unsupported = 0;
let mut count = 0;
while offset < bytes.len() {
let found = match identify(&bytes[offset..]) {
Ok(found) => found,
Err(error) => {
println!("{offset:#06x} decode failure: {error}");
return ExitCode::FAILURE;
match identify(&bytes[offset..]) {
Ok(found) => {
forms.push((offset, found));
offset += found.len;
}
};
let words: Vec<String> = bytes[offset..offset + found.len]
Err(error) => {
listing.failure = Some(format!("{offset:#06x} decode failure: {error}"));
break;
}
}
}
let boundary = |target: usize| forms.binary_search_by_key(&target, |form| form.0).is_ok();
// Past the last identified instruction the boundaries are unknown.
let identified = forms
.last()
.map_or(0, |&(offset, found)| offset + found.len);
for &(offset, found) in &forms {
let instruction = &bytes[offset..offset + found.len];
let words: Vec<String> = instruction
.chunks(4)
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
.collect();
let status = match decode(Architecture::Gfx1030, &bytes[offset..offset + found.len]) {
Ok(_) => "semantic".to_owned(),
let status = match decode_at(Architecture::Gfx1030, &bytes[..offset + found.len], offset) {
Ok(decoded) => match decoded.branch_target() {
Some(target) if listing.failure.is_some() && target >= identified => {
format!("branch target {target:#04x} unverified: stream not identified there")
}
Some(target) if !boundary(target) => {
format!("invalid branch target {target:#04x}")
}
_ => "semantic".to_owned(),
},
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
format!("unsupported operands: {error}")
}
Err(_) => "unsupported instruction semantics".to_owned(),
};
if status != "semantic" {
unsupported += 1;
listing.unsupported += 1;
}
println!(
listing.rows.push(format!(
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
found.form.family.name(),
found.form.name.to_ascii_lowercase(),
words.join(" ")
));
}
listing
}
#[cfg(test)]
mod tests {
use super::{coverage_report, listing};
use xenora_decoder::SEMANTIC_FORMS;
use xenora_isa::meta::{EncodingFamily, FORMS};
#[test]
fn coverage_totals_match_the_generated_table() {
let json = coverage_report(true);
assert!(json.starts_with("{\"architecture\":\"gfx1030\""), "{json}");
assert!(json.ends_with("}]}\n"), "{json}");
assert_eq!(json.matches('{').count(), json.matches('}').count());
let totals = format!(
"\"discovered\":{},\"semantic\":{},\"families\":[",
FORMS.len(),
SEMANTIC_FORMS.len()
);
offset += found.len;
count += 1;
assert!(json.contains(&totals), "{json}");
let families: Vec<usize> = json
.split("{\"family\":")
.skip(1)
.map(|row| {
let count = row.split("\"discovered\":").nth(1).unwrap();
count[..count.find(',').unwrap()].parse().unwrap()
})
.collect();
assert_eq!(families.len(), EncodingFamily::ALL.len());
assert_eq!(families.iter().sum::<usize>(), FORMS.len());
let text = coverage_report(false);
let total = format!(
"{:<10} {:>10} {:>9}\n",
"total",
FORMS.len(),
SEMANTIC_FORMS.len()
);
assert!(text.contains(&total), "{text}");
}
fn program(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
#[test]
fn branches_in_a_valid_program_are_semantic() {
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
let listing = listing(fixture);
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 15);
let branches: Vec<_> = listing
.rows
.iter()
.filter(|row| row.contains("branch"))
.collect();
assert_eq!(branches.len(), 3);
for row in &branches {
assert!(row.ends_with(" semantic"), "{row}");
}
assert_eq!(listing.unsupported, 0);
}
#[test]
fn targets_past_an_identification_failure_are_unverified() {
// s_branch 1 targets 0x08; 0xbfff0000 is not a gfx1030 form, so
// nothing past 0x04 is identified; s_endpgm.
let listing = listing(&program(&[0xbf82_0001, 0xbfff_0000, 0xbf81_0000]));
assert!(listing.failure.as_deref().unwrap().starts_with("0x0004"));
assert_eq!(listing.rows.len(), 1);
assert!(
listing.rows[0].ends_with("branch target 0x08 unverified: stream not identified there"),
"{}",
listing.rows[0]
);
}
#[test]
fn add_fixture_is_fully_semantic() {
let listing = listing(include_bytes!("../../../fixtures/rdna2/add.bin"));
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 7);
assert_eq!(listing.unsupported, 0);
}
#[test]
fn branch_targets_are_checked_against_the_whole_stream() {
// s_branch 1 skips one word; s_cbranch_scc0 1 lands inside the
// two-word v_mov_b32 literal form; s_endpgm.
let listing = listing(&program(&[
0xbf82_0001,
0xbf84_0001,
0x7e04_02ff,
0x00ff_00ff,
0xbf81_0000,
]));
assert_eq!(listing.failure, None);
assert!(
listing.rows[0].ends_with(" semantic"),
"{}",
listing.rows[0]
);
assert!(
listing.rows[1].ends_with("invalid branch target 0x0c"),
"{}",
listing.rows[1]
);
assert_eq!(listing.unsupported, 1);
}
println!(
"{count} instructions inspected against {} gfx1030 forms; {unsupported} not executable",
FORMS.len()
);
ExitCode::SUCCESS
}
+180 -22
View File
@@ -3,21 +3,45 @@
use std::fmt;
pub use xenora_isa::{
Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource,
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarSource, VectorCompareOp, VectorSource,
};
use xenora_isa::{
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_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,
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, VCC_LO,
};
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); 25] = [
/// 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),
@@ -35,6 +59,18 @@ pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [
("V_ADD_NC_U32", EncodingFamily::Vop3),
("V_AND_B32", EncodingFamily::Vop2),
("V_ASHRREV_I32", EncodingFamily::Vop2),
("V_CMP_EQ_I32", EncodingFamily::Vopc),
("V_CMP_EQ_U32", EncodingFamily::Vopc),
("V_CMP_GE_I32", EncodingFamily::Vopc),
("V_CMP_GE_U32", EncodingFamily::Vopc),
("V_CMP_GT_I32", EncodingFamily::Vopc),
("V_CMP_GT_U32", EncodingFamily::Vopc),
("V_CMP_LE_I32", EncodingFamily::Vopc),
("V_CMP_LE_U32", EncodingFamily::Vopc),
("V_CMP_LT_I32", EncodingFamily::Vopc),
("V_CMP_LT_U32", EncodingFamily::Vopc),
("V_CMP_NE_I32", EncodingFamily::Vopc),
("V_CMP_NE_U32", EncodingFamily::Vopc),
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
("V_LSHLREV_B32", EncodingFamily::Vop2),
@@ -56,6 +92,20 @@ pub struct DecodedInstruction {
pub instruction: Instruction,
}
impl DecodedInstruction {
/// Destination byte offset of a branch, from the start of the stream.
#[must_use]
pub fn branch_target(&self) -> Option<usize> {
match self.instruction {
Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } => Some(target),
_ => None,
}
}
}
impl fmt::Display for DecodedInstruction {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
@@ -140,26 +190,15 @@ pub fn decode(
architecture: Architecture,
bytes: &[u8],
) -> Result<Vec<DecodedInstruction>, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let mut result = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset)
.map_err(|kind| DecodeError { offset, kind })?;
result.push(DecodedInstruction {
offset,
byte_len,
instruction,
});
offset += usize::from(byte_len);
let decoded = decode_at(architecture, bytes, offset)?;
offset += usize::from(decoded.byte_len);
result.push(decoded);
}
for decoded in &result {
if let Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } = decoded.instruction
if let Some(target) = decoded.branch_target()
&& result
.binary_search_by_key(&target, |item| item.offset)
.is_err()
@@ -173,6 +212,32 @@ pub fn decode(
Ok(result)
}
/// Decodes the one instruction that starts at `offset` in `bytes`. Branch
/// targets are stream offsets, but whether they land on an instruction
/// boundary is left to the caller, which knows the rest of the stream.
///
/// # Errors
///
/// Returns `offset` with a truncated instruction, unsupported opcode or
/// unsupported form. An `offset` at or past the end is truncated.
pub fn decode_at(
architecture: Architecture,
bytes: &[u8],
offset: usize,
) -> Result<DecodedInstruction, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let rest = bytes.get(offset..).unwrap_or_default();
let (instruction, byte_len) =
decode_instruction(rest, offset).map_err(|kind| DecodeError { offset, kind })?;
Ok(DecodedInstruction {
offset,
byte_len,
instruction,
})
}
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
let end_index = usize::from(end);
let Some(word) = bytes
@@ -273,6 +338,27 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
{
use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
for (opcode, relation, signed) in [
(V_CMP_LT_I32, Less, true),
(V_CMP_EQ_I32, Equal, true),
(V_CMP_LE_I32, LessOrEqual, true),
(V_CMP_GT_I32, Greater, true),
(V_CMP_NE_I32, NotEqual, true),
(V_CMP_GE_I32, GreaterOrEqual, true),
(V_CMP_LT_U32, Less, false),
(V_CMP_EQ_U32, Equal, false),
(V_CMP_LE_U32, LessOrEqual, false),
(V_CMP_GT_U32, Greater, false),
(V_CMP_NE_U32, NotEqual, false),
(V_CMP_GE_U32, GreaterOrEqual, false),
] {
if opcode.matches(first) {
return vector_compare(VectorCompareOp { relation, signed }, first, bytes);
}
}
}
if V_ADD_NC_U32.matches(first) {
let len = V_ADD_NC_U32.byte_len();
let second = word(bytes, len)?;
@@ -309,6 +395,9 @@ 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()));
}
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")?;
return Ok((
@@ -417,6 +506,39 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
}
/// SOP2: SSRC0 in bits 0-7, SSRC1 in bits 8-15, SDST in bits 16-22.
/// Other SOP2 opcodes stay unsupported.
fn scalar_alu(
op: ScalarAluOp,
first: u32,
bytes: &[u8],
) -> Result<(Instruction, u8), DecodeErrorKind> {
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
mnemonic,
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
Ok((
Instruction::ScalarAlu {
op,
dst,
src0,
src1,
},
len0.max(len1),
))
}
fn scalar_source(
bits: u8,
bytes: &[u8],
@@ -558,11 +680,47 @@ fn buffer_operands(
Ok((data, index, resource))
}
/// VOPC: SRC0 in bits 0-8, VSRC1 in bits 9-16 (RDNA 2 ISA section 12.9). The
/// destination is implicitly `vcc_lo`. SRC0 excludes inline float constants,
/// `vcc_hi`, EXEC, M0, TTMPs and the condition selectors (SDWA 249, DPP 250/233).
fn vector_compare(
op: VectorCompareOp,
first: u32,
bytes: &[u8],
) -> Result<(Instruction, u8), DecodeErrorKind> {
let source = first & 0x1ff;
let src1 = ((first >> 9) & 0xff) as u8;
let base_len = 4;
let (src0, len) = match source {
0..=106 => (VectorSource::Scalar(source as u8), base_len),
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
VectorSource::Immediate(192u32.wrapping_sub(source)),
base_len,
),
255 => {
let len = base_len + 4;
(VectorSource::Immediate(word(bytes, len)?), len)
}
256..=511 => (VectorSource::Register(source as u8), base_len),
_ => {
return Err(unsupported(
op.mnemonic(),
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
));
}
};
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
}
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
let dst = (first >> 17) as u8;
let source = first & 0x1ff;
let base_len = V_MOV_B32.byte_len();
let (src, len) = match source {
0..=105 => (VectorSource::Scalar(source as u8), base_len),
// vcc_lo, which may hold a lane-derived compare mask (docs/shaders/vector-compare.md).
106 => (VectorSource::Scalar(VCC_LO), base_len),
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
VectorSource::Immediate(192u32.wrapping_sub(source)),
@@ -578,7 +736,7 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
_ => {
return Err(unsupported(
"v_mov_b32_e32",
"expected a VGPR, inline integer, inline +1.0f or literal",
"expected a VGPR, normal SGPR, vcc_lo, inline integer, inline +1.0f or literal",
));
}
};
+154 -7
View File
@@ -3,10 +3,10 @@ use std::path::PathBuf;
use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource,
VectorSource, decode,
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
};
use xenora_ref::{BranchCondition, Op, Source, VectorAlu};
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
@@ -97,7 +97,12 @@ fn rejects_other_opcodes_and_noncanonical_operands() {
(&[0xe070_2000, 0x801b_0100], "buffer_store_dword"),
(&[0xbf8c_3f71], "s_waitcnt"),
(&[0xbbfd_0001], "s_waitcnt_vscnt"),
(&[0x7e04_0200], "v_mov_b32_e32"),
(&[0x7e04_026b], "v_mov_b32_e32"), // VCC_HI is outside the source subset.
(&[0x7d02_046b], "v_cmp_lt_i32_e32"), // VCC_HI source.
(&[0x7d02_047e], "v_cmp_lt_i32_e32"), // EXEC_LO source.
(&[0x7d02_04f0], "v_cmp_lt_i32_e32"), // Inline 0.5 source.
(&[0x7d84_04f9, 0x0606_0601], "v_cmp_eq_u32_e32"), // SDWA.
(&[0x7d84_04fa, 0], "v_cmp_eq_u32_e32"), // DPP16.
(&[0x7e04_02fa, 0], "v_mov_b32_e32"),
(&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"),
(&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"),
@@ -281,6 +286,7 @@ fn reference_source(vector: VectorSource) -> Source {
match vector {
VectorSource::Register(reg) => Source::Register(reg),
VectorSource::Immediate(bits) => Source::Immediate(bits),
VectorSource::Scalar(_) => unreachable!("mapped to Op::MoveScalar"),
}
}
@@ -313,7 +319,32 @@ fn reference_op(instruction: Instruction) -> Op {
},
Instruction::WaitLoad => Op::WaitRead,
Instruction::WaitStore => Op::WaitWrite,
Instruction::MoveB32 {
dst,
src: VectorSource::Scalar(src),
} => Op::MoveScalar(dst, src),
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
Instruction::ScalarAlu {
op,
dst,
src0,
src1,
} => Op::Scalar(
match op {
ScalarAluOp::AddU32 => ScalarAlu::Add,
ScalarAluOp::SubU32 => ScalarAlu::Subtract,
ScalarAluOp::AddI32 => ScalarAlu::AddSigned,
ScalarAluOp::SubI32 => ScalarAlu::SubtractSigned,
ScalarAluOp::AddcU32 => ScalarAlu::AddWithCarry,
ScalarAluOp::SubbU32 => ScalarAlu::SubtractWithBorrow,
ScalarAluOp::AndB32 => ScalarAlu::And,
ScalarAluOp::OrB32 => ScalarAlu::Or,
ScalarAluOp::XorB32 => ScalarAlu::Xor,
},
dst,
reference_scalar(src0),
reference_scalar(src1),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
Instruction::ScalarCompareEqU32 { src0, src1 } => {
@@ -363,6 +394,25 @@ fn reference_op(instruction: Instruction) -> Op {
panic!("compute reference matrix received a graphics/image instruction")
}
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
Comparison {
offset: match op.relation {
CompareRelation::Less => 1,
CompareRelation::Equal => 2,
CompareRelation::LessOrEqual => 3,
CompareRelation::Greater => 4,
CompareRelation::NotEqual => 5,
CompareRelation::GreaterOrEqual => 6,
},
signed: op.signed,
},
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
src1,
),
Instruction::EndProgram => Op::End,
}
}
@@ -383,12 +433,14 @@ fn compares_fixture_instructions_against_llvm() {
OR_FIXTURE,
SHIFT_FIXTURE,
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 21, "forms compared: {forms:?}");
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -396,6 +448,7 @@ fn compares_fixture_instructions_against_llvm() {
}
fn assemble_matrix() -> Vec<u8> {
use std::fmt::Write as _;
// Cover register banks and extrema, immediate classes in both scalar
// compare positions, zero displacement and branches over literal words.
let mut assembly = String::from(
@@ -433,13 +486,48 @@ fn assemble_matrix() -> Vec<u8> {
v_mov_b32_e32 v255, lit(0x1)
s_mov_b32 s105, lit(0x1)
s_cmp_eq_u32 s105, lit(0x1)
s_add_u32 s105, s104, 0xdeadbeef
s_add_u32 s8, -16, 64
s_sub_u32 s105, s1, s2
s_sub_u32 s9, 0xdeadbeef, -16
s_addc_u32 s104, 0xdeadbeef, s105
s_subb_u32 s0, s0, s0
s_add_i32 s101, 0x7fffffff, s100
s_sub_i32 s100, -16, 0x80000000
s_and_b32 s1, -1, s2
s_or_b32 s103, s3, 0x80000000
s_xor_b32 s102, s104, -16
s_xor_b32 s7, s7, lit(0x1)
v_mov_b32_e32 v255, s105
v_mov_b32_e32 v0, s0
v_mov_b32_e32 v128, vcc_lo
",
);
use std::fmt::Write as _;
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
// inline integers at both ends, inline zero and a literal.
for relation in ["lt", "eq", "le", "gt", "ne", "ge"] {
for kind in ["i32", "u32"] {
for src0 in [
"v255",
"v0",
"s0",
"s105",
"vcc_lo",
"-16",
"64",
"0",
"0x80000000",
] {
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, {src0}, v128").unwrap();
}
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
}
}
for value in -16..=64 {
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
writeln!(assembly, "s_cmp_eq_u32 {value}, {value}").unwrap();
writeln!(assembly, "s_add_u32 s10, {value}, s11").unwrap();
}
assembly.push_str("s_endpgm\n");
let output = llvm_mc(&[], assembly.as_bytes());
@@ -563,7 +651,17 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
&[0xd516_0001],
];
let outside_subset: &[&[u32]] = &[
&[0x7e04_0200], // VOP1 SGPR source
&[0x7e04_026b], // VOP1 VCC_HI source
&[0x7da2_0501], // v_cmpx_eq_u32_e32
&[0x7d00_0501], // v_cmp_f_i32_e32
&[0x7d0e_0501], // v_cmp_t_i32_e32
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
&[0x8788_0908], // s_and_b64
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
&[0x806c_0908], // SOP2 TTMP destination
&[0x807e_0908], // SOP2 EXEC_LO destination
&[0x806a_0908], // SOP2 VCC_LO destination
&[0x8008_096a], // SOP2 VCC_LO source
&[0x3803_fe80], // OR with an inline SRC0
&[0x3803_fe08], // OR with an SGPR SRC0
&[0x3803_feff, 0xdead_beef], // OR with a literal SRC0
@@ -626,6 +724,17 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
let target = next_offset + displacement * 4;
format!("{mnemonic} -> 0x{target:04x}")
}
mnemonic if mnemonic.starts_with("v_cmp_") => {
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
parts[1] = match literal_bits(&parts[1]) {
Some(bits) => format!("0x{bits:x}"),
None => parts[1].parse::<i32>().map_or_else(
|_| parts[1].clone(),
|value| format!("0x{:x}", value as u32),
),
};
format!("{mnemonic} {}", parts.join(", "))
}
"v_mov_b32_e32" => {
let (destination, source) = operands.split_once(", ").unwrap();
let normalized = match source {
@@ -651,6 +760,18 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
};
format!("{mnemonic} {}, {}", scalar(left), scalar(right))
}
"s_add_u32" | "s_sub_u32" | "s_add_i32" | "s_sub_i32" | "s_addc_u32" | "s_subb_u32"
| "s_and_b32" | "s_or_b32" | "s_xor_b32" => {
let scalar = |operand: &str| match literal_bits(operand) {
Some(bits) => match bits as i32 {
inline @ -16..=64 => inline.to_string(),
_ => format!("0x{bits:x}"),
},
None => operand.to_owned(),
};
let operands: Vec<_> = operands.split(", ").map(scalar).collect();
format!("{mnemonic} {}", operands.join(", "))
}
_ => assembly.to_owned(),
}
}
@@ -786,3 +907,29 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
}
);
}
#[test]
fn decode_at_resolves_branch_targets_from_the_stream_offset() {
let decoded = decode_at(Architecture::Gfx1030, BITWISE_FIXTURE, 0x1c).unwrap();
assert_eq!(decoded.offset, 0x1c);
assert_eq!(decoded.byte_len, 4);
assert_eq!(decoded.branch_target(), Some(0x3c));
// Alone, the same branch still reports its stream target; only the whole
// stream can say whether that target is an instruction boundary.
let isolated = decode_at(Architecture::Gfx1030, &BITWISE_FIXTURE[..0x20], 0x1c).unwrap();
assert_eq!(isolated.branch_target(), Some(0x3c));
assert_eq!(
decode_at(
Architecture::Gfx1030,
BITWISE_FIXTURE,
BITWISE_FIXTURE.len()
),
Err(DecodeError {
offset: BITWISE_FIXTURE.len(),
kind: DecodeErrorKind::Truncated {
needed: 4,
available: 0
},
})
);
}
+1 -4
View File
@@ -39,10 +39,7 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
.difference(&decoded)
.map(|(name, _)| *name)
.collect();
assert_eq!(
inline_only,
BTreeSet::from(["IMAGE_SAMPLE_LZ", "S_CBRANCH_EXECZ", "S_CBRANCH_VCCZ"])
);
assert_eq!(inline_only, BTreeSet::from(["IMAGE_SAMPLE_LZ"]));
for (name, family) in SEMANTIC_FORMS {
assert!(
FORMS
+5 -5
View File
@@ -2243,7 +2243,7 @@
{"condition":"has_lit_0","encoding":"SOPC_INST_LITERAL","instruction":"S_CMP_LT_U32","kind":"variant","opcode":10}
{"condition":"has_lit_0_has_lit_1","encoding":"SOPC_INST_LITERAL","instruction":"S_CMP_LT_U32","kind":"variant","opcode":10}
{"condition":"has_lit_1","encoding":"SOPC_INST_LITERAL","instruction":"S_CMP_LT_U32","kind":"variant","opcode":10}
{"condition":"default","encoding":"SOPK_INST_LITERAL","instruction":"S_SETREG_IMM32_B32","kind":"variant","opcode":21}
{"condition":"default","encoding":"SOPK_INST_LITERAL","flags":[],"group":"SALU","instruction":"S_SETREG_IMM32_B32","kind":"variant","opcode":21,"operands":[["SIMM16","FMT_NUM_B16","OPR_HWREG",16,false,true,false,true],["LITERAL","FMT_NUM_B32","OPR_SIMM32",32,true,false,false,true]],"subgroups":["NOT_ASSIGNED"]}
{"condition":"has_lit","encoding":"VOP1_INST_LITERAL","instruction":"V_BFREV_B32","kind":"variant","opcode":56}
{"condition":"has_lit","encoding":"VOP1_INST_LITERAL","instruction":"V_CEIL_F16","kind":"variant","opcode":92}
{"condition":"has_lit","encoding":"VOP1_INST_LITERAL","instruction":"V_CEIL_F32","kind":"variant","opcode":34}
@@ -2503,16 +2503,16 @@
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_CVT_PKRTZ_F16_F32","kind":"variant","opcode":47}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_DOT2C_F32_F16","kind":"variant","opcode":2}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_DOT4C_I32_I8","kind":"variant","opcode":13}
{"condition":"default","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAAK_F16","kind":"variant","opcode":56}
{"condition":"default","encoding":"VOP2_INST_LITERAL","flags":[],"group":"VALU","instruction":"V_FMAAK_F16","kind":"variant","opcode":56,"operands":[["VDST","FMT_NUM_F16","OPR_VGPR",16,false,true,false,true],["SRC0","FMT_NUM_F16","OPR_SRC",16,true,false,false,true],["VSRC1","FMT_NUM_F16","OPR_VGPR",16,true,false,false,true],["LITERAL","FMT_NUM_F16","OPR_SIMM16",16,true,false,false,true]],"subgroups":["NOT_ASSIGNED"]}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAAK_F16","kind":"variant","opcode":56}
{"condition":"default","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAAK_F32","kind":"variant","opcode":45}
{"condition":"default","encoding":"VOP2_INST_LITERAL","flags":[],"group":"VALU","instruction":"V_FMAAK_F32","kind":"variant","opcode":45,"operands":[["VDST","FMT_NUM_F32","OPR_VGPR",32,false,true,false,true],["SRC0","FMT_NUM_F32","OPR_SRC",32,true,false,false,true],["VSRC1","FMT_NUM_F32","OPR_VGPR",32,true,false,false,true],["LITERAL","FMT_NUM_F32","OPR_SIMM32",32,true,false,false,true]],"subgroups":["NOT_ASSIGNED"]}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAAK_F32","kind":"variant","opcode":45}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAC_F16","kind":"variant","opcode":54}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAC_F32","kind":"variant","opcode":43}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAC_LEGACY_F32","kind":"variant","opcode":6}
{"condition":"default","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAMK_F16","kind":"variant","opcode":55}
{"condition":"default","encoding":"VOP2_INST_LITERAL","flags":[],"group":"VALU","instruction":"V_FMAMK_F16","kind":"variant","opcode":55,"operands":[["VDST","FMT_NUM_F16","OPR_VGPR",16,false,true,false,true],["SRC0","FMT_NUM_F16","OPR_SRC",16,true,false,false,true],["LITERAL","FMT_NUM_F16","OPR_SIMM16",16,true,false,false,true],["VSRC1","FMT_NUM_F16","OPR_VGPR",16,true,false,false,true]],"subgroups":["NOT_ASSIGNED"]}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAMK_F16","kind":"variant","opcode":55}
{"condition":"default","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAMK_F32","kind":"variant","opcode":44}
{"condition":"default","encoding":"VOP2_INST_LITERAL","flags":[],"group":"VALU","instruction":"V_FMAMK_F32","kind":"variant","opcode":44,"operands":[["VDST","FMT_NUM_F32","OPR_VGPR",32,false,true,false,true],["SRC0","FMT_NUM_F32","OPR_SRC",32,true,false,false,true],["LITERAL","FMT_NUM_F32","OPR_SIMM32",32,true,false,false,true],["VSRC1","FMT_NUM_F32","OPR_VGPR",32,true,false,false,true]],"subgroups":["NOT_ASSIGNED"]}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_FMAMK_F32","kind":"variant","opcode":44}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_LDEXP_F16","kind":"variant","opcode":59}
{"condition":"has_lit","encoding":"VOP2_INST_LITERAL","instruction":"V_LSHLREV_B32","kind":"variant","opcode":26}
+12
View File
@@ -30,6 +30,18 @@ VARIANTS = (
("V_XOR_B32", "ENC_VOP2"),
("V_ADD_F32", "ENC_VOP2"),
("V_MUL_F32", "ENC_VOP2"),
("V_CMP_LT_I32", "ENC_VOPC"),
("V_CMP_EQ_I32", "ENC_VOPC"),
("V_CMP_LE_I32", "ENC_VOPC"),
("V_CMP_GT_I32", "ENC_VOPC"),
("V_CMP_NE_I32", "ENC_VOPC"),
("V_CMP_GE_I32", "ENC_VOPC"),
("V_CMP_LT_U32", "ENC_VOPC"),
("V_CMP_EQ_U32", "ENC_VOPC"),
("V_CMP_LE_U32", "ENC_VOPC"),
("V_CMP_GT_U32", "ENC_VOPC"),
("V_CMP_NE_U32", "ENC_VOPC"),
("V_CMP_GE_U32", "ENC_VOPC"),
("EXP", "ENC_EXP"),
("V_INTERP_P1_F32", "ENC_VINTRP"),
("V_INTERP_P2_F32", "ENC_VINTRP"),
+16 -5
View File
@@ -204,7 +204,7 @@ def snapshot_from_xml(data):
}
# Extension variants keep only what classifies them; their
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
if encoding_name in BASE_ENCODINGS:
if encoding_name in BASE_ENCODINGS or condition == "default":
record.update({
"flags": sorted(flag for flag, value in flags.items() if value),
"group": text(group, "Name"),
@@ -256,22 +256,33 @@ def forms_from_snapshot(snapshot):
entry.add("always_literal")
entry.add(kind)
based = {(variant["instruction"], variant["encoding"]) for variant in variants if variant["encoding"] in BASE_ENCODINGS}
forms = []
for variant in variants:
encoding_name = variant["encoding"]
if encoding_name not in BASE_ENCODINGS:
identity = encoding_name
if encoding_name in EXTENSIONS:
# A few instructions exist only with a literal (S_SETREG_IMM32_B32,
# V_FMAMK_F32, ...): the XML lists them under the literal encoding's
# default condition and gives them no base variant.
base, kind = EXTENSIONS[encoding_name]
if kind != "literal" or variant["condition"] != "default" or (variant["instruction"], base) in based:
continue
encoding_name = base
elif encoding_name not in BASE_ENCODINGS:
continue
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
encoding = encodings[encoding_name]
id_encoding = encodings[identity]
fields = dict((name, ranges) for name, ranges in encoding["fields"])
prefix_mask, _ = place(0, fields["ENCODING"])
prefixes = {identifier & prefix_mask for identifier in encoding["identifiers"]}
prefixes = {identifier & prefix_mask for identifier in id_encoding["identifiers"]}
if len(prefixes) != 1:
fail(f"{encoding_name} has an ambiguous encoding prefix")
prefix = prefixes.pop()
id_mask = encoding["identifier_mask"]
id_mask = id_encoding["identifier_mask"] & 0xFFFFFFFF
opcode = variant["opcode"]
if "OP" in fields:
op_mask, op_bits = place(opcode, fields["OP"])
@@ -285,7 +296,7 @@ def forms_from_snapshot(snapshot):
# first-dword identifiers cannot express; carry it separately.
low = 0xFFFFFFFF
candidates = sorted({
identifier for identifier in encoding["identifiers"]
identifier & 0xFFFFFFFF for identifier in id_encoding["identifiers"]
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
})
if len(candidates) != 1:
+541
View File
@@ -0,0 +1,541 @@
#!/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"}
LOGICAL = {"and", "or", "xor"}
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),
}
# 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"]]
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")
signed_format = data_format.startswith("FMT_NUM_I")
if is_source and signed_format != (form["signedness"] == "signed"):
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)
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["signedness"] == "bitwise") != (form["operation"] in LOGICAL):
errors.append(
f"{label}: signedness {form['signedness']} contradicts operation {form['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" 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"]
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']},",
]
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 (mask 0x{mask:09_x}).",
" pub const fn from_word(word: u32) -> Option<Self> {",
f" match word & 0x{mask:09_x} {{",
]
for form in sorted(forms, key=lambda item: item["opcode"]):
out.append(f" 0x{_identifier(encoding, form['opcode']):09_x} => Some(Self::{form['variant']}),")
out += [
" _ => None,",
" }",
" }",
"",
" /// 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})"
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())
+232
View File
@@ -0,0 +1,232 @@
# 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"]
+131 -9
View File
@@ -3,15 +3,25 @@
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_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_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,
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;
/// Selects the instruction encoding independently of the container and execution ABI.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -45,6 +55,8 @@ impl Opcode {
pub enum VectorSource {
/// VGPR index.
Register(u8),
/// Normal SGPR index (s0-s105) or `vcc_lo` (106), read as a wave-uniform value.
Scalar(u8),
/// Inline integer or literal word, represented by its bits.
Immediate(u32),
}
@@ -53,6 +65,8 @@ impl fmt::Display for VectorSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Register(register) => write!(formatter, "v{register}"),
Self::Scalar(VCC_LO) => formatter.write_str("vcc_lo"),
Self::Scalar(register) => write!(formatter, "s{register}"),
Self::Immediate(value) => write!(formatter, "0x{value:x}"),
}
}
@@ -79,6 +93,81 @@ impl fmt::Display for ScalarSource {
}
}
/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareRelation {
/// S0 < S1 (opcode offset 1).
Less,
/// S0 == S1 (offset 2).
Equal,
/// S0 <= S1 (offset 3).
LessOrEqual,
/// S0 > S1 (offset 4).
Greater,
/// S0 != S1 (offset 5).
NotEqual,
/// S0 >= S1 (offset 6).
GreaterOrEqual,
}
/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands.
///
/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and
/// the pinned XML descriptions. VCC and EXEC rules are in
/// docs/shaders/vector-compare.md.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct VectorCompareOp {
/// The tested relation.
pub relation: CompareRelation,
/// `_i32` (two's complement) when true, `_u32` when false.
pub signed: bool,
}
impl VectorCompareOp {
/// Lower-case mnemonic of the 32-bit VOPC encoding.
pub fn mnemonic(self) -> &'static str {
const SIGNED: [&str; 6] = [
"v_cmp_lt_i32_e32",
"v_cmp_eq_i32_e32",
"v_cmp_le_i32_e32",
"v_cmp_gt_i32_e32",
"v_cmp_ne_i32_e32",
"v_cmp_ge_i32_e32",
];
const UNSIGNED: [&str; 6] = [
"v_cmp_lt_u32_e32",
"v_cmp_eq_u32_e32",
"v_cmp_le_u32_e32",
"v_cmp_gt_u32_e32",
"v_cmp_ne_u32_e32",
"v_cmp_ge_u32_e32",
];
let index = self.relation as usize;
if self.signed {
SIGNED[index]
} else {
UNSIGNED[index]
}
}
/// The per-lane test result for operand bits S0 and S1.
pub fn test(self, src0: u32, src1: u32) -> bool {
let ordering = if self.signed {
(src0 as i32).cmp(&(src1 as i32))
} else {
src0.cmp(&src1)
};
match self.relation {
CompareRelation::Less => ordering.is_lt(),
CompareRelation::Equal => ordering.is_eq(),
CompareRelation::LessOrEqual => ordering.is_le(),
CompareRelation::Greater => ordering.is_gt(),
CompareRelation::NotEqual => ordering.is_ne(),
CompareRelation::GreaterOrEqual => ordering.is_ge(),
}
}
}
/// Output targeted by a supported uncompressed four-component export.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExportTarget {
@@ -120,11 +209,25 @@ pub enum Instruction {
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
ScalarAlu {
op: ScalarAluOp,
dst: u8,
src0: ScalarSource,
src1: ScalarSource,
},
/// SOPC 32-bit equality comparison writing SCC.
ScalarCompareEqU32 {
src0: ScalarSource,
src1: ScalarSource,
},
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
VectorCompare {
op: VectorCompareOp,
src0: VectorSource,
src1: u8,
},
/// SOPP jump to a stream byte offset when SCC is clear.
BranchSccZero { target: usize },
/// SOPP jump when the Wave32 execution mask is empty.
@@ -177,6 +280,21 @@ pub enum Instruction {
EndProgram,
}
/// Formats an SGPR destination with LLVM's names for the EXEC and VCC halves.
struct ScalarDestination(u8);
impl fmt::Display for ScalarDestination {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
106 => formatter.write_str("vcc_lo"),
107 => formatter.write_str("vcc_hi"),
126 => formatter.write_str("exec_lo"),
127 => formatter.write_str("exec_hi"),
register => write!(formatter, "s{register}"),
}
}
}
impl Instruction {
/// Returns the mnemonic for the exact encoding family represented.
pub fn mnemonic(self) -> &'static str {
@@ -188,7 +306,9 @@ impl Instruction {
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarAlu { op, .. } => op.mnemonic(),
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
Self::VectorCompare { op, .. } => op.mnemonic(),
Self::BranchSccZero { .. } => "s_cbranch_scc0",
Self::BranchExecZero { .. } => "s_cbranch_execz",
Self::BranchVccZero { .. } => "s_cbranch_vccz",
@@ -250,14 +370,16 @@ impl fmt::Display for Instruction {
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } => match dst {
106 => write!(formatter, " vcc_lo, {src}"),
107 => write!(formatter, " vcc_hi, {src}"),
126 => write!(formatter, " exec_lo, {src}"),
127 => write!(formatter, " exec_hi, {src}"),
_ => write!(formatter, " s{dst}, {src}"),
},
Self::ScalarMoveB32 { dst, src } => {
write!(formatter, " {}, {src}", ScalarDestination(dst))
}
Self::ScalarAlu {
dst, src0, src1, ..
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
Self::VectorCompare { src0, src1, .. } => {
write!(formatter, " vcc_lo, {src0}, v{src1}")
}
Self::Branch { target }
| Self::BranchSccZero { target }
| Self::BranchExecZero { target }
+12 -2
View File
@@ -355,9 +355,19 @@ pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
}
}
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
trailer.literal = [source("SRC0"), source("SRC1"), source("SRC2")]
// An attribute field (XML OPR_ATTR) is not an operand selector: in the
// VOP3 interpolation forms SRC0 holds {attr_word, attr_chan, attr}
// bit-fields (AMD RDNA 2 ISA guide, section 10.4.2), so 255 there
// does not select a literal.
trailer.literal = ["SRC0", "SRC1", "SRC2"]
.into_iter()
.flatten()
.filter(|name| {
!form
.operands
.iter()
.any(|operand| operand.field == *name && operand.kind == "OPR_ATTR")
})
.filter_map(source)
.any(|value| value == SRC_LITERAL);
}
EncodingFamily::Mimg => {
+51
View File
@@ -0,0 +1,51 @@
//! 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)
}
+60
View File
@@ -110,6 +110,66 @@ pub const V_MUL_F32: Opcode = Opcode {
bits: 0x10000000,
bytes: 4,
};
pub const V_CMP_LT_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d020000,
bytes: 4,
};
pub const V_CMP_EQ_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d040000,
bytes: 4,
};
pub const V_CMP_LE_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d060000,
bytes: 4,
};
pub const V_CMP_GT_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d080000,
bytes: 4,
};
pub const V_CMP_NE_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d0a0000,
bytes: 4,
};
pub const V_CMP_GE_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d0c0000,
bytes: 4,
};
pub const V_CMP_LT_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d820000,
bytes: 4,
};
pub const V_CMP_EQ_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d840000,
bytes: 4,
};
pub const V_CMP_LE_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d860000,
bytes: 4,
};
pub const V_CMP_GT_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d880000,
bytes: 4,
};
pub const V_CMP_NE_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d8a0000,
bytes: 4,
};
pub const V_CMP_GE_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d8c0000,
bytes: 4,
};
pub const EXP: Opcode = Opcode {
mask: 0xfc000000,
bits: 0xf8000000,
File diff suppressed because it is too large. Load diff
+158
View File
@@ -0,0 +1,158 @@
//! 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,
}
/// 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,
/// 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],
}
+288
View File
@@ -0,0 +1,288 @@
// @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,
}
impl ScalarAluOp {
/// Every operation, in registry order.
pub const ALL: [Self; 9] = [
Self::AddU32,
Self::SubU32,
Self::AddI32,
Self::SubI32,
Self::AddcU32,
Self::SubbU32,
Self::AndB32,
Self::OrB32,
Self::XorB32,
];
/// Selects the operation from a first instruction word (mask 0xff80_0000).
pub const fn from_word(word: u32) -> Option<Self> {
match word & 0xff80_0000 {
0x8000_0000 => Some(Self::AddU32),
0x8080_0000 => Some(Self::SubU32),
0x8100_0000 => Some(Self::AddI32),
0x8180_0000 => Some(Self::SubI32),
0x8200_0000 => Some(Self::AddcU32),
0x8280_0000 => Some(Self::SubbU32),
0x8700_0000 => Some(Self::AndB32),
0x8800_0000 => Some(Self::OrB32),
0x8900_0000 => Some(Self::XorB32),
_ => None,
}
}
/// 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",
}
}
/// 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,
}
}
/// 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,
}]
}
/// 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),
}
}
}
/// Identity of every registry form, in registry order.
pub const FORM_IDS: [(&str, EncodingFamily); 9] = [
("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),
];
/// One validated row per registry form, in registry order.
pub static FORMS: [FormSemantics; 9] = [
FormSemantics {
name: "S_ADD_U32",
family: EncodingFamily::Sop2,
opcode: 0,
operation: Operation::Add,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
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,
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,
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,
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,
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,
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,
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,
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,
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],
},
];
+454
View File
@@ -0,0 +1,454 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! gfx1030 extension-word negative tests (issue #172): truncated and invalid
//! literal, SDWA, DPP16, DPP8 and MIMG NSA trailers.
//!
//! Every source instruction is original and was assembled by llvm-mc 23.1.6
//! (`source_encodings_match_llvm` re-checks the bytes). Expected results come
//! from LLVM's disassembly of the cut or altered bytes and from the field
//! layouts in AMD's public "RDNA 2 Instruction Set Architecture" reference
//! (microcode formats: SDWA, DPP16, DPP8, MIMG NSA), never from Xenora's
//! decoder. `identify` recognises lengths and allowed extensions; it does not
//! validate control-word values (see `reserved_control_values_keep_their_trailer_lengths`).
use std::io::Write;
use std::process::{Command, Stdio};
use xenora_isa::meta::{
IdentifyError, SRC_DPP8, SRC_DPP16, SRC_LITERAL, SRC_SDWA, Trailer, VectorControl, identify,
};
struct Fixture {
source: &'static str,
bytes: &'static [u8],
}
const SOP2_LITERAL: Fixture = Fixture {
source: "s_add_u32 s9, 0x12345679, s11",
bytes: &[0xff, 0x0b, 0x09, 0x80, 0x79, 0x56, 0x34, 0x12],
};
const SOPK_IMMEDIATE: Fixture = Fixture {
source: "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x125678ab",
bytes: &[0x01, 0xf8, 0x80, 0xba, 0xab, 0x78, 0x56, 0x12],
};
const VOP1_LITERAL: Fixture = Fixture {
source: "v_mov_b32_e32 v7, 0x12345679",
bytes: &[0xff, 0x02, 0x0e, 0x7e, 0x79, 0x56, 0x34, 0x12],
};
const VOP2_LITERAL: Fixture = Fixture {
source: "v_add_f32_e32 v7, 0x3f800003, v8",
bytes: &[0xff, 0x10, 0x0e, 0x06, 0x03, 0x00, 0x80, 0x3f],
};
const FMAMK: Fixture = Fixture {
source: "v_fmamk_f32 v7, v8, 0x40000001, v9",
bytes: &[0x08, 0x13, 0x0e, 0x58, 0x01, 0x00, 0x00, 0x40],
};
const FMAAK: Fixture = Fixture {
source: "v_fmaak_f32 v7, v8, v9, 0x40000002",
bytes: &[0x08, 0x13, 0x0e, 0x5a, 0x02, 0x00, 0x00, 0x40],
};
const VOPC_LITERAL: Fixture = Fixture {
source: "v_cmp_eq_u32_e32 vcc_lo, 0x1235, v9",
bytes: &[0xff, 0x12, 0x84, 0x7d, 0x35, 0x12, 0x00, 0x00],
};
const VOP3_LITERAL: Fixture = Fixture {
source: "v_fma_f32 v7, v8, v9, 0x3f800003",
bytes: &[
0x07, 0x00, 0x4b, 0xd5, 0x08, 0x13, 0xfe, 0x03, 0x03, 0x00, 0x80, 0x3f,
],
};
const VOP3P_LITERAL: Fixture = Fixture {
source: "v_pk_fma_f16 v7, v8, v9, 0x3c02",
bytes: &[
0x07, 0x40, 0x0e, 0xcc, 0x08, 0x13, 0xfe, 0x1b, 0x02, 0x3c, 0x00, 0x00,
],
};
const VOP1_SDWA: Fixture = Fixture {
source: "v_mov_b32_sdwa v7, v8 dst_sel:BYTE_1 dst_unused:UNUSED_PAD src0_sel:DWORD",
bytes: &[0xf9, 0x02, 0x0e, 0x7e, 0x08, 0x01, 0x06, 0x00],
};
const VOP2_SDWA: Fixture = Fixture {
source: "v_add_f32_sdwa v7, v8, v9 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:DWORD",
bytes: &[0xf9, 0x12, 0x0e, 0x06, 0x08, 0x06, 0x04, 0x06],
};
const VOPC_SDWA: Fixture = Fixture {
source: "v_cmp_eq_u32_sdwa s4, v8, v9 src0_sel:DWORD src1_sel:DWORD",
bytes: &[0xf9, 0x12, 0x84, 0x7d, 0x08, 0x84, 0x06, 0x06],
};
const DPP16: Fixture = Fixture {
source: "v_add_f32_dpp v7, v8, v9 row_shl:2 row_mask:0xf bank_mask:0xf",
bytes: &[0xfa, 0x12, 0x0e, 0x06, 0x08, 0x02, 0x01, 0xff],
};
const DPP8: Fixture = Fixture {
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5]",
bytes: &[0xe9, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
};
const DPP8_FI: Fixture = Fixture {
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5] fi:1",
bytes: &[0xea, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
};
const NSA1: Fixture = Fixture {
source: "image_sample v[4:7], [v8, v10], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
bytes: &[
0x0a, 0x0f, 0x80, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x00, 0x00, 0x00,
],
};
const NSA2: Fixture = Fixture {
source: "image_sample_d v[4:7], [v8, v10, v12, v14, v16, v18], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
bytes: &[
0x0c, 0x0f, 0x88, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x00, 0x00,
0x00,
],
};
const NSA3: Fixture = Fixture {
source: "image_sample_c_d_cl v[4:7], [v8, v10, v12, v14, v16, v18, v20, v22, v24, v26, v28], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_3D",
bytes: &[
0x16, 0x0f, 0xac, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16,
0x18, 0x1a, 0x1c, 0x00, 0x00,
],
};
const FRACT_F64: Fixture = Fixture {
source: "v_fract_f64_e32 v[6:7], v[8:9]",
bytes: &[0x08, 0x7d, 0x0c, 0x7e],
};
const READFIRSTLANE: Fixture = Fixture {
source: "v_readfirstlane_b32 s7, v8",
bytes: &[0x08, 0x05, 0x0e, 0x7e],
};
const FMAC: Fixture = Fixture {
source: "v_fmac_f32_e32 v7, v8, v9",
bytes: &[0x08, 0x13, 0x0e, 0x56],
};
const READLANE: Fixture = Fixture {
source: "v_readlane_b32 s7, v8, s9",
bytes: &[0x07, 0x00, 0x60, 0xd7, 0x08, 0x13, 0x00, 0x02],
};
const NOP: Fixture = Fixture {
source: "s_nop 7",
bytes: &[0x07, 0x00, 0x80, 0xbf],
};
const VOPC_REGISTER: Fixture = Fixture {
source: "v_cmp_eq_u32_e32 vcc_lo, v8, v9",
bytes: &[0x08, 0x13, 0x84, 0x7d],
};
#[test]
fn proper_prefixes_report_exact_required_lengths() {
// Each row cuts at every dword boundary and one byte before the end.
// LLVM emits no original instruction for any prefix. Below, "silent"
// means no diagnostic, and "invalid" means LLVM's invalid encoding warning.
// Empty input is silent in all rows. The expected values are the next
// base boundary (4 or 8) until the base is present, then the LLVM length.
let cases: &[(&Fixture, &[usize])] = &[
// silent, SSRC0 selects the literal dword.
(&SOP2_LITERAL, &[4, 8, 8]),
// invalid, mandatory SOPK immediate.
(&SOPK_IMMEDIATE, &[4, 8, 8]),
// silent, literal selector.
(&VOP1_LITERAL, &[4, 8, 8]),
// silent, literal selector.
(&VOP2_LITERAL, &[4, 8, 8]),
// invalid, embedded multiplier dword.
(&FMAMK, &[4, 8, 8]),
// invalid, embedded addend dword.
(&FMAAK, &[4, 8, 8]),
// silent, literal selector.
(&VOPC_LITERAL, &[4, 8, 8]),
// invalid at 4 then silent, 8-byte base and literal.
(&VOP3_LITERAL, &[4, 8, 12, 12]),
// invalid at 4 then silent, 8-byte base and literal.
(&VOP3P_LITERAL, &[4, 8, 12, 12]),
// invalid, SDWA control dword.
(&VOP1_SDWA, &[4, 8, 8]),
// invalid, SDWA control dword.
(&VOP2_SDWA, &[4, 8, 8]),
// invalid, SDWAB control dword.
(&VOPC_SDWA, &[4, 8, 8]),
// invalid, DPP16 control dword.
(&DPP16, &[4, 8, 8]),
// invalid, DPP8 control dword (fi:0).
(&DPP8, &[4, 8, 8]),
// invalid, DPP8 control dword (fi:1).
(&DPP8_FI, &[4, 8, 8]),
// invalid, 8-byte base and one NSA dword.
(&NSA1, &[4, 8, 12, 12]),
// invalid, 8-byte base and two NSA dwords.
// LLVM also prints a stray v_mul_f32 from the address bytes.
(&NSA2, &[4, 8, 16, 16, 16]),
// invalid, 8-byte base and three NSA dwords.
// LLVM also prints stray v_mul_f32 and v_mul_hi_u32_u24 from the address bytes.
(&NSA3, &[4, 8, 20, 20, 20, 20]),
];
for &(fixture, expected) in cases {
let len = fixture.bytes.len();
let prefixes: Vec<_> = (0..len).step_by(4).chain([len - 1]).collect();
assert_eq!(prefixes.len(), expected.len(), "{}", fixture.source);
for (prefix, &needed) in prefixes.into_iter().zip(expected) {
assert_eq!(
identify(&fixture.bytes[..prefix]),
Err(IdentifyError::Truncated { needed }),
"{} at {prefix}/{len} bytes",
fixture.source,
);
}
}
}
#[test]
fn disallowed_vector_selectors_and_literal_are_rejected() {
// Replace the nine-bit SRC0 field of each assembled e32 instruction
// and append a known control or literal dword.
let cases = [
// LLVM rejects SDWA on v_fract_f64. Expect InvalidExtension("sdwa").
(&FRACT_F64, SRC_SDWA, &VOP1_SDWA, "sdwa"),
// LLVM rejects DPP16 on v_fract_f64. Expect InvalidExtension("dpp16").
(&FRACT_F64, SRC_DPP16, &DPP16, "dpp16"),
// LLVM rejects DPP8 on v_fract_f64 and prints the trailer as s_cmpk_lt_i32.
// Expect InvalidExtension("dpp8") for the rejected first instruction.
(&FRACT_F64, SRC_DPP8, &DPP8, "dpp8"),
// LLVM rejects SDWA on v_fmac_f32. Expect InvalidExtension("sdwa").
(&FMAC, SRC_SDWA, &VOP1_SDWA, "sdwa"),
// LLVM rejects DPP16 on this v_cmp_eq_u32. Expect InvalidExtension("dpp16").
(&VOPC_REGISTER, SRC_DPP16, &DPP16, "dpp16"),
// LLVM prints v_readfirstlane_b32 with "Invalid immediate" because
// this source must be a VGPR. Expect InvalidExtension("literal").
(&READFIRSTLANE, SRC_LITERAL, &VOP1_LITERAL, "literal"),
];
for (fixture, selector, trailer, reason) in cases {
let mut bytes = fixture.bytes.to_vec();
let word = u32::from_le_bytes(fixture.bytes.try_into().unwrap());
bytes.copy_from_slice(&((word & !0x1ff) | selector).to_le_bytes());
bytes.extend_from_slice(&trailer.bytes[4..]);
assert_eq!(
identify(&bytes),
Err(IdentifyError::InvalidExtension(reason)),
"{} with SRC0={selector:#x}: {bytes:02x?}",
fixture.source,
);
}
}
#[test]
fn literal_for_vop3_readlane_is_rejected() {
// v_readlane_b32: change SRC0 in the second base dword at bits 8:0
// and append the v_mov_b32 literal. LLVM prints "Invalid immediate"
// for the VGPR-only source. Expect the form to reject the literal.
let mut bytes = READLANE.bytes.to_vec();
let word = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
bytes[4..8].copy_from_slice(&((word & !0x1ff) | SRC_LITERAL).to_le_bytes());
bytes.extend_from_slice(&VOP1_LITERAL.bytes[4..]);
assert_eq!(
identify(&bytes),
Err(IdentifyError::InvalidExtension("literal"))
);
}
/// Identification recognizes length independently of control-word validation.
#[test]
fn reserved_control_values_keep_their_trailer_lengths() {
let cases = [
// v_add_f32_dpp: replace DPP_CTRL 0x102 with 0x100, which LLVM reports as reserved.
// LLVM prints "Invalid dpp_ctrl value". Expect 8 bytes and DPP16.
(&DPP16, 5, 0, "V_ADD_F32", VectorControl::Dpp16),
// v_mov_b32_sdwa: change SRC0_SEL from 6 to 7, which LLVM treats as reserved.
// LLVM prints DWORD and reassembles it as 6. Expect 8 bytes and SDWA.
(&VOP1_SDWA, 6, 7, "V_MOV_B32", VectorControl::Sdwa),
];
for (fixture, offset, value, name, control) in cases {
let mut bytes = fixture.bytes.to_vec();
bytes[offset] = value;
let found = identify(&bytes).unwrap();
assert_eq!(found.form.name, name);
assert_eq!(found.len, 8);
assert_eq!(
found.trailer,
Trailer {
vector_control: Some(control),
..Trailer::default()
},
);
}
}
#[test]
fn next_instruction_starts_after_the_trailer() {
// Append s_nop 7 to each original instruction. LLVM disassembles the
// two instructions with lengths (offset, 4). Expect that boundary from
// identify and the trailer selected by SRC0, SSRC0, or MIMG.NSA.
let cases = [
// LLVM emits s_nop at byte 8. Expect a scalar literal dword.
(
&SOP2_LITERAL,
"S_ADD_U32",
8,
Trailer {
literal: true,
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect an SDWA control dword.
(
&VOP1_SDWA,
"V_MOV_B32",
8,
Trailer {
vector_control: Some(VectorControl::Sdwa),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect a DPP16 control dword.
(
&DPP16,
"V_ADD_F32",
8,
Trailer {
vector_control: Some(VectorControl::Dpp16),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:0.
(
&DPP8,
"V_MOV_B32",
8,
Trailer {
vector_control: Some(VectorControl::Dpp8 {
fetch_inactive: false,
}),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:1.
(
&DPP8_FI,
"V_MOV_B32",
8,
Trailer {
vector_control: Some(VectorControl::Dpp8 {
fetch_inactive: true,
}),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 12. Expect one NSA dword.
(
&NSA1,
"IMAGE_SAMPLE",
12,
Trailer {
nsa_dwords: 1,
..Trailer::default()
},
),
// LLVM emits s_nop at byte 16. Expect two NSA dwords.
(
&NSA2,
"IMAGE_SAMPLE_D",
16,
Trailer {
nsa_dwords: 2,
..Trailer::default()
},
),
// LLVM emits s_nop at byte 20. Expect three NSA dwords.
(
&NSA3,
"IMAGE_SAMPLE_C_D_CL",
20,
Trailer {
nsa_dwords: 3,
..Trailer::default()
},
),
];
for (fixture, name, offset, trailer) in cases {
let bytes = [fixture.bytes, NOP.bytes].concat();
let first = identify(&bytes).unwrap();
assert_eq!(
(first.form.name, first.len, first.trailer),
(name, offset, trailer),
"{} followed by {}",
fixture.source,
NOP.source,
);
let second = identify(&bytes[first.len..]).unwrap();
assert_eq!(
(second.form.name, second.len, second.trailer),
("S_NOP", 4, Trailer::default()),
);
assert_eq!(first.len + second.len, bytes.len());
}
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
fn source_encodings_match_llvm() {
let fixtures = [
&SOP2_LITERAL,
&SOPK_IMMEDIATE,
&VOP1_LITERAL,
&VOP2_LITERAL,
&FMAMK,
&FMAAK,
&VOPC_LITERAL,
&VOP3_LITERAL,
&VOP3P_LITERAL,
&VOP1_SDWA,
&VOP2_SDWA,
&VOPC_SDWA,
&DPP16,
&DPP8,
&DPP8_FI,
&NSA1,
&NSA2,
&NSA3,
&FRACT_F64,
&READFIRSTLANE,
&FMAC,
&READLANE,
&NOP,
&VOPC_REGISTER,
];
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|| "llvm-mc".into(),
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
);
let mut llvm = Command::new(executable)
.args([
"-triple=amdgcn-amd-amdhsa",
"-mcpu=gfx1030",
"-mattr=+wavefrontsize32",
"-show-encoding",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
{
let mut input = llvm.stdin.take().unwrap();
for fixture in fixtures {
writeln!(input, "{}", fixture.source).unwrap();
}
}
let output = llvm.wait_with_output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr),
);
let assembly = String::from_utf8(output.stdout).unwrap();
let encodings: Vec<_> = assembly
.lines()
.filter_map(|line| line.split_once("; encoding: [").map(|(_, bytes)| bytes))
.collect();
assert_eq!(encodings.len(), fixtures.len());
for (fixture, encoding) in fixtures.into_iter().zip(encodings) {
let bytes: Vec<_> = encoding
.strip_suffix(']')
.unwrap()
.split(',')
.map(|byte| u8::from_str_radix(byte.trim().strip_prefix("0x").unwrap(), 16).unwrap())
.collect();
assert_eq!(bytes, fixture.bytes, "{}", fixture.source);
}
}
+311
View File
@@ -0,0 +1,311 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Regenerate the gfx1030 Wave32 instruction-identification oracle corpus."""
import argparse
from collections import defaultdict
from itertools import islice, zip_longest
from pathlib import Path
import random
import re
import runpy
import subprocess
import tempfile
HERE = Path(__file__).resolve().parent
ISA = HERE.parents[1]
TARGET = ("-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-mattr=+wavefrontsize32")
BASE_32 = {"SOP1", "SOP2", "SOPC", "SOPK", "SOPP", "VINTRP", "VOP1", "VOP2", "VOPC"}
ENCODING = re.compile(r"^\s*(.*?)\s*; encoding: \[([^\]]+)\]", re.MULTILINE)
SECTION = re.compile(r"^Disassembly of section \.text\.(\d+):")
# Instruction text, offset, consumed words, then optional trailing text: a
# branch-target annotation such as `<.text+0x841c>` or an LLVM warning such as
# `; Warning: ... scalar reg isn't aligned`, neither of which stops decoding.
INSTRUCTION = re.compile(r"^\t(.*?)\s*// ([0-9A-F]{12}): ((?:[0-9A-F]{8}(?: |$))+)(.*)$")
def llvm(executable, *args, source=None):
return subprocess.run(
[executable, *TARGET, "-show-encoding", *args],
input=source, text=True, capture_output=True, check=True,
)
def encodings(output):
for text, bytes_text in ENCODING.findall(output):
yield " ".join(text.split()), bytes(int(token, 16) for token in bytes_text.split(","))
def disassemble_batch(llvm_bin, blobs):
"""LLVM's decode of the first instruction of each blob.
Each blob goes into its own section of one object built from `.byte`
directives; llvm-objdump disassembles every section from offset zero and
prints the words it consumed. That length is what the decoder read, not the
length of a re-encoding (llvm-mc --disassemble re-encodes, which shortens
inconsistent MIMG NSA probes). Returns (text, consumed bytes) or None when
LLVM cannot decode offset zero (it prints `.long`/`.short`/`.byte`).
"""
source = []
for index, blob in enumerate(blobs):
source.append(f'.section .text.{index},"ax"')
if blob:
source.append(".byte " + ",".join(f"0x{byte:02x}" for byte in blob))
with tempfile.TemporaryDirectory() as directory:
assembly_path = Path(directory) / "probes.s"
object_path = Path(directory) / "probes.o"
assembly_path.write_text("\n".join(source) + "\n")
subprocess.run(
[llvm_bin / "llvm-mc", *TARGET, "-filetype=obj", assembly_path, "-o", object_path],
check=True, capture_output=True,
)
dump = subprocess.run(
[llvm_bin / "llvm-objdump", "-d", "--mcpu=gfx1030", "--mattr=+wavefrontsize32", object_path],
check=True, capture_output=True, text=True,
).stdout
first = {}
section = None
for line in dump.splitlines():
header = SECTION.match(line)
if header:
section = int(header.group(1))
continue
instruction = INSTRUCTION.match(line)
if section is None or section in first or not instruction:
continue
text, offset, words, warning = instruction.groups()
if int(offset, 16) != 0:
continue
if text.startswith((".long", ".short", ".byte")):
first[section] = None
else:
text = " ".join(text.split())
warning = warning.strip()
if warning.startswith(";"):
text += f" [LLVM: {warning.lstrip('; ')}]"
first[section] = (text, 4 * len(words.split()))
return [first.get(index) for index in range(len(blobs))]
CRASHED = "crashed"
def disassemble_all(llvm_bin, blobs):
"""Batches of 128; a batch that crashes llvm-objdump is split until the
crashing blobs are isolated, and each of those is reported as CRASHED."""
results = []
for start in range(0, len(blobs), 128):
results.extend(_isolate(llvm_bin, blobs[start:start + 128]))
return results
def _isolate(llvm_bin, blobs):
try:
return disassemble_batch(llvm_bin, blobs)
except subprocess.CalledProcessError as error:
if error.returncode != -11:
raise
if len(blobs) == 1:
return [CRASHED]
half = len(blobs) // 2
return _isolate(llvm_bin, blobs[:half]) + _isolate(llvm_bin, blobs[half:])
def extension(text, length, family):
mnemonic = text.split()[0]
if "dpp8:" in text:
return "dpp8fi" if "fi:1" in text else "dpp8"
if mnemonic.endswith("_dpp"):
return "dpp16"
if mnemonic.endswith("_sdwa"):
return "sdwa"
base_bytes = 4 if family in BASE_32 else 8
if mnemonic.endswith("_e64"):
base_bytes = 8
extra = length - base_bytes
if mnemonic.startswith("image_") and extra > 0:
return f"nsa{extra // 4}"
# After excluding vector control and image addresses, an extra dword
# carrying a numeric operand is the literal (including mandatory literals).
if extra == 4 and re.search(r"(?:,|\s)\s*-?(?:0x[\da-f]+|\d+)(?=,|\s|$|/\*)", text):
return "literal"
if extra > 0:
raise ValueError(f"unclassified LLVM extension: {length} bytes {text}")
return "-"
def assembly(executable):
source = HERE / "corpus.s"
families = [
line.split("//", 1)[1].strip()
for line in source.read_text().splitlines()
if line.split("//", 1)[0].strip()
]
result = llvm(executable, source)
if result.stderr:
raise ValueError(result.stderr)
decoded = list(encodings(result.stdout))
if len(decoded) != len(families):
raise ValueError("LLVM must emit exactly one encoding per assembly line")
return [(family, text, data) for family, (text, data) in zip(families, decoded)]
def metadata_forms():
snapshot = ISA / "data/rdna2.jsonl"
project = runpy.run_path(str(ISA / "generate_rdna2_meta.py"))["forms_from_snapshot"]
return project(snapshot.read_text())[2]
def probes():
# The normalized snapshot stores instruction variants and encoding records
# separately. Reuse its projection to obtain identifiers, widths and labels
# for coverage. The projected mnemonic and extensions are never consulted.
forms = metadata_forms()
rng = random.Random(209)
for form in forms:
width = form["bytes"]
# One probe with every non-identifying bit zero (operands s0/v0, no
# modifiers), then two with seeded random operand bits.
yield "zero", form["encoding"].upper(), form["bits"].to_bytes(width, "little") + bytes(16)
for _ in range(2):
value = form["bits"] | (rng.getrandbits(width * 8) & ~form["mask"])
yield "random", form["encoding"].upper(), value.to_bytes(width, "little") + rng.randbytes(16)
# Extension selectors from the RDNA 2 ISA reference: the SRC0 (VOP1, VOP2,
# VOPC, VOP3*) or SSRC0 (SOP1, SOP2, SOPC) value that makes one extra dword
# follow the base encoding.
SELECTORS = {"literal": 0xFF, "sdwa": 0xF9, "dpp16": 0xFA, "dpp8": 0xE9, "dpp8fi": 0xEA}
# Instructions whose last dword is a legal control word for each extension;
# LLVM assembles them, so the control words are LLVM's own.
CONTROL_SOURCES = {
"sdwa": "v_add_f32_sdwa v0, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD",
"sdwa-vop1": "v_mov_b32_sdwa v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD",
"sdwa-vopc": "v_cmp_eq_f32_sdwa vcc_lo, v0, v0 src0_sel:DWORD src1_sel:DWORD",
"dpp16": "v_add_f32_dpp v0, v0, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf",
"dpp8": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7]",
"dpp8fi": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7] fi:1",
}
LITERAL = (0x12345678).to_bytes(4, "little")
def controls(executable):
source = "\n".join(CONTROL_SOURCES.values()) + "\n"
decoded = list(encodings(llvm(executable, source=source).stdout))
return {name: data[-4:] for name, (_, data) in zip(CONTROL_SOURCES, decoded)}
def extension_probes(executable, forms):
"""Every form's zero-operand base with each extension selector its family
can carry, followed by a legal control dword or literal. LLVM decides which
combinations are instructions; the metadata's extension list is not read."""
control = controls(executable)
for form in forms:
family = form["encoding"].upper()
base = form["bits"]
if family in ("VOP1", "VOP2", "VOPC"):
kinds = ["literal", "sdwa", "dpp16", "dpp8", "dpp8fi"]
shift = 0
elif family in ("VOP3", "VOP3SDST", "VOP3P"):
kinds, shift = ["literal"], 32
elif family in ("SOP1", "SOP2", "SOPC"):
kinds, shift = ["literal"], 0
else:
continue
field = 0x1FF if shift == 32 or family.startswith("VOP") else 0xFF
if base & form["mask"] & (field << shift):
continue # SRC0/SSRC0 is part of this form's identifier
for kind in kinds:
value = (base & ~(field << shift)) | (SELECTORS[kind] << shift)
if kind == "literal":
trailer = LITERAL
elif kind == "sdwa" and family in ("VOPC", "VOP1"):
trailer = control[f"sdwa-{family.lower()}"]
else:
trailer = control[kind]
yield kind, family, value.to_bytes(form["bytes"], "little") + trailer + bytes(12)
def truncations(entries):
by_family = defaultdict(list)
for entry in entries:
by_family[entry[0]].append(entry)
groups = [
sorted(group, key=lambda entry: -len(entry[2]))
for _, group in sorted(by_family.items())
]
interleaved = (entry for batch in zip_longest(*groups) for entry in batch if entry)
yield from islice(interleaved, 40)
def decoded_columns(text, length, family):
return text.split()[0], str(length), extension(text, length, family)
def generate(llvm_bin):
rows = []
entries = assembly(llvm_bin / "llvm-mc")
for family, text, data in entries:
rows.append(("asm", data.hex(), *decoded_columns(text, len(data), family), f"{family} {text}"))
probe_list = list(probes()) + [
(f"ext-{kind}", family, data)
for kind, family, data in extension_probes(llvm_bin / "llvm-mc", metadata_forms())
]
cut_list = [
(family, text, data, data[:size])
for family, text, data in truncations(entries)
for size in range(0, len(data), 4)
]
decoded_all = disassemble_all(llvm_bin, [data for _, _, data in probe_list] + [cut for *_, cut in cut_list])
for (kind, family, data), decoded in zip(probe_list, decoded_all):
if decoded is None:
columns = ("invalid", "0", "-")
note = "LLVM cannot decode offset zero"
elif decoded == CRASHED:
columns = ("crashed", "0", "-")
note = "llvm-objdump crashed (SIGSEGV)"
elif "/*Invalid" not in decoded[0]:
text, length = decoded
columns = decoded_columns(text, length, family)
note = text
if decoded not in (None, CRASHED) and "/*Invalid" in decoded[0]:
# LLVM decodes the words (so it knows the opcode and the length)
# but flags an operand the instruction cannot take, for example an
# SGPR or literal for a VGPR-only source.
text, length = decoded
mnemonic, *rest = decoded_columns(text, length, family)
columns = (f"invalid-operand:{mnemonic}", *rest)
note = text
source = f"probe-{kind}" if kind in ("zero", "random") else "probe-ext"
if kind.startswith("ext-"):
note = f"{kind[4:]} {note}"
rows.append((source, data.hex(), *columns, f"{family} {note}"))
for (family, text, data, prefix), decoded in zip(cut_list, decoded_all[len(probe_list):]):
if decoded is None:
observed = "cannot decode" if prefix else "no instruction"
elif decoded == CRASHED:
observed = "crashed (SIGSEGV)"
else:
observed = f"decoded {decoded[1]} bytes: {decoded[0]}"
note = f"{family} LLVM {observed} | cut {data.hex()} {text}"
rows.append(("truncation", prefix.hex(), "truncated", "0", "-", note))
header = "source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote\n"
return header + "".join("\t".join(row) + "\n" for row in sorted(rows))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--llvm-bin", required=True, type=Path)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
data = generate(args.llvm_bin.resolve())
output = HERE / "corpus.tsv"
if args.check:
if output.read_bytes() != data.encode():
parser.exit(1, f"{output} differs from the LLVM output\n")
else:
output.write_bytes(data.encode())
if __name__ == "__main__":
main()
+320
View File
@@ -0,0 +1,320 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original gfx1030 Wave32 instruction identification cases.
s_mov_b32 s105, s0 // SOP1
s_mov_b32 exec_lo, -16 // SOP1
s_mov_b32 m0, 64 // SOP1
s_mov_b32 vcc_hi, 0xdeadbeef // SOP1
s_mov_b64 exec, vcc // SOP1
s_mov_b64 vcc, 0x12345678 // SOP1
s_not_b32 s0, s105 // SOP1
s_not_b64 s[104:105], s[0:1] // SOP1
s_brev_b32 s105, m0 // SOP1
s_bcnt1_i32_b32 s0, exec_lo // SOP1
s_ff1_i32_b32 s105, -16 // SOP1
s_flbit_i32_b32 s105, 0x80000100 // SOP1
s_sext_i32_i8 s0, s105 // SOP1
s_sext_i32_i16 s105, s0 // SOP1
s_getpc_b64 s[104:105] // SOP1
s_setpc_b64 s[0:1] // SOP1
s_and_saveexec_b64 s[0:1], s[104:105] // SOP1
s_wqm_b64 s[104:105], exec // SOP1
s_add_u32 s105, s0, 0x12345678 // SOP2
s_add_u32 s0, 0xdeadbeef, s105 // SOP2
s_add_i32 s0, -16, 64 // SOP2
s_sub_i32 s105, s0, m0 // SOP2
s_subb_u32 s0, vcc_lo, exec_lo // SOP2
s_min_i32 s105, s104, -16 // SOP2
s_max_u32 s0, s105, 64 // SOP2
s_cselect_b32 s105, -1, s0 // SOP2
s_and_b64 s[104:105], exec, vcc // SOP2
s_or_b64 vcc, s[0:1], exec // SOP2
s_xor_b32 s0, s0, 0xdeadbeef // SOP2
s_nand_b32 s105, m0, vcc_lo // SOP2
s_lshl_b32 s0, s105, 31 // SOP2
s_lshr_b64 s[104:105], s[0:1], 63 // SOP2
s_ashr_i32 s105, 0x87654321, 31 // SOP2
s_mul_i32 s0, s105, -16 // SOP2
s_bfe_u32 s105, s0, 0x0010000f // SOP2
s_cmp_eq_i32 s0, s105 // SOPC
s_cmp_lg_i32 m0, -16 // SOPC
s_cmp_gt_i32 64, s105 // SOPC
s_cmp_ge_i32 s105, 0xdeadbeef // SOPC
s_cmp_lt_u32 0x12345678, exec_hi // SOPC
s_cmp_le_u32 vcc_lo, 64 // SOPC
s_cmp_eq_u64 s[104:105], vcc // SOPC
s_bitcmp0_b32 s105, 31 // SOPC
s_bitcmp1_b64 exec, 63 // SOPC
s_movk_i32 s0, -32768 // SOPK
s_movk_i32 s105, 32767 // SOPK
s_movk_i32 m0, -1 // SOPK
s_addk_i32 s105, -32768 // SOPK
s_mulk_i32 s0, 32767 // SOPK
s_cmpk_eq_i32 s105, -32768 // SOPK
s_cmpk_lg_u32 s0, 65535 // SOPK
s_getreg_b32 s105, hwreg(HW_REG_MODE) // SOPK
s_setreg_b32 hwreg(HW_REG_MODE, 4, 8), s0 // SOPK
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 8, 16), 0xdeadbeef // SOPK
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0 // SOPK
s_nop 15 // SOPP
s_endpgm 0 // SOPP
s_branch -32768 // SOPP
s_cbranch_scc0 32767 // SOPP
s_cbranch_scc1 -1 // SOPP
s_cbranch_vccz 0 // SOPP
s_cbranch_vccnz 3 // SOPP
s_cbranch_execz 7 // SOPP
s_cbranch_execnz -7 // SOPP
s_barrier // SOPP
s_waitcnt vmcnt(0) lgkmcnt(1) expcnt(7) // SOPP
s_sleep 127 // SOPP
s_trap 255 // SOPP
s_load_dword s105, s[0:1], 1048575 // SMEM
s_load_dword s0, s[104:105], -1048576 // SMEM
s_load_dwordx2 s[104:105], s[0:1], 0 glc // SMEM
s_load_dwordx4 s[0:3], s[100:101], s105 // SMEM
s_load_dwordx8 s[96:103], s[0:1], 7 // SMEM
s_load_dwordx16 s[0:15], s[104:105], 16 // SMEM
s_buffer_load_dword s105, s[0:3], 4095 // SMEM
s_buffer_load_dwordx2 s[104:105], s[0:3], 0 // SMEM
s_buffer_load_dwordx4 s[0:3], s[100:103], s105 // SMEM
s_memtime s[104:105] // SMEM
s_dcache_inv // SMEM
v_mov_b32_e32 v255, v0 // VOP1
v_mov_b32_e32 v0, s105 // VOP1
v_mov_b32_e32 v255, 0xdeadbeef // VOP1
v_mov_b32_e32 v0, -16 // VOP1
v_mov_b32_e32 v255, 64 // VOP1
v_mov_b32_e32 v0, 0.5 // VOP1
v_mov_b32_e32 v255, -4.0 // VOP1
v_mov_b32_e32 v0, 0.15915494 // VOP1
v_cvt_f32_i32_e32 v255, v0 // VOP1
v_cvt_f32_u32_e32 v0, v255 // VOP1
v_cvt_i32_f32_e32 v255, 0x3f800001 // VOP1
v_rcp_f32_e32 v0, v255 // VOP1
v_sqrt_f32_e32 v255, v0 // VOP1
v_readfirstlane_b32 s105, v255 // VOP1
v_mov_b32_sdwa v255, v0 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 // VOP1
v_mov_b32_dpp v0, v255 quad_perm:[3,2,1,0] row_mask:0x1 bank_mask:0x8 // VOP1
v_mov_b32_dpp v255, v0 row_shl:15 bound_ctrl:1 // VOP1
v_mov_b32_dpp v0, v255 row_share:15 // VOP1
v_mov_b32_dpp v255, v0 dpp8:[7,6,5,4,3,2,1,0] fi:0 // VOP1
v_mov_b32_dpp v0, v255 dpp8:[0,0,0,0,7,7,7,7] fi:1 // VOP1
v_mov_b32_e32 v255, 0x3e22f983 // VOP1
v_add_f32_e32 v0, v255, v0 // VOP2
v_sub_f32_e32 v255, 0x3f800001, v0 // VOP2
v_subrev_f32_e32 v0, s105, v255 // VOP2
v_mul_f32_e32 v255, -4.0, v0 // VOP2
v_mul_i32_i24_e32 v0, -16, v255 // VOP2
v_mul_u32_u24_e32 v255, 64, v0 // VOP2
v_min_f32_e32 v0, 0.5, v255 // VOP2
v_max_f32_e32 v255, 0.15915494, v0 // VOP2
v_lshrrev_b32_e32 v0, 31, v255 // VOP2
v_ashrrev_i32_e32 v255, 31, v0 // VOP2
v_lshlrev_b32_e32 v0, 31, v255 // VOP2
v_and_b32_e32 v255, 0xdeadbeef, v0 // VOP2
v_or_b32_e32 v0, m0, v255 // VOP2
v_xor_b32_e32 v255, vcc_lo, v0 // VOP2
v_add_nc_u32_e32 v0, exec_lo, v255 // VOP2
v_fmamk_f32 v255, v0, 0x3f800001, v255 // VOP2
v_fmaak_f32 v0, v255, v0, 0xdeadbeef // VOP2
v_add_f32_sdwa v255, v0, v255 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:WORD_0 // VOP2
v_add_f32_dpp v0, v255, v0 row_shl:7 bound_ctrl:1 // VOP2
v_mul_f32_dpp v255, v0, v255 dpp8:[1,2,3,4,5,6,7,0] fi:1 // VOP2
v_cmp_eq_f32_e32 vcc_lo, 0.5, v255 // VOPC
v_cmp_lt_f32_e32 vcc_lo, -4.0, v0 // VOPC
v_cmp_ge_f32_e32 vcc_lo, 0x3f800001, v255 // VOPC
v_cmp_ne_u32_e32 vcc_lo, 0xdeadbeef, v0 // VOPC
v_cmp_gt_i32_e32 vcc_lo, -16, v255 // VOPC
v_cmp_le_i32_e32 vcc_lo, s105, v0 // VOPC
v_cmpx_eq_u32_e32 64, v255 // VOPC
v_cmp_eq_i32_sdwa s105, v255, v0 src0_sel:WORD_0 src1_sel:BYTE_3 // VOPC
v_cmp_lt_u32_sdwa vcc_lo, v0, v255 src0_sel:BYTE_1 src1_sel:WORD_1 // VOPC
v_cmp_class_f32_e32 vcc_lo, v0, v255 // VOPC
v_add_f32_e64 v255, -v0, |v255| clamp // VOP3
v_add_f32_e64 v0, 0x3f800001, v255 // VOP3
v_mul_f32_e64 v255, v0, 0.5 mul:2 // VOP3
v_fma_f32 v0, v255, 0x3f800001, v0 // VOP3
v_fma_f32 v255, -v0, |v255|, -4.0 // VOP3
v_mad_u32_u24 v0, v255, 64, v0 // VOP3
v_mad_i32_i24 v255, v0, -16, v255 // VOP3
v_min3_f32 v0, v255, v0, 0.5 // VOP3
v_max3_i32 v255, v0, v255, -16 // VOP3
v_med3_u32 v0, v255, v0, 64 // VOP3
v_bfe_u32 v255, v0, 31, 1 // VOP3
v_bfe_i32 v0, v255, 0, 32 // VOP3
v_bfi_b32 v255, v0, v255, 0x12345678 // VOP3
v_alignbit_b32 v0, v255, v0, 31 // VOP3
v_cmp_eq_u32_e64 s105, v255, 0xdeadbeef // VOP3
v_readlane_b32 s105, v255, 31 // VOP3
v_writelane_b32 v255, s105, 31 // VOP3
v_add_co_u32 v255, s105, v0, v255 // VOP3SDST
v_add_co_u32 v0, vcc_lo, 0xdeadbeef, v255 // VOP3SDST
v_sub_co_u32 v255, s0, v0, v255 // VOP3SDST
v_subrev_co_u32 v0, s105, v255, v0 // VOP3SDST
v_div_scale_f32 v255, s105, v0, v0, v255 // VOP3SDST
v_div_scale_f64 v[254:255], vcc_lo, v[0:1], v[0:1], v[2:3] // VOP3SDST
v_pk_add_f16 v255, v0, v255 op_sel:[1,0] op_sel_hi:[0,1] // VOP3P
v_pk_mul_f16 v0, v255, 0x3c01 // VOP3P
v_pk_fma_f16 v255, v0, v255, 0x3c01 // VOP3P
v_pk_add_i16 v0, v255, 64 clamp // VOP3P
v_pk_sub_i16 v255, v0, -16 // VOP3P
v_pk_mul_lo_u16 v0, v255, v0 // VOP3P
v_pk_min_i16 v255, v0, v255 // VOP3P
v_pk_max_u16 v0, v255, v0 // VOP3P
v_pk_lshlrev_b16 v255, 15, v0 // VOP3P
v_dot2_f32_f16 v0, v255, v0, 0.5 // VOP3P
v_interp_p1_f32 v255, v0, attr32.w // VINTRP
v_interp_p2_f32 v0, v255, attr0.x // VINTRP
v_interp_mov_f32 v255, p0, attr32.y // VINTRP
v_interp_mov_f32 v0, p10, attr1.z // VINTRP
v_interp_p1_f32 v0, v255, attr1.y // VINTRP
v_interp_p2_f32 v255, v0, attr31.z // VINTRP
ds_write_b32 v255, v0 offset:65535 // DS
ds_read_b32 v0, v255 offset:65535 // DS
ds_write_b8 v0, v255 offset:0 // DS
ds_write_b16 v255, v0 offset:32768 // DS
ds_read_u8 v0, v255 offset:1 // DS
ds_read_i16 v255, v0 offset:65534 // DS
ds_write_b64 v255, v[254:255] offset:8 // DS
ds_read_b64 v[0:1], v255 offset:16 // DS
ds_write2_b32 v0, v255, v0 offset0:255 offset1:0 // DS
ds_read2_b32 v[254:255], v0 offset0:0 offset1:255 // DS
ds_add_u32 v255, v0 offset:65535 // DS
ds_add_rtn_u32 v0, v255, v0 offset:1 // DS
ds_cmpst_b32 v0, v255, v0 offset:32 // DS
ds_bpermute_b32 v255, v0, v255 // DS
ds_permute_b32 v0, v255, v0 // DS
buffer_load_dword v255, off, s[100:103], 0 offset:4095 // MUBUF
buffer_load_dword v0, v255, s[0:3], s105 offen offset:1 // MUBUF
buffer_load_dword v255, v0, s[0:3], 0 idxen // MUBUF
buffer_load_dword v0, v[254:255], s[0:3], 0 idxen offen glc slc // MUBUF
buffer_load_ubyte v255, off, s[0:3], 0 // MUBUF
buffer_load_sshort v0, off, s[0:3], 0 // MUBUF
buffer_load_dwordx2 v[254:255], off, s[0:3], 0 offset:4095 // MUBUF
buffer_load_dwordx3 v[0:2], off, s[0:3], 0 // MUBUF
buffer_store_dwordx4 v[252:255], off, s[100:103], 0 offset:4095 // MUBUF
buffer_store_byte v0, v255, s[0:3], s105 offen // MUBUF
buffer_atomic_add v255, off, s[0:3], 0 glc // MUBUF
buffer_atomic_cmpswap v[254:255], off, s[0:3], 0 glc // MUBUF
tbuffer_load_format_x v255, off, s[100:103], 0 format:[BUF_FMT_32_UINT] offset:4095 // MTBUF
tbuffer_load_format_xy v[0:1], v255, s[0:3], s105 format:[BUF_FMT_32_32_FLOAT] offen // MTBUF
tbuffer_load_format_xyz v[253:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_FLOAT] // MTBUF
tbuffer_load_format_xyzw v[0:3], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] // MTBUF
tbuffer_store_format_x v255, v0, s[100:103], 0 format:[BUF_FMT_32_SINT] idxen // MTBUF
tbuffer_store_format_xy v[254:255], off, s[0:3], 0 format:[BUF_FMT_32_32_UINT] // MTBUF
tbuffer_store_format_xyz v[0:2], off, s[0:3], 0 format:[BUF_FMT_32_32_32_UINT] // MTBUF
tbuffer_store_format_xyzw v[252:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_UINT] offset:4095 // MTBUF
tbuffer_load_format_d16_xy v255, off, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] // MTBUF
tbuffer_store_format_d16_xyzw v[254:255], off, s[0:3], 0 format:[BUF_FMT_16_16_16_16_FLOAT] // MTBUF
image_load v255, v0, s[96:103] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm // MIMG
image_load_mip v[254:255], v[0:2], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm // MIMG
image_store v255, v[0:1], s[0:7] dmask:0x8 dim:SQ_RSRC_IMG_2D unorm // MIMG
image_sample v[252:255], [v255,v0], s[0:7], s[100:103] dmask:0xf dim:SQ_RSRC_IMG_2D // MIMG
image_sample v255, [v0,v128,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_sample_c v[254:255], [v255,v5,v1,v0], s[0:7], s[8:11] dmask:0x5 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
image_sample_c_l v255, [v0,v2,v4,v6,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
image_sample_d v255, [v0,v2,v4,v6,v8,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D // MIMG
image_sample_d v0, [v255,v2,v4,v6,v8,v10,v12,v14,v16], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_gather4 v[252:255], v[0:1], s[0:7], s[8:11] dmask:0x8 dim:SQ_RSRC_IMG_2D // MIMG
image_atomic_add v255, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc // MIMG
image_sample_d_cl v255, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_sample_c_d_cl v0, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18,v20], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
exp mrt0 v255, off, off, v0 done // EXP
exp mrt7 off, v255, v0, off // EXP
exp pos0 v0, v255, v0, v255 done // EXP
exp pos3 v255, v0, v255, v0 // EXP
exp param0 v255, off, v0, off // EXP
exp param31 v0, v255, off, off // EXP
exp null off, off, off, off done // EXP
flat_load_dword v255, v[0:1] offset:2047 // FLAT
flat_load_dword v0, v[254:255] offset:1024 // FLAT
flat_load_ubyte v255, v[0:1] offset:0 // FLAT
flat_load_sbyte v0, v[254:255] glc // FLAT
flat_load_dwordx2 v[254:255], v[0:1] slc // FLAT
flat_load_dwordx4 v[0:3], v[254:255] // FLAT
flat_store_dword v[254:255], v0 offset:2047 // FLAT
flat_store_short v[0:1], v255 offset:1 // FLAT
flat_atomic_add v255, v[0:1], v255 glc // FLAT
flat_atomic_swap v[254:255], v0 // FLAT
global_load_dword v255, v[0:1], off offset:-2048 // GLOBAL
global_load_dword v0, v255, s[104:105] offset:2047 // GLOBAL
global_load_ubyte v255, v0, s[0:1] // GLOBAL
global_load_dwordx3 v[253:255], v[0:1], off glc // GLOBAL
global_store_dword v255, v0, s[104:105] offset:-2048 // GLOBAL
global_store_dwordx4 v[254:255], v[0:3], off offset:2047 // GLOBAL
global_store_byte v0, v255, s[0:1] // GLOBAL
global_atomic_or v255, v0, v255, s[104:105] glc // GLOBAL
global_atomic_add v[254:255], v0, off // GLOBAL
scratch_load_dword v255, v0, off offset:2047 // SCRATCH
scratch_load_dword v0, off, s105 offset:-2048 // SCRATCH
scratch_load_ushort v255, v0, off // SCRATCH
scratch_load_dwordx2 v[254:255], off, s0 // SCRATCH
scratch_load_dwordx4 v[0:3], v255, off // SCRATCH
scratch_store_dword v255, v0, off offset:-2048 // SCRATCH
scratch_store_dword off, v255, s0 offset:2047 // SCRATCH
scratch_store_byte v0, v255, off // SCRATCH
scratch_store_dwordx4 off, v[252:255], s105 // SCRATCH
// Forms the byte probes could not reach with legal operands (FLAT SADDR, DS GDS, BVH).
ds_gws_init v1 offset:65535 gds // DS
ds_gws_barrier v1 offset:0 gds // DS
ds_gws_sema_v gds // DS
ds_gws_sema_br v1 gds // DS
ds_gws_sema_p gds // DS
ds_gws_sema_release_all gds // DS
ds_ordered_count v0, v1 offset:65535 gds // DS
flat_load_dwordx3 v[0:2], v[254:255] offset:2047 // FLAT
flat_load_sshort v255, v[254:255] offset:2047 // FLAT
flat_load_ushort v0, v[254:255] offset:2047 // FLAT
flat_load_sbyte_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_sbyte_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_load_short_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_short_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_load_ubyte_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_ubyte_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_store_byte v[0:1], v2 // FLAT
flat_store_byte_d16_hi v[0:1], v2 // FLAT
flat_store_dwordx2 v[0:1], v[2:3] // FLAT
flat_store_dwordx3 v[0:1], v[2:4] // FLAT
flat_store_dwordx4 v[0:1], v[2:5] // FLAT
flat_store_short_d16_hi v[0:1], v2 // FLAT
flat_atomic_add v0, v[0:1], v2 glc // FLAT
flat_atomic_add_x2 v[0:1], v[2:3] // FLAT
flat_atomic_and v0, v[0:1], v2 glc // FLAT
flat_atomic_and_x2 v[0:1], v[2:3] // FLAT
flat_atomic_dec v0, v[0:1], v2 glc // FLAT
flat_atomic_dec_x2 v[0:1], v[2:3] // FLAT
flat_atomic_inc v0, v[0:1], v2 glc // FLAT
flat_atomic_inc_x2 v[0:1], v[2:3] // FLAT
flat_atomic_or v0, v[0:1], v2 glc // FLAT
flat_atomic_or_x2 v[0:1], v[2:3] // FLAT
flat_atomic_smax v0, v[0:1], v2 glc // FLAT
flat_atomic_smax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_smin v0, v[0:1], v2 glc // FLAT
flat_atomic_smin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_sub v0, v[0:1], v2 glc // FLAT
flat_atomic_sub_x2 v[0:1], v[2:3] // FLAT
flat_atomic_umax v0, v[0:1], v2 glc // FLAT
flat_atomic_umax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_umin v0, v[0:1], v2 glc // FLAT
flat_atomic_umin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_xor v0, v[0:1], v2 glc // FLAT
flat_atomic_xor_x2 v[0:1], v[2:3] // FLAT
flat_atomic_fmax v0, v[0:1], v2 glc // FLAT
flat_atomic_fmax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_fmin v0, v[0:1], v2 glc // FLAT
flat_atomic_fmin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_swap_x2 v[0:1], v[2:3] offset:2047 // FLAT
flat_atomic_cmpswap v0, v[0:1], v[2:3] glc // FLAT
flat_atomic_cmpswap_x2 v[0:1], v[2:5] // FLAT
flat_atomic_fcmpswap v[0:1], v[2:3] // FLAT
flat_atomic_fcmpswap_x2 v[0:1], v[2:5] // FLAT
image_bvh_intersect_ray v[0:3], v[0:10], s[0:3] // MIMG
image_bvh64_intersect_ray v[0:3], v[0:11], s[0:3] // MIMG
image_bvh_intersect_ray v[0:3], [v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14], s[0:3] // MIMG
v_interp_p1ll_f16 v0, v1, attr0.x // VOP3
v_interp_p1lv_f16 v0, v1, attr0.x, v2 // VOP3
v_interp_p2_f16 v0, v1, attr0.x, v2 // VOP3
v_mqsad_u32_u8 v[0:3], v[2:3], v4, v[4:7] // VOP3
v_permlane16_b32 v0, v1, s2, s3 // VOP3
v_permlanex16_b32 v255, v1, s105, m0 op_sel:[1,1] // VOP3
v_swaprel_b32 v0, v1 // VOP1
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
# Rows of the asm, probe-zero and probe-ext sources where identify and LLVM do not simply agree
# (neither `identified` nor `both_reject`), as `class hex`, sorted by hex. Pinned by meta_corpus.rs;
# review each change against LLVM.
operand_flagged 000000d60000000000000000000000000000000000000000
operand_flagged 000000d6ff00000078563412000000000000000000000000
metadata_only 000000dd0000000000000000000000000000000000000000
operand_flagged 000001d60000000000000000000000000000000000000000
operand_flagged 000001d6ff00000078563412000000000000000000000000
metadata_only 000008f10000000000000000000000000000000000000000
metadata_only 00000cf10000000000000000000000000000000000000000
metadata_only 000020dc0000000000000000000000000000000000000000
metadata_only 000024dc0000000000000000000000000000000000000000
metadata_only 000028dc0000000000000000000000000000000000000000
metadata_only 000028f10000000000000000000000000000000000000000
metadata_only 00002cdc0000000000000000000000000000000000000000
metadata_only 00002cf10000000000000000000000000000000000000000
metadata_only 000030dc0000000000000000000000000000000000000000
metadata_only 000034dc0000000000000000000000000000000000000000
metadata_only 000038dc0000000000000000000000000000000000000000
metadata_only 00003cdc0000000000000000000000000000000000000000
metadata_only 000040dd0000000000000000000000000000000000000000
operand_flagged 000042d70000000000000000000000000000000000000000
operand_flagged 000042d7ff00000078563412000000000000000000000000
operand_flagged 000043d70000000000000000000000000000000000000000
operand_flagged 000043d7ff00000078563412000000000000000000000000
metadata_only 000044dd0000000000000000000000000000000000000000
metadata_only 000048dd0000000000000000000000000000000000000000
metadata_only 000048f10000000000000000000000000000000000000000
metadata_only 00004cdd0000000000000000000000000000000000000000
metadata_only 00004cf10000000000000000000000000000000000000000
metadata_only 000054dd0000000000000000000000000000000000000000
metadata_only 000058dd0000000000000000000000000000000000000000
operand_flagged 00005ad70000000000000000000000000000000000000000
operand_flagged 00005ad7ff00000078563412000000000000000000000000
metadata_only 00005cdd0000000000000000000000000000000000000000
operand_flagged 000060d70000000000000000000000000000000000000000
metadata_only 000060d80000000000000000000000000000000000000000
metadata_only 000060dc0000000000000000000000000000000000000000
metadata_only 000060dd0000000000000000000000000000000000000000
metadata_only 000064d80000000000000000000000000000000000000000
metadata_only 000064dc0000000000000000000000000000000000000000
metadata_only 000064dd0000000000000000000000000000000000000000
metadata_only 000068d80000000000000000000000000000000000000000
metadata_only 000068dc0000000000000000000000000000000000000000
metadata_only 000068dd0000000000000000000000000000000000000000
metadata_only 000068f10000000000000000000000000000000000000000
metadata_only 00006cd80000000000000000000000000000000000000000
metadata_only 00006cdc0000000000000000000000000000000000000000
metadata_only 00006cdd0000000000000000000000000000000000000000
metadata_only 00006cf10000000000000000000000000000000000000000
metadata_only 000070d80000000000000000000000000000000000000000
metadata_only 000070dc0000000000000000000000000000000000000000
metadata_only 000070dd0000000000000000000000000000000000000000
metadata_only 000074d80000000000000000000000000000000000000000
metadata_only 000074dc0000000000000000000000000000000000000000
metadata_only 000074dd0000000000000000000000000000000000000000
operand_flagged 000075d50000000000000000000000000000000000000000
operand_flagged 000075d5ff00000078563412000000000000000000000000
operand_flagged 000077d70000000000000000000000000000000000000000
operand_flagged 000077d7ff00000078563412000000000000000000000000
operand_flagged 000078d70000000000000000000000000000000000000000
operand_flagged 000078d7ff00000078563412000000000000000000000000
metadata_only 000078dc0000000000000000000000000000000000000000
metadata_only 000078dd0000000000000000000000000000000000000000
metadata_only 00007cdc0000000000000000000000000000000000000000
metadata_only 00007cdd0000000000000000000000000000000000000000
oracle_only 000080d5ff00000078563412000000000000000000000000
metadata_only 000080dc0000000000000000000000000000000000000000
metadata_only 000080dd0000000000000000000000000000000000000000
metadata_only 000082d50000000000000000000000000000000000000000
metadata_only 000084dc0000000000000000000000000000000000000000
metadata_only 000088dc0000000000000000000000000000000000000000
metadata_only 000088f10000000000000000000000000000000000000000
metadata_only 00008cdc0000000000000000000000000000000000000000
metadata_only 00008cf10000000000000000000000000000000000000000
metadata_only 000090dc0000000000000000000000000000000000000000
metadata_only 000094dc0000000000000000000000000000000000000000
oracle_only 00009bd5ff00000078563412000000000000000000000000
metadata_only 0000c0dc0000000000000000000000000000000000000000
metadata_only 0000c0f10000000000000000000000000000000000000000
oracle_only 0000c1d5ff00000078563412000000000000000000000000
operand_flagged 0000c3d50000000000000000000000000000000000000000
operand_flagged 0000c4d50000000000000000000000000000000000000000
metadata_only 0000c4dc0000000000000000000000000000000000000000
metadata_only 0000c4f10000000000000000000000000000000000000000
operand_flagged 0000c8d50000000000000000000000000000000000000000
metadata_only 0000c8dc0000000000000000000000000000000000000000
metadata_only 0000ccdc0000000000000000000000000000000000000000
metadata_only 0000ccf10000000000000000000000000000000000000000
metadata_only 0000d0f10000000000000000000000000000000000000000
metadata_only 0000d4dc0000000000000000000000000000000000000000
metadata_only 0000d8dc0000000000000000000000000000000000000000
metadata_only 0000d8f10000000000000000000000000000000000000000
metadata_only 0000dcdc0000000000000000000000000000000000000000
metadata_only 0000dcf10000000000000000000000000000000000000000
metadata_only 0000e0dc0000000000000000000000000000000000000000
metadata_only 0000e4dc0000000000000000000000000000000000000000
metadata_only 0000e4f10000000000000000000000000000000000000000
metadata_only 0000e8dc0000000000000000000000000000000000000000
metadata_only 0000e8f10000000000000000000000000000000000000000
metadata_only 0000ecdc0000000000000000000000000000000000000000
metadata_only 0000f0dc0000000000000000000000000000000000000000
metadata_only 0000f4dc0000000000000000000000000000000000000000
metadata_only 0000f8dc0000000000000000000000000000000000000000
metadata_only 0000fcd80000000000000000000000000000000000000000
metadata_only 0000fcdc0000000000000000000000000000000000000000
operand_flagged 0004007e00000000000000000000000000000000
operand_flagged 0086007e00000000000000000000000000000000
operand_flagged 0088007e00000000000000000000000000000000
operand_flagged 0090007e00000000000000000000000000000000
operand_flagged 00ca007e00000000000000000000000000000000
operand_flagged 00d0007e00000000000000000000000000000000
metadata_only 010098f10000000000000000000000000000000000000000
metadata_only 01009cf10000000000000000000000000000000000000000
oracle_only e900007e0088c6fa000000000000000000000000
oracle_only e936007e0088c6fa000000000000000000000000
oracle_only e982007e0088c6fa000000000000000000000000
oracle_only ea00007e0088c6fa000000000000000000000000
oracle_only ea36007e0088c6fa000000000000000000000000
oracle_only ea82007e0088c6fa000000000000000000000000
oracle_only f900007e00060600000000000000000000000000
oracle_only f936007e00060600000000000000000000000000
oracle_only f982007e00060600000000000000000000000000
oracle_only fa00007e00e400ff000000000000000000000000
oracle_only fa36007e00e400ff000000000000000000000000
oracle_only fa82007e00e400ff000000000000000000000000
oracle_only ff00007e78563412000000000000000000000000
oracle_only ff1f80be78563412000000000000000000000000
oracle_only ff2180be78563412000000000000000000000000
oracle_only ff36007e78563412000000000000000000000000
oracle_only ff4980be78563412000000000000000000000000
oracle_only ff82007e78563412000000000000000000000000
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// One instruction per line for each family and extension word; checked against llvm-mc.
s_mov_b32 s0, 0x12345678
s_add_u32 s0, s1, 0x1234
s_cmp_eq_u32 s0, 0xdeadbeef
s_movk_i32 s0, 0x1234
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x0
s_load_dwordx4 s[0:3], s[4:5], 0x10
s_nop 0
s_endpgm
v_mov_b32 v0, 0x12345678
v_mov_b32_sdwa v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:DWORD
v_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6]
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6] fi:1
v_add_f32_sdwa v0, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD
v_add_f32_dpp v0, v1, v2 row_shl:1 row_mask:0xf bank_mask:0xf
v_cmp_eq_u32_e32 vcc_lo, 0x1234, v1
v_cmp_eq_u32_sdwa s0, v1, v2 src0_sel:DWORD src1_sel:DWORD
v_fmamk_f32 v0, v1, 0x40000000, v2
v_fmaak_f32 v0, v1, v2, 0x40000000
v_fma_f32 v0, v1, v2, 0x3f800001
v_add_co_u32 v0, s0, v1, v2
v_readlane_b32 s0, v1, 0
v_pk_add_f16 v0, v1, v2
v_pk_fma_f16 v0, v1, v2, 0x3c01
v_interp_p1_f32 v0, v1, attr0.x
ds_write_b32 v0, v1
ds_read_b32 v0, v1 offset:16
buffer_load_dword v0, off, s[0:3], 0
tbuffer_load_format_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
tbuffer_load_format_d16_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
tbuffer_store_format_d16_xyzw v[0:1], off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
image_sample v[0:3], v[0:1], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample v[0:3], [v0, v2], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample_c v[0:3], [v0, v2, v4, v6], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY
image_msaa_load v[0:3], v[0:2], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm
flat_load_dword v0, v[0:1]
global_load_dword v0, v[0:1], off
scratch_load_dword v0, v1, off
exp mrt0 v0, v0, v0, v0 done
+55 -2
View File
@@ -70,8 +70,8 @@ fn hand_assembled_words_identify() {
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
// VOP3 v_add_f32_e64 v0, v1, v2: VOP3 opcode 259 = 256 + VOP2 opcode 3.
assert_eq!(name_of(&[0xd503_0000, 0x0002_0501]), ("V_ADD_F32", 8));
// VOP3 v_add_f32_e64 v0, v1, v2 (LLVM 23 encoding): opcode 259 = 256 + VOP2 opcode 3.
assert_eq!(name_of(&[0xd503_0000, 0x0202_0501]), ("V_ADD_F32", 8));
}
#[test]
@@ -99,6 +99,32 @@ fn literal_sdwa_and_dpp_words_extend_the_length() {
);
}
#[test]
fn vop3_interpolation_attribute_fields_never_select_a_literal() {
// AMD RDNA 2 ISA guide section 10.4.2: in the VOP3 interpolation forms SRC0
// holds {attr_word, attr_chan, attr} bit-fields (XML OPR_ATTR), so SRC0 = 255
// is attr 63, channel w (and attr_word 0) and the instruction is 8 bytes.
// LLVM 23.1.6 agrees (#235).
for (first, name) in [
(0xd600_0000, "V_INTERP_P1_F32"),
(0xd601_0000, "V_INTERP_P2_F32"),
(0xd602_0000, "V_INTERP_MOV_F32"),
(0xd742_0000, "V_INTERP_P1LL_F16"),
(0xd743_0000, "V_INTERP_P1LV_F16"),
(0xd75a_0000, "V_INTERP_P2_F16"),
] {
let found = identify(&words(&[first, 0x0000_00ff, 0x1234_5678])).unwrap();
assert_eq!((found.form.name, found.len), (name, 8));
assert!(!found.trailer.literal, "{name}");
}
// A general VOP3 source with the same selector still takes the literal.
let add = identify(&words(&[0xd503_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
assert_eq!((add.form.name, add.len), ("V_ADD_F32", 12));
// So does a VGPR-only source (LLVM reports these 12 bytes with an invalid operand).
let permlane = identify(&words(&[0xd777_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
assert_eq!((permlane.form.name, permlane.len), ("V_PERMLANE16_B32", 12));
}
#[test]
fn truncated_and_unassigned_inputs_are_rejected() {
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
@@ -154,6 +180,33 @@ fn every_form_identifies_as_itself() {
assert_eq!(total, FORMS.len());
}
#[test]
fn documented_form_counts_match_the_generated_table() {
let count = FORMS.len();
let count = format!("{},{:03}", count / 1000, count % 1000);
let families = EncodingFamily::ALL.len();
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
for (file, claim) in [
(
"docs/research/rdna2.md",
format!("{count} forms in {families} encoding families"),
),
(
"CHANGELOG.md",
format!("{count} base forms across {families} encoding families"),
),
] {
let text = fs::read_to_string(root.join(file)).unwrap();
assert!(
text.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.contains(&claim),
"{file} must state \"{claim}\""
);
}
}
#[test]
fn first_word_opcode_table_agrees_with_full_metadata() {
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
+304
View File
@@ -0,0 +1,304 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent LLVM corpus check of gfx1030 instruction identification (#209).
//!
//! `llvm/corpus.tsv` is generated by `llvm/corpus.py` from LLVM 23.1.6 alone:
//! llvm-mc assembles the original instructions in `llvm/corpus.s`, and
//! llvm-objdump decodes byte probes built from each metadata form's
//! identifying bits (one with every other bit zero, two with seeded random
//! operand bits). The expected name, consumed length and extension of every
//! row are LLVM's. This test compares `identify` with them and pins what it
//! measures: per-source class counts, the exact rows where the two disagree
//! for assembled and zero-operand inputs, and a digest of the random-probe
//! classification.
//!
//! Identification is not execution support: a row counted as identified only
//! means both agree on which instruction the bytes are and how long it is.
use std::collections::BTreeMap;
use xenora_isa::meta::{FORMS, Identified, IdentifyError, VectorControl, identify};
const CORPUS: &str = include_str!("llvm/corpus.tsv");
/// Row classes, in report order.
const CLASSES: [&str; 9] = [
"identified", // both decode: same name, length and extension
"mismatch", // both decode, but name, length or extension differ
"oracle_only", // LLVM decodes, identify returns an error
"metadata_only", // identify decodes, LLVM cannot
"both_reject", // neither decodes
"oracle_crash", // llvm-objdump crashed; no oracle answer
"truncated", // a proper prefix: identify asks for more bytes
"truncation_other",
"operand_flagged", // same instruction and length; LLVM flags an operand as invalid
];
const SOURCES: [&str; 5] = [
"asm",
"probe-zero",
"probe-ext",
"probe-random",
"truncation",
];
fn base_name(mnemonic: &str) -> String {
let upper = mnemonic.to_ascii_uppercase();
["_E32", "_E64", "_SDWA", "_DPP"]
.into_iter()
.find_map(|suffix| upper.strip_suffix(suffix))
.unwrap_or(&upper)
.to_owned()
}
fn extension(found: &Identified) -> String {
let nsa = format!("nsa{}", found.trailer.nsa_dwords);
let mut parts = Vec::new();
if found.trailer.literal {
parts.push("literal");
}
match found.trailer.vector_control {
Some(VectorControl::Sdwa) => parts.push("sdwa"),
Some(VectorControl::Dpp8 {
fetch_inactive: false,
}) => parts.push("dpp8"),
Some(VectorControl::Dpp8 {
fetch_inactive: true,
}) => parts.push("dpp8fi"),
Some(VectorControl::Dpp16) => parts.push("dpp16"),
None => {}
}
if found.trailer.nsa_dwords != 0 {
parts.push(&nsa);
}
if parts.is_empty() {
"-".into()
} else {
parts.join("+")
}
}
struct Row<'a> {
source: usize,
form: Option<&'static str>,
family: &'a str,
hex: &'a str,
class: usize,
detail: String,
}
fn classify(line: &str) -> Row<'_> {
let [source, hex, mnemonic, len, ext, note] = line.split('\t').collect::<Vec<_>>()[..] else {
panic!("bad corpus row: {line}");
};
let source = SOURCES
.iter()
.position(|s| *s == source)
.unwrap_or_else(|| panic!("bad source: {line}"));
let (family, text) = note.split_once(' ').unwrap();
let bytes: Vec<u8> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
.collect();
let len: usize = len.parse().unwrap();
let found = identify(&bytes);
let answer = match &found {
Ok(found) => format!(
"{} ({} bytes, {})",
found.form.name,
found.len,
extension(found)
),
Err(error) => format!("{error:?}"),
};
let mut differences = Vec::new();
// LLVM decoded the words but flagged an operand the instruction cannot
// take. identify does not validate operands; it must still agree on the
// instruction and its length, or reject the extension outright.
let (flagged, mnemonic) = match mnemonic.strip_prefix("invalid-operand:") {
Some(mnemonic) => (true, mnemonic),
None => (false, mnemonic),
};
let class = match (mnemonic, &found) {
("truncated", Err(IdentifyError::Truncated { needed })) if *needed > bytes.len() => 6,
("truncated", _) => 7,
("crashed", _) => 5,
("invalid", Err(_)) => 4,
("invalid", Ok(_)) => 3,
(_, Err(IdentifyError::InvalidExtension(_))) if flagged => 4,
(_, Err(_)) => 2,
(_, Ok(found)) => {
if found.form.name != base_name(mnemonic) {
differences.push("name");
}
if found.len != len {
differences.push("length");
}
if extension(found) != ext {
differences.push("extension");
}
if !differences.is_empty() {
1
} else if flagged {
8
} else {
0
}
}
};
let kind = if differences.is_empty() {
CLASSES[class].to_owned()
} else {
format!("mismatch/{}", differences.join("+"))
};
Row {
source,
form: found.ok().map(|found| found.form.name),
family,
hex,
class,
detail: format!("{kind}: {hex} | LLVM {text} ({len} bytes, {ext}) | Xenora {answer}"),
}
}
/// FNV-1a over the sorted `class hex` lines, to pin thousands of rows compactly.
fn digest(lines: &[String]) -> u64 {
lines
.iter()
.flat_map(|l| l.bytes().chain(*b"\n"))
.fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
})
}
// Measured against LLVM 23.1.6 on 2026-11-24. Any change needs the affected
// rows reviewed against LLVM, not an update of these numbers alone.
// Rows: one per source, columns in CLASSES order.
const COUNTS: [[usize; 9]; 5] = [
[317, 0, 0, 0, 0, 0, 0, 0, 0], // asm
[1365, 0, 0, 82, 0, 0, 0, 0, 18], // probe-zero
[1398, 0, 21, 0, 752, 0, 0, 0, 8], // probe-ext
[1236, 0, 0, 1678, 3, 2, 0, 0, 11], // probe-random
[0, 0, 0, 0, 0, 0, 87, 0, 0], // truncation
];
/// Every assembled, zero-operand or extension-probe row where the two disagree
/// (neither `identified` nor `both_reject`), as `class hex`, sorted by hex.
const DISAGREEMENTS: &str = include_str!("llvm/corpus_disagreements.txt");
/// Digest of the sorted `class hex` lines of the random probes.
const RANDOM_DIGEST: u64 = 0x32fb_5d7d_0826_ce14;
#[test]
fn identification_agrees_with_the_llvm_corpus() {
let mut lines = CORPUS.lines();
assert_eq!(
lines.next(),
Some("source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote")
);
let rows: Vec<_> = lines.map(classify).collect();
let mut counts = [[0usize; 9]; 5];
let mut by_family = BTreeMap::<&str, [usize; 9]>::new();
for row in &rows {
counts[row.source][row.class] += 1;
by_family.entry(row.family).or_default()[row.class] += 1;
}
println!("{:9} {}", "family", CLASSES.join(" "));
for (family, c) in &by_family {
print!("{family:9}");
for (name, n) in CLASSES.iter().zip(c) {
print!(" {n:>w$}", w = name.len());
}
println!();
}
for (source, c) in SOURCES.iter().zip(&counts) {
println!("{source:13} {c:?}");
}
let mut disagreements: Vec<_> = rows
.iter()
.filter(|r| r.source < 3 && !matches!(r.class, 0 | 4))
.collect();
disagreements.sort_unstable_by_key(|r| r.hex);
for r in &disagreements {
println!("{}", r.detail);
}
let disagreements: Vec<_> = disagreements
.iter()
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
.collect();
let mut random: Vec<_> = rows
.iter()
.filter(|r| r.source == 3)
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
.collect();
random.sort_unstable();
let random_digest = digest(&random);
println!("random digest {random_digest:#018x}");
for r in rows
.iter()
.filter(|r| r.source == 3 && r.class == 1)
.take(5)
{
println!("random example {}", r.detail);
}
// Distinct metadata forms: agreed by LLVM on at least one row, or only
// ever decoded by Xenora (LLVM rejected every probe of that form).
let mut forms = BTreeMap::<&str, (usize, usize)>::new();
for row in &rows {
if let Some(form) = row.form {
let entry = forms.entry(form).or_default();
match row.class {
0 | 8 => entry.0 += 1,
3 => entry.1 += 1,
_ => {}
}
}
}
let agreed = forms.values().filter(|(a, _)| *a > 0).count();
let never: Vec<_> = forms
.iter()
.filter(|(_, (a, m))| *a == 0 && *m > 0)
.map(|(name, _)| *name)
.collect();
println!(
"distinct forms seen {}: agreed {agreed}, metadata-only on every row {}",
forms.len(),
never.len()
);
println!("never decoded by LLVM: {}", never.join(" "));
let mut all_names: Vec<_> = FORMS.iter().map(|form| form.name).collect();
all_names.sort_unstable();
all_names.dedup();
let unseen: Vec<_> = all_names
.iter()
.filter(|name| !forms.contains_key(*name))
.collect();
println!(
"metadata: {} forms, {} distinct names, {} names with no corpus row: {unseen:?}",
FORMS.len(),
all_names.len(),
unseen.len()
);
assert_eq!(counts, COUNTS, "class counts per source changed");
let pinned: Vec<_> = DISAGREEMENTS
.lines()
.filter(|line| !line.starts_with('#'))
.collect();
assert_eq!(disagreements, pinned, "disagreeing rows changed");
assert_eq!(
random_digest, RANDOM_DIGEST,
"random-probe classification changed"
);
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target (set LLVM_BIN)"]
fn llvm_corpus_is_fresh() {
let bin = std::env::var("LLVM_BIN").expect("LLVM_BIN");
let status = std::process::Command::new("python3")
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/llvm/corpus.py"))
.args(["--llvm-bin", &bin, "--check"])
.status()
.expect("run corpus.py");
assert!(
status.success(),
"corpus.tsv differs from LLVM's current output"
);
}
+87
View File
@@ -0,0 +1,87 @@
//! LLVM oracle for instruction identification: names and lengths from llvm-mc encodings.
use std::process::Command;
use xenora_isa::meta::identify;
const SOURCE: &str = include_str!("llvm/identify.s");
fn encodings() -> Vec<(String, Vec<u8>)> {
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|| "llvm-mc".into(),
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
);
let path = std::env::temp_dir().join(format!("xenora-identify-{}.s", std::process::id()));
std::fs::write(&path, SOURCE).unwrap();
let output = Command::new(executable)
.args([
"-triple=amdgcn-amd-amdhsa",
"-mcpu=gfx1030",
"-mattr=+wavefrontsize32",
"-show-encoding",
])
.arg(&path)
.output()
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
std::fs::remove_file(&path).ok();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout)
.unwrap()
.lines()
.filter_map(|line| {
let (text, encoding) = line.split_once("; encoding: [")?;
let mnemonic = text.split_whitespace().next()?.to_ascii_uppercase();
let bytes = encoding
.trim_end_matches(']')
.split(',')
.map(|byte| u8::from_str_radix(byte.trim().trim_start_matches("0x"), 16).unwrap())
.collect();
Some((mnemonic, bytes))
})
.collect()
}
fn base_name(mnemonic: &str) -> &str {
["_E32", "_E64", "_SDWA", "_DPP"]
.iter()
.fold(mnemonic, |name, suffix| name.trim_end_matches(suffix))
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
fn identification_matches_llvm_names_and_lengths() {
let encodings = encodings();
let expected_lines = SOURCE
.lines()
.filter(|line| !line.is_empty() && !line.starts_with("//"))
.count();
assert_eq!(encodings.len(), expected_lines);
// The VOP3 and VOP3P literal probes must really carry a literal trailer:
// 1.0 in either width would be an inline constant and only eight bytes.
for (probe, literal) in [("V_FMA_F32", 0x3f80_0001_u32), ("V_PK_FMA_F16", 0x3c01)] {
let (_, bytes) = encodings
.iter()
.find(|(mnemonic, _)| mnemonic == probe)
.unwrap_or_else(|| panic!("{probe} probe missing"));
assert_eq!(bytes.len(), 12, "{probe}");
assert_eq!(bytes[8..], literal.to_le_bytes(), "{probe}");
}
let mut stream = Vec::new();
for (mnemonic, bytes) in &encodings {
let found = identify(bytes).unwrap_or_else(|error| panic!("{mnemonic}: {error}"));
assert_eq!(found.form.name, base_name(mnemonic), "{mnemonic}");
assert_eq!(found.len, bytes.len(), "{mnemonic}");
stream.extend_from_slice(bytes);
}
let mut offset = 0;
for (mnemonic, bytes) in &encodings {
let found = identify(&stream[offset..]).unwrap();
assert_eq!(found.len, bytes.len(), "{mnemonic} in stream");
offset += found.len;
}
assert_eq!(offset, stream.len());
}
+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
);
}
}
+255 -59
View File
@@ -53,6 +53,25 @@ impl Register {
}
}
/// Instruction prefixes decoded ahead of an opcode.
///
/// The interpreter decodes these once per instruction and passes them to the
/// helpers that need them, so prefix state travels as one typed value instead
/// of a list of independent booleans.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Prefixes {
/// REX.W: 64-bit operand size.
rex_w: bool,
/// REX.R: extends the ModRM `reg` field to R8-R15.
rex_r: bool,
/// REX.B: extends the ModRM `rm` field to R8-R15.
rex_b: bool,
/// The GS segment override prefix (0x65) is present.
seg_gs: bool,
/// The FS segment override prefix (0x64) is present.
seg_fs: bool,
}
/// RFLAGS status bits tracked during guest execution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RFlags {
@@ -153,6 +172,167 @@ mod layout_tests {
}
}
#[cfg(test)]
mod prefix_tests {
use super::{CpuState, ExitReason, Interpreter, Register};
use crate::memory::{GuestMemory, MemoryPermissions};
const CODE_BASE: u64 = 0x1000;
const CODE_SIZE: usize = 0x1000;
const STACK_BASE: u64 = 0x8000_0000;
const STACK_SIZE: usize = 0x10000;
const FS_BASE: u64 = 0x9000;
const GS_BASE: u64 = 0xA000;
/// A guest memory image with executable code, a stack and distinct FS and
/// GS bases.
fn memory_with_code(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
CODE_BASE,
CODE_SIZE,
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.expect("code region");
memory
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
.expect("stack region");
// The segment bases are distinct so a swapped prefix is visible.
memory
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("fs region");
memory
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("gs region");
memory
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run(code: &[u8]) -> (CpuState, ExitReason) {
let mut memory = memory_with_code(code);
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// `mov r8, imm64`: 49 B8 <imm64>.
fn mov_r8_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x49, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rbx, imm64`: 48 BB <imm64>.
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rax, imm64`: 48 B8 <imm64>.
fn mov_rax_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
///
/// Encoding 49 89 D8 is `mov r8, rbx`.
#[test]
fn rex_b_extends_the_rm_field_to_r8() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
///
/// Encoding 4C 89 C3 is `mov rbx, r8`.
#[test]
fn rex_r_extends_the_reg_field_to_r8() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R and REX.B extend independent fields, so the destination r9 and
/// the source r12 are chosen by different prefix bits.
///
/// Encoding 4D 89 E1 is `mov r9, r12`.
#[test]
fn rex_r_and_rex_b_extend_independent_fields() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// r9 receives r12, which is zero here, and not the value in r8.
assert_eq!(state.get(Register::R9), 0);
assert_eq!(state.get(Register::R12), 0);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
}
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
/// low half of the source and its upper half is cleared.
///
/// Encoding 89 D8 is `mov eax, ebx`.
#[test]
fn a_move_without_rex_w_is_32_bit_wide() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
}
/// The FS segment override adds the FS base to the effective address.
///
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
#[test]
fn the_fs_prefix_adds_the_fs_base() {
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
code.push(0xF4); // hlt
let mut memory = memory_with_code(&code);
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
0x1122_3344_5566_7788
);
// The GS base is untouched: the GS-prefixed store did not happen.
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
}
}
/// Result returned after running guest execution.
#[derive(Debug)]
pub struct ExecutionResult {
@@ -246,29 +426,34 @@ 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 mut rex_w = false;
let mut rex_r = false;
let mut rex_b = false;
let mut seg_gs = false;
let mut seg_fs = false;
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 prefixes = Prefixes::default();
let mut byte = self.fetch_u8()?;
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while byte == 0x65 || byte == 0x64 {
if byte == 0x65 {
seg_gs = true;
prefixes.seg_gs = true;
} else {
seg_fs = true;
prefixes.seg_fs = true;
}
byte = self.fetch_u8()?;
}
// Handle REX prefix (0x40 - 0x4F)
if (byte & 0xF0) == 0x40 {
rex_w = (byte & 0x08) != 0;
rex_r = (byte & 0x04) != 0;
rex_b = (byte & 0x01) != 0;
prefixes.rex_w = (byte & 0x08) != 0;
prefixes.rex_r = (byte & 0x04) != 0;
prefixes.rex_b = (byte & 0x01) != 0;
byte = self.fetch_u8()?;
}
@@ -276,22 +461,27 @@ impl<'a> Interpreter<'a> {
// HLT: Halt execution
0xF4 => Ok(Some(ExitReason::Halt)),
// SYSCALL: 0x0F 0x05
0x0F => {
let second = self.fetch_u8()?;
if second == 0x05 {
let syscall_num = self.cpu.get(Register::Rax);
Ok(Some(ExitReason::Syscall(syscall_num)))
} else {
Err(ExitReason::IllegalInstruction(second))
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if prefixes.rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
};
self.cpu.set(reg, reversed);
Ok(None)
}
}
op => Err(ExitReason::IllegalInstruction(op)),
},
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0xB8) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if rex_w {
if prefixes.rex_w {
let imm = self.fetch_u64()?;
self.cpu.set(reg, imm);
} else {
@@ -304,28 +494,28 @@ impl<'a> Interpreter<'a> {
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
0x31 | 0x33 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let res = if rex_w {
let res = if prefixes.rex_w {
val1 ^ val2
} else {
(val1 as u32 ^ val2 as u32) as u64
};
self.cpu.set(dst, res);
self.update_flags_logic(res, rex_w);
self.update_flags_logic(res, prefixes.rex_w);
Ok(None)
}
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
0x01 | 0x03 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val1, val2)
} else {
let (r, f) = add32(val1 as u32, val2 as u32);
@@ -339,11 +529,11 @@ impl<'a> Interpreter<'a> {
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
0x29 | 0x2B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val1, val2)
} else {
let (r, f) = sub32(val1 as u32, val2 as u32);
@@ -357,13 +547,13 @@ impl<'a> Interpreter<'a> {
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
0x39 | 0x3B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (v1, v2) = if byte == 0x39 {
(self.cpu.get(rm), self.cpu.get(reg))
} else {
(self.cpu.get(reg), self.cpu.get(rm))
};
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(v1, v2)
} else {
let (r, f) = sub32(v1 as u32, v2 as u32);
@@ -377,7 +567,7 @@ impl<'a> Interpreter<'a> {
0x83 => {
let modrm = self.fetch_u8()?;
let op = (modrm >> 3) & 7;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let imm8 = self.fetch_i8()? as i64;
let imm = imm8 as u64;
@@ -385,7 +575,7 @@ impl<'a> Interpreter<'a> {
match op {
0 => {
// ADD
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val, imm)
} else {
let (r, f) = add32(val as u32, imm as u32);
@@ -396,7 +586,7 @@ impl<'a> Interpreter<'a> {
}
5 => {
// SUB
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -407,7 +597,7 @@ impl<'a> Interpreter<'a> {
}
7 => {
// CMP
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -424,7 +614,7 @@ impl<'a> Interpreter<'a> {
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
0x89 | 0x8B => {
let modrm = self.fetch_u8()?;
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
self.execute_mov_rm(modrm, &prefixes, byte == 0x8B)
}
// JMP rel8 (0xEB)
@@ -478,7 +668,7 @@ impl<'a> Interpreter<'a> {
// PUSH reg (0x50..=0x57)
0x50..=0x57 => {
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x50) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.cpu.get(reg);
self.push_u64(val)?;
@@ -487,7 +677,7 @@ impl<'a> Interpreter<'a> {
// POP reg (0x58..=0x5F)
0x58..=0x5F => {
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x58) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.pop_u64()?;
self.cpu.set(reg, val);
@@ -518,32 +708,26 @@ impl<'a> Interpreter<'a> {
fn decode_modrm_reg_reg(
&self,
modrm: u8,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
) -> Result<(Register, Register), ExitReason> {
let mode = (modrm >> 6) & 3;
if mode != 3 {
return Err(ExitReason::IllegalInstruction(modrm));
}
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
#[allow(clippy::too_many_arguments)]
fn execute_mov_rm(
&mut self,
modrm: u8,
rex_w: bool,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
is_load: bool,
seg_gs: bool,
seg_fs: bool,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if mode == 3 {
@@ -551,12 +735,24 @@ impl<'a> Interpreter<'a> {
let rm = Register::from_index(rm_idx);
if is_load {
let val = self.cpu.get(rm);
self.cpu
.set(reg, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
reg,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
} else {
let val = self.cpu.get(reg);
self.cpu
.set(rm, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
rm,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
}
return Ok(None);
}
@@ -566,8 +762,8 @@ impl<'a> Interpreter<'a> {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
let scale_shift = (sib >> 6) & 3;
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
let index_raw = ((sib >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
let base_v = if mode == 0 && (sib & 7) == 5 {
// disp32 with no base register
@@ -623,15 +819,15 @@ impl<'a> Interpreter<'a> {
(base_val as i64 + disp) as u64
};
if seg_gs {
if prefixes.seg_gs {
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
} else if seg_fs {
} else if prefixes.seg_fs {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if rex_w {
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
@@ -647,7 +843,7 @@ impl<'a> Interpreter<'a> {
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if rex_w {
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
+75 -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 {
@@ -1077,6 +1089,16 @@ impl DbtEngine {
cur_rip += 1;
match op2 {
// BSWAP r32/r64: the register is encoded in the opcode.
0xC8..=0xCF => {
insn_count += 1;
let reg = (op2 & 7) | (u8::from(rex_b) << 3);
let offset = u32::from(reg) * 8;
asm.ldr_uoff_64(X9, X19, offset);
// REV X9, X9 or REV W9, W9. A W write clears the upper half.
asm.emit(if rex_w { 0xdac0_0d29 } else { 0x5ac0_0929 });
asm.str_uoff_64(X9, X19, offset);
}
// Jcc rel32 (0x0F 0x80..=0x8F)
0x80..=0x8F => {
insn_count += 1;
@@ -1651,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());
}
}
+91 -51
View File
@@ -91,6 +91,17 @@ 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;
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 +116,82 @@ 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].chunks_exact(SECTION_HEADER_SIZE) {
// 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 +210,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 +253,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
@@ -245,7 +283,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)?
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
fn check_bswap(native: bool) {
const ENTRY: u64 = 0x1000;
const INPUT: u64 = 0x1122_3344_5566_7788;
for reg in 0_u8..16 {
for width in [16, 32, 64] {
let wide = width == 64;
let mut code = Vec::new();
if width == 16 {
code.push(0x66);
}
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
if rex != 0x40 {
code.push(rex);
}
code.extend([0x0f, 0xc8 + (reg & 7)]);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr.fill(0xdead_beef);
cpu.gpr[reg as usize] = INPUT;
cpu.flags = RFlags {
cf: wide,
zf: !wide,
sf: wide,
of: !wide,
};
let flags = cpu.flags;
let mut expected = cpu.gpr;
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
if width == 16 {
assert!(matches!(
result.exit_reason,
ExitReason::IllegalInstruction(_)
));
assert_eq!(result.instructions_executed, 0);
} else {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{code:02x?}"
);
assert_eq!(result.instructions_executed, 1);
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
expected[reg as usize] = if wide {
0x8877_6655_4433_2211
} else {
0x8877_6655
};
}
assert_eq!(result.final_state.gpr, expected);
assert_eq!(result.final_state.flags, flags);
}
}
}
#[test]
fn interpreter_bswap() {
check_bswap(false);
}
#[test]
fn native_bswap() {
check_bswap(true);
}
+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);
}
}
}
}
}
+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());
}
+103
View File
@@ -259,3 +259,106 @@ fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
assert!(!records[1].is_supported_dbt);
}
}
#[test]
fn exported_reports_agree_across_fixtures_and_blocker_locations() {
let dir =
std::env::temp_dir().join(format!("xenora-report-consistency-{}", std::process::id()));
// (file offset, RVA) for a reachable instruction immediately after a MOV.
for (fixture, file_offset, rva, sections, imports) in [
(create_synthetic_probe_pe(), 0x209, 0x1009_u32, 1, 0),
(
include_bytes!("../../../fixtures/pe/trusted-runner.exe").to_vec(),
0x44e,
0x104e,
4,
1,
),
] {
assert_eq!(fixture[file_offset], 0xc3);
for padding in [None, Some(0), Some(1), Some(7)] {
let mut pe = fixture.clone();
let blocker = padding.map(|n| {
pe[file_offset..file_offset + n].fill(0x90);
pe[file_offset + n] = 0xcc;
rva + n as u32
});
run_probe_and_export(&pe, &dir, &ProbeConfig::default()).unwrap();
let read = |name| std::fs::read_to_string(dir.join(name)).unwrap();
let md = read("candidate_static_report.md");
let json = read("candidate_static_report.json");
let cpu = read("cpu_coverage.csv");
let import_csv = read("imports.csv");
std::fs::remove_dir_all(&dir).unwrap();
let json_field = |name: &str| {
let prefix = format!("\"{name}\": ");
json.lines()
.find_map(|line| line.trim().strip_prefix(&prefix))
.unwrap()
.trim_end_matches(',')
.trim_matches('"')
};
assert_eq!(json_field("sections_count"), sections.to_string());
assert!(
md.lines()
.any(|line| line == format!("## Sections Census ({sections})"))
);
assert_eq!(
md.lines()
.filter(|line| line.contains(" VirtualSize: "))
.count(),
sections
);
assert_eq!(json_field("total_imports"), imports.to_string());
assert!(
md.lines()
.any(|line| line == format!("- **Total Imported Thunks**: `{imports}`"))
);
assert_eq!(import_csv.lines().skip(1).count(), imports);
let expected = blocker.map(|addr| format!("0x{addr:08x}"));
assert_eq!(
json_field("first_unsupported_dbt_rva"),
expected.as_deref().unwrap_or("none")
);
let md_rvas: Vec<_> = md
.lines()
.filter_map(|line| {
line.strip_prefix("- **RVA**: `")?
.split_once('`')
.map(|(addr, _)| addr)
})
.collect();
assert_eq!(md_rvas, expected.iter().collect::<Vec<_>>());
// The first columns precede quoted fields. Read the support flags from
// the closing quote of the mnemonic, which can itself contain commas.
let mut unsupported = Vec::new();
let mut tail = Vec::new();
for row in cpu.lines().skip(1) {
let (addr, rest) = row.split_once(',').unwrap();
let (_, fields) = rest.split_once(",\"").unwrap();
let (bytes, mnemonic) = fields.split_once("\",\"").unwrap();
let (_, flags) = mnemonic.split_once("\",").unwrap();
if flags.split(',').next() == Some("false") {
unsupported.push(addr);
}
let address = u32::from_str_radix(addr.strip_prefix("0x").unwrap(), 16).unwrap();
if address >= rva {
tail.push((address, bytes));
}
}
assert_eq!(unsupported, expected.iter().collect::<Vec<_>>());
let mut expected_tail = Vec::new();
if let Some(end) = blocker {
expected_tail.extend((rva..end).map(|addr| (addr, "90")));
expected_tail.push((end, "cc"));
} else {
expected_tail.push((rva, "c3"));
}
assert_eq!(tail, expected_tail);
}
}
}
+2
View File
@@ -32,12 +32,14 @@ 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",
"MTLCommandQueue",
"MTLComputeCommandEncoder",
"MTLComputePipeline",
"MTLDepthStencil",
"MTLDevice",
"MTLLibrary",
"MTLPixelFormat",
+244 -40
View File
@@ -16,28 +16,50 @@ use objc2_metal::{
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{Bc1Upload, TiledBc1};
use xenora_texture::{
Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1,
};
#[path = "render.rs"]
mod render;
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;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const BC1_READBACK: &str = r"
const BC_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
kernel void read_bc(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
}
";
// Signed formats return -1.0..=1.0; each byte holds the channel times 127.
const BC_SNORM_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc_snorm(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
float4 texel = clamp(image.read(uint2(index % width, index / width)), -1.0f, 1.0f);
uint4 bytes = uint4(int4(round(texel * 127.0f))) & 0xffu;
output[index] = bytes.r | (bytes.g << 8u) | (bytes.b << 16u) | (bytes.a << 24u);
}
";
enum ComputeInput<'a> {
Words(&'a [u32]),
Texture(&'a ProtocolObject<dyn MTLTexture>, usize),
@@ -88,6 +110,17 @@ pub struct MetalError {
}
impl MetalError {
/// Operation name of the error returned when the device lacks BC texture
/// compression, which is a hardware capability, not an implementation fault.
pub const BC_UNAVAILABLE: &'static str = "supportsBCTextureCompression";
/// Whether the device lacks a required capability, as opposed to a failure
/// in Xenora's validation or Metal execution.
#[must_use]
pub fn is_capability_unavailable(&self) -> bool {
self.operation == Self::BC_UNAVAILABLE
}
pub(crate) fn new(operation: &'static str, detail: impl Into<String>) -> Self {
Self {
operation,
@@ -184,11 +217,18 @@ impl NativeCompute {
let (width, height) = tiled
.mip_extent(mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(width, height)?;
let pixels = self.validate_bc_extent(width, height, "BC1")?;
let blocks = tiled
.linearize(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
&blocks,
width.div_ceil(4) * 8,
width,
height,
pixels,
)
}
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
@@ -269,8 +309,9 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(level.width, level.height)?;
self.read_bc1_blocks(
let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?;
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
level.bytes,
level.row_pitch,
level.width,
@@ -279,22 +320,100 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
)
}
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
/// Read a selected subresource from a validated pitched BC2 or BC3 upload.
///
/// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA`
/// texture, and the output has the layout of [`Self::read_bc1_upload`].
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression, or Metal setup or execution failure.
pub fn read_bc_alpha_upload(
&self,
upload: &BcAlphaUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let (format, name) = match upload.format() {
BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"),
BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"),
};
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
self.read_bc_blocks(
format,
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
/// Read a selected subresource from a validated pitched BC4 or BC5 upload.
///
/// The original blocks go to a native `BC4_R*` or `BC5_RG*` texture.
/// Unsigned output has the layout of [`Self::read_bc1_upload`]. Signed
/// output stores each channel, times 127 and rounded, as a two's-complement
/// byte in the same order. Metal fills missing green and blue with 0 and
/// alpha with 1.
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression (operation `supportsBCTextureCompression`),
/// or Metal setup or execution failure.
pub fn read_bc_channel_upload(
&self,
upload: &BcChannelUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let (format, name) = match upload.format() {
BcChannelFormat::Bc4Unorm => (MTLPixelFormat::BC4_RUnorm, "BC4 UNORM"),
BcChannelFormat::Bc4Snorm => (MTLPixelFormat::BC4_RSnorm, "BC4 SNORM"),
BcChannelFormat::Bc5Unorm => (MTLPixelFormat::BC5_RGUnorm, "BC5 UNORM"),
BcChannelFormat::Bc5Snorm => (MTLPixelFormat::BC5_RGSnorm, "BC5 SNORM"),
};
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
self.read_bc_blocks(
format,
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
fn validate_bc_extent(
&self,
width: usize,
height: usize,
name: &str,
) -> Result<usize, MetalError> {
let pixels = width
.checked_mul(height)
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
.ok_or_else(|| MetalError::new("texture bounds", "expected 1..=4096 texels"))?;
if !self.device.supportsBCTextureCompression() {
return Err(MetalError::new(
"supportsBCTextureCompression",
"BC1 is unavailable",
MetalError::BC_UNAVAILABLE,
format!("{name} is unavailable"),
));
}
Ok(pixels)
}
fn read_bc1_blocks(
fn read_bc_blocks(
&self,
format: MTLPixelFormat,
blocks: &[u8],
row_pitch: usize,
width: usize,
@@ -302,14 +421,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
pixels: usize,
) -> Result<Vec<u32>, MetalError> {
autoreleasepool(|_| {
// SAFETY: The positive bounded dimensions and supported BC1 format
// SAFETY: The positive bounded dimensions and supported BC format
// describe a 2D texture with just its base level.
let descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
MTLPixelFormat::BC1_RGBA,
width,
height,
false,
format, width, height, false,
)
};
descriptor.setStorageMode(MTLStorageMode::Shared);
@@ -318,7 +434,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
.device
.newTextureWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
MetalError::new("newTextureWithDescriptor", "BC allocation failed")
})?;
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
@@ -332,7 +448,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
// SAFETY: The region spans the whole level, including any partial
// edge block. Both callers validate that the input holds all rows
// of complete BC1 blocks at the supplied, block-aligned stride.
// of complete blocks of this format at the supplied, block-aligned
// stride.
unsafe {
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
@@ -341,12 +458,14 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
bytes_per_row,
);
}
self.run(
BC1_READBACK,
"read_bc1",
ComputeInput::Texture(&texture, pixels),
)
.map(|profile| profile.output)
let (source, entry) =
if format == MTLPixelFormat::BC4_RSnorm || format == MTLPixelFormat::BC5_RGSnorm {
(BC_SNORM_READBACK, "read_bc_snorm")
} else {
(BC_READBACK, "read_bc")
};
self.run(source, entry, ComputeInput::Texture(&texture, pixels))
.map(|profile| profile.output)
})
}
@@ -438,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(
@@ -446,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(
@@ -454,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()?;
@@ -462,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",
@@ -568,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],
+5 -1
View File
@@ -13,7 +13,11 @@ pub mod sampler;
pub mod texture_pipeline;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use compute::{GuestBuffer, GuestBufferView, MetalError, NativeCompute, RunProfile};
pub use compute::{
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"))]
pub use sampler::MetalSampler;
File diff suppressed because it is too large. Load diff
+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);
}
}
+64
View File
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the reference rasteriser agrees with the independently derived
//! expectations for every depth case. Runs without a GPU.
#[path = "support/depth_cases.rs"]
mod depth_cases;
use depth_cases::{BC1_BLOCKS, Fill, SIZE, cases, expected};
use xenora_ref::depth::{RefDraw, RefFill, RefTexture, render_depth};
/// Row-major 8x8 texels decoded block by block with the CPU BC1 decoder.
pub 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() {
let decoded = xenora_texture::decode_bc1(*bytes);
for (index, texel) in decoded.iter().enumerate() {
let x = (block % 2) * 4 + index % 4;
let y = (block / 2) * 4 + index / 4;
texels[y * 8 + x] = *texel;
}
}
texels
}
#[test]
fn reference_matches_independent_expectations() {
let texels = bc1_texels();
let texture = RefTexture {
width: 8,
height: 8,
texels: &texels,
};
let expected = expected();
let cases = cases();
assert_eq!(cases.len(), 30);
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| RefDraw {
positions: draw.positions,
fill: match draw.fill {
Fill::Flat(rgba) => RefFill::Flat(rgba),
Fill::Texture => RefFill::Texture,
},
compare: draw.compare,
write: draw.write,
})
.collect();
let (color, depth) = render_depth(
[SIZE, SIZE],
case.clear_color,
case.clear_depth,
&draws,
Some(texture),
)
.expect("reference render");
assert_eq!(color, want.color, "{} colour", case.name);
assert_eq!(depth, want.depth, "{} depth", 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
File diff suppressed because it is too large. Load diff
+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}");
}
+151
View File
@@ -0,0 +1,151 @@
use xenora_metal::{DepthCompare, DepthDraw, DepthFill, DepthPass, DepthState};
use xenora_ref::depth::CompareFunction;
use xenora_texture::{Bc1Upload, Bc1UploadDesc};
use super::depth_cases::{BC1_BLOCKS, Case, Fill, GREEN, SIZE, cases, expected};
use super::{context, native};
fn compare(function: CompareFunction) -> DepthCompare {
match function {
CompareFunction::Never => DepthCompare::Never,
CompareFunction::Less => DepthCompare::Less,
CompareFunction::Equal => DepthCompare::Equal,
CompareFunction::LessEqual => DepthCompare::LessEqual,
CompareFunction::Greater => DepthCompare::Greater,
CompareFunction::NotEqual => DepthCompare::NotEqual,
CompareFunction::GreaterEqual => DepthCompare::GreaterEqual,
CompareFunction::Always => DepthCompare::Always,
}
}
fn metal_draws(case: &Case) -> Vec<DepthDraw> {
case.draws
.iter()
.map(|draw| DepthDraw {
positions: draw.positions,
fill: match draw.fill {
Fill::Flat(rgba) => DepthFill::Flat(rgba),
Fill::Texture => DepthFill::Bc1Texture,
},
depth: DepthState {
compare: compare(draw.compare),
write: draw.write,
},
})
.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 and depth must equal the independently derived
/// values (which the CPU reference also reproduces in `depth_reference`).
/// Colour and depth are compared separately, per pixel.
#[test]
fn depth_attachment_known_answers() {
let gpu = context();
let upload = bc1_upload();
let expected = expected();
let cases = cases();
assert_eq!(cases.len(), expected.len());
let mut checked = 0;
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws = metal_draws(case);
let output = native(
gpu.render_depth(&DepthPass {
extent: [SIZE, SIZE],
clear_color: case.clear_color,
clear_depth: case.clear_depth,
draws: &draws,
// Only the textured case needs BC support, so a device without it
// fails that case alone, as a capability error.
texture: case
.draws
.iter()
.any(|draw| matches!(draw.fill, Fill::Texture))
.then_some(&upload),
}),
);
for (index, (pixel, wanted)) in output
.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);
}
assert_eq!(output.color.len(), SIZE * SIZE * 4);
match (&output.depth, &want.depth) {
(Some(depth), Some(wanted)) => {
assert_eq!(depth.len(), wanted.len());
for (index, (value, wanted)) in depth.iter().zip(wanted).enumerate() {
let (x, y) = (index % SIZE, index / SIZE);
assert_eq!(
value.to_bits(),
wanted.to_bits(),
"{} depth at ({x}, {y}): {value} vs {wanted}",
case.name
);
}
}
(None, None) => {}
(got, want) => panic!("{}: depth presence {got:?} vs {want:?}", case.name),
}
checked += 1;
}
println!("checked {checked} depth passes of {} pixels", SIZE * SIZE);
}
#[test]
fn depth_state_without_attachment_is_rejected() {
let gpu = context();
let draw = DepthDraw {
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],
],
fill: DepthFill::Flat(GREEN),
depth: DepthState {
compare: DepthCompare::Less,
write: false,
},
};
let pass = |clear_depth, draw: DepthDraw| {
gpu.render_depth(&DepthPass {
extent: [SIZE, SIZE],
clear_color: [0; 4],
clear_depth,
draws: &[draw],
texture: None,
})
};
let error = pass(None, draw).expect_err("depth test without attachment");
assert!(!error.is_capability_unavailable(), "{error}");
for clear in [-0.25, 1.5, f32::NAN] {
pass(Some(clear), draw).expect_err("clear depth outside 0..=1");
}
let textured = DepthDraw {
fill: DepthFill::Bc1Texture,
..draw
};
pass(Some(1.0), textured).expect_err("textured draw without texture");
}
+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}"
);
}
}
@@ -0,0 +1,404 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Metal upload and readback of original BC2 and BC3 blocks.
//!
//! Every block below was written for this test. The full-texel reference is
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
//! the Microsoft Direct3D 11 block-compression documentation (BC2, BC3) and
//! the Khronos Data Format Specification 1.3 (S3TC DXT3/DXT5). Apple's GPU
//! decoder is the value under test, so expected and actual values come from
//! different decoders.
use super::{context, native};
use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3};
/// The specifications define colour and BC3 alpha interpolation in real
/// numbers, and the CPU reference truncates them. On an Apple M5 Pro the
/// native decoder's interpolated values lie within 8/7 (1.143) codes of the real
/// value (they match 6-bit fixed-point weights), so they can sit two codes
/// above the truncated reference: 124 against 122 for BC3 alpha
/// (4 * 200 + 3 * 20) / 7 = 122.86. Endpoints, BC2 alpha and BC3's fixed
/// 0 and 255 are exact and are pinned by the anchor checks.
const TOLERANCE: u8 = 2;
/// Bound for anchors against the real-number value of an interpolated code.
const REAL_TOLERANCE: f64 = 1.5;
fn assert_near(label: &str, actual: u8, real: f64) {
assert!(
(f64::from(actual) - real).abs() <= REAL_TOLERANCE,
"{label}: got {actual}, real value {real:.2}"
);
}
const WIDTH: usize = 5;
const HEIGHT: usize = 5;
const ROW_PITCH: usize = 48;
const SLICE_PITCH: usize = 112;
/// Colour half: two little-endian RGB565 endpoints, then 2-bit indices.
/// Every row of 0xe4 selects palette entries 0, 1, 2, 3 from left to right.
fn colour((first, second): (u16, u16)) -> [u8; 8] {
let [a, b] = first.to_le_bytes();
let [c, d] = second.to_le_bytes();
[a, b, c, d, 0xe4, 0xe4, 0xe4, 0xe4]
}
/// BC3 alpha half whose texel `t` selects palette entry `(t + 6) % 8`, so
/// every row starts with the indices 6 and 7 and a full block uses all eight.
fn bc3_alpha(first: u8, second: u8) -> [u8; 8] {
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
let i = bits.to_le_bytes();
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
}
fn block(alpha: [u8; 8], colour: [u8; 8]) -> [u8; 16] {
let mut block = [0; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour);
block
}
// First endpoint greater: red over blue.
const DESCENDING: (u16, u16) = (0xf800, 0x001f);
// First endpoint smaller, with odd channel values that exercise rounding.
const ASCENDING: (u16, u16) = (0x52aa, 0xad55);
// Equal endpoints: BC1 would decode index 3 as transparent black.
const EQUAL: (u16, u16) = (0x07e0, 0x07e0);
/// White with zero alpha (BC2 nibbles 0; BC3 endpoints 0 and 0) in every
/// padding slot, so a wrong row or slice pitch reads visibly wrong texels.
const PAD: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0];
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
type Layer = [[u8; 16]; 5];
/// Two layers of a 5×5 texture with two mips. Each subresource has seven
/// physical blocks: rows of two logical blocks plus one padding block, a
/// padding block that closes the slice, and mip 1 uses only its block zero.
fn upload_bytes(layers: [Layer; 2]) -> Vec<u8> {
let mut bytes = Vec::new();
for [b0, b1, b2, b3, small] in layers {
for slot in [b0, b1, PAD, b2, b3, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
for slot in [small, PAD, PAD, PAD, PAD, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
}
assert_eq!(bytes.len(), 2 * 2 * SLICE_PITCH);
bytes
}
/// Per-channel tolerance of each texel of `block`: zero where the index
/// selects a stored endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255,
/// and [`TOLERANCE`] only for interpolated codes.
fn tolerances(format: BcAlphaFormat, block: [u8; 16]) -> [[u8; 4]; 16] {
let colour = u32::from_le_bytes([block[12], block[13], block[14], block[15]]);
let mut alpha_bits = [0; 8];
alpha_bits[..6].copy_from_slice(&block[2..8]);
let alpha_indices = u64::from_le_bytes(alpha_bits);
let six_value = block[0] <= block[1];
std::array::from_fn(|t| {
let rgb = if (colour >> (2 * t)) & 3 < 2 {
0
} else {
TOLERANCE
};
let index = (alpha_indices >> (3 * t)) & 7;
let a = match format {
BcAlphaFormat::Bc2 => 0,
BcAlphaFormat::Bc3 if index < 2 || (six_value && index >= 6) => 0,
BcAlphaFormat::Bc3 => TOLERANCE,
};
[rgb, rgb, rgb, a]
})
}
/// Crops a row-major grid of blocks to a `width`×`height` level of CPU-decoded
/// words (red in the lowest byte, as the readback kernel writes them), each
/// with its per-channel tolerance.
fn reference(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
blocks: &[[u8; 16]],
blocks_x: usize,
(width, height): (usize, usize),
) -> Vec<(u32, [u8; 4])> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
let block = blocks[(y / 4) * blocks_x + x / 4];
let t = (y % 4) * 4 + x % 4;
let word = u32::from_le_bytes(decode(block)[t]);
texels.push((word, tolerances(format, block)[t]));
}
}
texels
}
fn alpha(word: u32) -> u8 {
word.to_le_bytes()[3]
}
/// Returns the largest per-channel difference, failing on any channel above
/// its tolerance with the texel index and both values.
fn assert_close(label: &str, actual: &[u32], expected: &[(u32, [u8; 4])]) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &(want, tolerance))) in actual.iter().zip(expected).enumerate() {
for ((g, w), limit) in got
.to_le_bytes()
.into_iter()
.zip(want.to_le_bytes())
.zip(tolerance)
{
assert!(
g.abs_diff(w) <= limit,
"{label}: texel {texel} got {got:#010x}, want {want:#010x} (per-channel limit {tolerance:?})"
);
worst = worst.max(g.abs_diff(w));
}
}
worst
}
/// GPU reads of both layers: `[layer][mip]`.
type Reads = [[Vec<u32>; 2]; 2];
/// Uploads both layers, reads all four subresources on the GPU, compares
/// them with the CPU decoder and returns the reads with the worst difference.
fn read_and_compare(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
layers: [Layer; 2],
) -> (Reads, u8) {
let bytes = upload_bytes(layers);
let upload = BcAlphaUpload::new(
&bytes,
BcAlphaUploadDesc {
width: WIDTH,
height: HEIGHT,
mips: 2,
layers: 2,
format,
row_pitch: ROW_PITCH,
slice_pitch: SLICE_PITCH,
},
)
.unwrap();
let gpu = context();
let mut worst = 0;
let reads = std::array::from_fn(|layer| {
let base = native(gpu.read_bc_alpha_upload(&upload, layer, 0));
let expected = reference(format, decode, &layers[layer][..4], 2, (WIDTH, HEIGHT));
let label = format!("{format:?} layer {layer}");
worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected));
let small = native(gpu.read_bc_alpha_upload(&upload, layer, 1));
let expected = reference(format, decode, &layers[layer][4..], 1, (2, 2));
worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected));
[base, small]
});
for (layer, mip) in [(2, 0), (0, 2)] {
assert_eq!(
gpu.read_bc_alpha_upload(&upload, layer, mip)
.unwrap_err()
.operation,
"texture subresource"
);
}
(reads, worst)
}
#[test]
fn reads_pitched_bc2_explicit_alpha_across_mips_and_layers() {
// Nibble t in texel t, low nibble first: alpha t * 17.
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let opaque = [0xff; 8];
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc2,
decode_bc2,
[
[
block(ramp, descending),
block(reverse, ascending),
block(opaque, equal),
block(ramp, ascending),
block(reverse, descending),
],
[
block(opaque, ascending),
block(ramp, equal),
block(reverse, descending),
block(opaque, descending),
block(ramp, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
// (0, 0): red endpoint, nibble 0. (1, 0): blue endpoint, nibble 1.
assert_eq!(base[0], 0x0000_00ff);
assert_eq!(base[1], 0x11ff_0000);
// (0, 2) is texel 8 of block 0: red endpoint, nibble 8 -> 0x88.
assert_eq!(base[2 * WIDTH], 0x8800_00ff);
// (3, 3) is texel 15 of block 0: nibble 15 -> opaque.
assert_eq!(alpha(base[3 * WIDTH + 3]), 0xff);
// (4, 0) is texel 0 of block 1: reversed ramp, nibble 15.
assert_eq!(alpha(base[4]), 0xff);
// (3, 4) is index 3 of block 2's equal green endpoints: opaque green,
// not BC1's transparent black.
assert_eq!(base[4 * WIDTH + 3], 0xff00_ff00);
// Layer 1 mip 1: green endpoints, ramp nibbles 0, 1, 4, 5.
assert_eq!(
reads[1][1],
[0x0000_ff00, 0x1100_ff00, 0x4400_ff00, 0x5500_ff00]
);
println!("checked 58 BC2 texels from four subresources, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() {
// First endpoint greater: eight-value palette.
let eight = bc3_alpha(200, 20);
// First endpoint smaller: six-value palette with fixed 0 and 255.
let six = bc3_alpha(20, 200);
// Equal endpoints also select the six-value palette.
let level = bc3_alpha(128, 128);
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc3,
decode_bc3,
[
[
block(eight, descending),
block(six, ascending),
block(level, equal),
block(eight, ascending),
block(six, descending),
],
[
block(six, equal),
block(eight, ascending),
block(level, descending),
block(six, ascending),
block(eight, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
let a = |x: usize, y: usize| alpha(base[y * WIDTH + x]);
// Block 0, eight-value: row 0 holds indices 6, 7, 0, 1, and row 1
// indices 2, 3, 4, 5, each (k = index - 1) ((7 - k) * 200 + k * 20) / 7.
assert_near("index 6", a(0, 0), (2.0 * 200.0 + 5.0 * 20.0) / 7.0);
assert_near("index 7", a(1, 0), (200.0 + 6.0 * 20.0) / 7.0);
for (x, k) in (0..4).zip(1..) {
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
assert_near(&format!("index {}", k + 1), a(x, 1), real);
}
// Then the endpoints themselves, exactly; texel (0, 0) is the red endpoint.
assert_eq!([a(2, 0), a(3, 0)], [200, 20]);
assert_eq!(base[0] & 0x00ff_ffff, 0x0000_00ff);
// Block 1, six-value: column 4 holds indices 6, 2, 6, 2. Index 6 is the
// fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
assert_eq!([a(4, 0), a(4, 2)], [0, 0]);
assert_near("six-value index 2", a(4, 1), 56.0);
assert_near("six-value index 2", a(4, 3), 56.0);
// Block 2, equal endpoints of 128: row 4 holds indices 6, 7, 0, 1, so the
// six-value mode shows as the fixed 0 and 255.
assert_eq!([a(0, 4), a(1, 4), a(2, 4), a(3, 4)], [0, 255, 128, 128]);
// Mip 1, six-value: indices 6, 7, 2, 3 -> 0, 255, 56, (3 * 20 + 2 * 200) / 5 = 92.
let small: Vec<_> = reads[0][1].iter().copied().map(alpha).collect();
assert_eq!(small[..2], [0, 255]);
assert_near("six-value index 2", small[2], 56.0);
assert_near("six-value index 3", small[3], 92.0);
println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}");
}
/// Reads one-mip, one-layer uploads of `width`×`height` from `blocks` laid
/// out with `row_pitch`, comparing with the CPU decoder.
fn read_edge(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
blocks: &[[u8; 16]],
(width, height, row_pitch): (usize, usize, usize),
) -> Vec<u32> {
let bytes = blocks.as_flattened();
let upload = BcAlphaUpload::new(
bytes,
BcAlphaUploadDesc {
width,
height,
mips: 1,
layers: 1,
format,
row_pitch,
slice_pitch: bytes.len(),
},
)
.unwrap();
let actual = native(context().read_bc_alpha_upload(&upload, 0, 0));
let expected = reference(format, decode, blocks, width.div_ceil(4), (width, height));
assert_close(&format!("{format:?} {width}x{height}"), &actual, &expected);
actual
}
#[test]
fn reads_bc2_and_bc3_edge_blocks() {
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let [descending, equal] = [DESCENDING, EQUAL].map(colour);
// 5×3 is one row of two blocks: Metal receives a zero row stride, and
// both blocks are cut at row 3, the second also at column 1. The row
// pitch keeps one padding block.
let wide = (5, 3, 48);
let bc2 = read_edge(
BcAlphaFormat::Bc2,
decode_bc2,
&[block(ramp, descending), block(reverse, equal), PAD],
wide,
);
// (0, 0) red, nibble 0; (4, 0) green, reversed nibble 15; (0, 2) red,
// nibble 8; (4, 2) green, reversed nibble 7.
assert_eq!(
[bc2[0], bc2[4], bc2[10], bc2[14]],
[0x0000_00ff, 0xff00_ff00, 0x8800_00ff, 0x7700_ff00]
);
let bc3 = read_edge(
BcAlphaFormat::Bc3,
decode_bc3,
&[
block(bc3_alpha(200, 20), descending),
block(bc3_alpha(20, 200), equal),
PAD,
],
wide,
);
// Row 0 of block 0 is indices 6, 7, 0, 1: (2, 0) and (3, 0) are the
// endpoints 200 and 20. Column 0 of block 1 is indices 6, 2, 6: green
// with the fixed 0, then (4 * 20 + 200) / 5 = 56.
assert_eq!([alpha(bc3[2]), alpha(bc3[3])], [200, 20]);
assert_eq!([bc3[4], bc3[14]], [0x0000_ff00; 2]);
assert_near("six-value index 2", alpha(bc3[9]), 56.0);
// 1×1 is a single block cut to its first texel.
let one = (1, 1, 16);
let bc2 = read_edge(
BcAlphaFormat::Bc2,
decode_bc2,
&[block(reverse, descending)],
one,
);
assert_eq!(bc2, [0xff00_00ff]);
let bc3 = read_edge(
BcAlphaFormat::Bc3,
decode_bc3,
&[block(bc3_alpha(20, 200), descending)],
one,
);
assert_eq!(bc3, [0x0000_00ff]);
println!("checked 32 BC2 and BC3 texels from 5x3 and 1x1 edge levels");
}
@@ -0,0 +1,535 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Metal upload and readback of original BC4 and BC5 blocks.
//!
//! Every block below was written for this test. The full-texel reference is
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
//! the Microsoft Direct3D 11 block-compression documentation (BC4, BC5) and
//! the Khronos Data Format Specification 1.3 (RGTC). Apple's GPU decoder is
//! the value under test, so expected and actual values come from different
//! decoders.
use super::{context, native};
use xenora_texture::{
BcChannelFormat, BcChannelUpload, BcChannelUploadDesc, decode_bc4_snorm, decode_bc4_unorm,
decode_bc5_snorm, decode_bc5_unorm,
};
/// The specifications define interpolation in real numbers and the CPU
/// reference truncates toward zero. On an Apple M5 Pro every format's
/// interpolated codes sit up to two codes from that reference; each test
/// prints its measured worst case. Endpoints and the six-value fixed codes
/// are exact and are pinned by the anchor checks.
const TOLERANCE: u8 = 2;
/// Bound for anchors against the real-number value of an interpolated code.
/// The measured worst on an Apple M5 Pro is 1.71 codes: signed eight-value
/// index 4 of 100 and -100 is (4 * 100 - 3 * 100) / 7 = 14.29 and reads 16.
const REAL_TOLERANCE: f64 = 2.0;
const WIDTH: usize = 5;
const HEIGHT: usize = 5;
/// One 8-byte channel block whose texel `t` selects palette entry
/// `(t + 6) % 8`: every row starts with indices 6 and 7, and a full block
/// uses all eight.
fn channel(first: u8, second: u8) -> [u8; 8] {
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
let i = bits.to_le_bytes();
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
}
fn signed(first: i8, second: i8) -> [u8; 8] {
channel(first.to_le_bytes()[0], second.to_le_bytes()[0])
}
/// Index 0 everywhere at endpoint 0x7f: 127 unsigned or 1.0 signed, so a
/// wrong row or slice pitch reads visibly wrong texels.
const PAD: [u8; 8] = [0x7f, 0x7f, 0, 0, 0, 0, 0, 0];
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
type Layer = [Vec<u8>; 5];
struct Case {
format: BcChannelFormat,
/// Expected little-endian texel words of one block.
reference: fn(&[u8]) -> [u32; 16],
layers: [Layer; 2],
}
fn unorm_word(r: u8, g: u8) -> u32 {
u32::from_le_bytes([r, g, 0, 255])
}
/// Both -128 and -127 decode to -1.0, so the native output is -127 for each.
fn snorm_word(r: i8, g: i8) -> u32 {
let byte = |value: i8| value.max(-127).to_le_bytes()[0];
u32::from_le_bytes([byte(r), byte(g), 0, 127])
}
fn bc4_unorm(block: &[u8]) -> [u32; 16] {
decode_bc4_unorm(block.try_into().unwrap()).map(|r| unorm_word(r, 0))
}
fn bc4_snorm(block: &[u8]) -> [u32; 16] {
decode_bc4_snorm(block.try_into().unwrap()).map(|r| snorm_word(r, 0))
}
fn bc5_unorm(block: &[u8]) -> [u32; 16] {
decode_bc5_unorm(block.try_into().unwrap()).map(|[r, g]| unorm_word(r, g))
}
fn bc5_snorm(block: &[u8]) -> [u32; 16] {
decode_bc5_snorm(block.try_into().unwrap()).map(|[r, g]| snorm_word(r, g))
}
fn dual(red: [u8; 8], green: [u8; 8]) -> Vec<u8> {
[red, green].concat()
}
/// Seven physical blocks per subresource: rows of two logical blocks plus
/// one padding block, a padding block closing the slice, and mip 1 using
/// only its block zero. Returns the bytes with the row and slice pitch.
fn upload_bytes(format: BcChannelFormat, layers: &[Layer; 2]) -> (Vec<u8>, usize, usize) {
let block = format.block_bytes();
let pad = PAD.repeat(block / PAD.len());
let mut bytes = Vec::new();
for [b0, b1, b2, b3, small] in layers {
for slot in [b0, b1, &pad, b2, b3, &pad, &pad] {
bytes.extend_from_slice(slot);
}
bytes.extend_from_slice(small);
for _ in 0..6 {
bytes.extend_from_slice(&pad);
}
}
(bytes, 3 * block, 7 * block)
}
/// Crops decoded blocks (a row-major block grid) to a `width`×`height` level.
fn crop<T: Copy>(blocks: &[[T; 16]], blocks_x: usize, width: usize, height: usize) -> Vec<T> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
texels.push(blocks[(y / 4) * blocks_x + x / 4][(y % 4) * 4 + x % 4]);
}
}
texels
}
/// Per-channel distances; signed formats compare bytes as two's complement.
fn distances(format: BcChannelFormat, got: u32, want: u32) -> [u8; 4] {
let signed = matches!(
format,
BcChannelFormat::Bc4Snorm | BcChannelFormat::Bc5Snorm
);
let (got, want) = (got.to_le_bytes(), want.to_le_bytes());
std::array::from_fn(|c| {
if signed {
(got[c] as i8).abs_diff(want[c] as i8)
} else {
got[c].abs_diff(want[c])
}
})
}
/// Per-channel tolerance of each texel: zero where a channel block's index
/// selects a stored endpoint or a six-value fixed code (and for the constant
/// channels), [`TOLERANCE`] only for interpolated codes.
fn tolerances(format: BcChannelFormat, block: &[u8]) -> [[u8; 4]; 16] {
let signed = matches!(
format,
BcChannelFormat::Bc4Snorm | BcChannelFormat::Bc5Snorm
);
let limit = |channel: &[u8], t: usize| {
let mut bits = [0; 8];
bits[..6].copy_from_slice(&channel[2..8]);
let index = (u64::from_le_bytes(bits) >> (3 * t)) & 7;
let six_value = if signed {
channel[0] as i8 <= channel[1] as i8
} else {
channel[0] <= channel[1]
};
if index < 2 || (six_value && index >= 6) {
0
} else {
TOLERANCE
}
};
std::array::from_fn(|t| {
let green = if block.len() == 16 {
limit(&block[8..], t)
} else {
0
};
[limit(&block[..8], t), green, 0, 0]
})
}
/// Asserts every channel is within its tolerance and returns the worst.
fn check_texels(
label: &str,
format: BcChannelFormat,
actual: &[u32],
expected: &[(u32, [u8; 4])],
) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &(want, limit))) in actual.iter().zip(expected).enumerate() {
let diff = distances(format, got, want);
assert!(
diff.iter().zip(limit).all(|(&d, l)| d <= l),
"{label}: texel {texel} got {got:#010x}, want {want:#010x} (per-channel limit {limit:?})"
);
worst = worst.max(*diff.iter().max().unwrap());
}
worst
}
/// CPU reference words of `block` with their per-channel tolerances.
fn expected_block(
case_format: BcChannelFormat,
reference: fn(&[u8]) -> [u32; 16],
block: &[u8],
) -> [(u32, [u8; 4]); 16] {
let words = reference(block);
let limits = tolerances(case_format, block);
std::array::from_fn(|t| (words[t], limits[t]))
}
/// GPU reads of both layers: `[layer][mip]`.
type Reads = [[Vec<u32>; 2]; 2];
/// Uploads both layers, reads all four subresources on the GPU, compares
/// them with the CPU decoder and returns the reads with the worst difference.
fn read_and_compare(case: &Case) -> (Reads, u8) {
let (bytes, row_pitch, slice_pitch) = upload_bytes(case.format, &case.layers);
let upload = BcChannelUpload::new(
&bytes,
BcChannelUploadDesc {
width: WIDTH,
height: HEIGHT,
mips: 2,
layers: 2,
format: case.format,
row_pitch,
slice_pitch,
},
)
.unwrap();
let gpu = context();
let mut worst = 0;
let reads = std::array::from_fn(|layer| {
let decoded: Vec<_> = case.layers[layer]
.iter()
.map(|block| expected_block(case.format, case.reference, block))
.collect();
let levels = [
crop(&decoded[..4], 2, WIDTH, HEIGHT),
crop(&decoded[4..], 1, 2, 2),
];
std::array::from_fn(|mip| {
let actual = native(gpu.read_bc_channel_upload(&upload, layer, mip as u32));
let expected = &levels[mip];
let label = format!("{:?} layer {layer} mip {mip}", case.format);
worst = worst.max(check_texels(&label, case.format, &actual, expected));
actual
})
});
for (layer, mip) in [(2, 0), (0, 2)] {
assert_eq!(
gpu.read_bc_channel_upload(&upload, layer, mip)
.unwrap_err()
.operation,
"texture subresource"
);
}
(reads, worst)
}
fn assert_near(label: &str, actual: f64, real: f64) {
assert!(
(actual - real).abs() <= REAL_TOLERANCE,
"{label}: got {actual}, real value {real:.2}"
);
}
fn byte(word: u32, channel: usize) -> u8 {
word.to_le_bytes()[channel]
}
fn sbyte(word: u32, channel: usize) -> i8 {
byte(word, channel) as i8
}
/// Unsigned blocks: eight-value (200 > 20), six-value (20 < 200), extremes
/// in both orders, and equal endpoints, which select the six-value mode.
fn unsigned_blocks() -> [[u8; 8]; 5] {
[
channel(200, 20),
channel(20, 200),
channel(128, 128),
channel(255, 0),
channel(0, 255),
]
}
/// Signed blocks: eight-value (100 > -100), six-value (-100 < 100), equal
/// zeros, and the extremes 127 and -128 in both orders.
fn signed_blocks() -> [[u8; 8]; 5] {
[
signed(100, -100),
signed(-100, 100),
signed(0, 0),
signed(127, -128),
signed(-128, 127),
]
}
/// Checks the hand-derived values of the base level of layer 0, whose
/// blocks are the five channel blocks in order.
fn unsigned_anchors(base: &[u32], channel: usize) {
let v = |x: usize, y: usize| byte(base[y * WIDTH + x], channel);
// Block 0, eight-value 200, 20: row 0 indices 6, 7, 0, 1, row 1 2..=5.
assert_eq!([v(2, 0), v(3, 0)], [200, 20]);
for (x, k) in (0..2).chain(0..4).zip([5, 6, 1, 2, 3, 4]) {
let y = usize::from(k < 5);
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
assert_near(
&format!("eight-value index {}", k + 1),
v(x, y).into(),
real,
);
}
// Block 1, six-value 20, 200: column 4 holds indices 6, 2, 6, 2; index 6
// is the fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
assert_eq!([v(4, 0), v(4, 2)], [0, 0]);
assert_near("six-value index 2", v(4, 1).into(), 56.0);
// Block 2, equal 128: row 4 indices 6, 7, 0, 1 -> fixed 0 and 255.
assert_eq!([v(0, 4), v(1, 4), v(2, 4), v(3, 4)], [0, 255, 128, 128]);
// Block 3, 255 > 0: texel (4, 4) is its texel 0, index 6:
// (2 * 255) / 7 = 72.9.
assert_near("extreme index 6", v(4, 4).into(), 510.0 / 7.0);
}
fn signed_anchors(base: &[u32], channel: usize) {
let v = |x: usize, y: usize| sbyte(base[y * WIDTH + x], channel);
// Block 0, eight-value 100, -100: row 0 indices 6, 7, 0, 1.
assert_eq!([v(2, 0), v(3, 0)], [100, -100]);
for (x, k) in (0..2).chain(0..4).zip([5, 6, 1, 2, 3, 4]) {
let y = usize::from(k < 5);
let real = f64::from((7 - k) * 100 - k * 100) / 7.0;
assert_near(
&format!("eight-value index {}", k + 1),
v(x, y).into(),
real,
);
}
// Block 1, six-value -100, 100: column 4 holds indices 6, 2, 6, 2; index
// 6 is the fixed -1.0 and index 2 is (4 * -100 + 100) / 5 = -60.
assert_eq!([v(4, 0), v(4, 2)], [-127, -127]);
assert_near("six-value index 2", v(4, 1).into(), -60.0);
// Block 2, equal zeros: row 4 indices 6, 7, 0, 1 -> fixed -1.0, 1.0, 0, 0.
assert_eq!([v(0, 4), v(1, 4), v(2, 4), v(3, 4)], [-127, 127, 0, 0]);
// Block 3, 127 > -128: index 6 is (2 * 127 + 5 * -127) / 7 = -54.4, with
// -128 read as -1.0.
assert_near("extreme index 6", v(4, 4).into(), -381.0 / 7.0);
}
fn layers(
blocks: [[u8; 8]; 5],
other: [[u8; 8]; 5],
pair: fn([u8; 8], [u8; 8]) -> Vec<u8>,
) -> [Layer; 2] {
[
blocks.map(|b| pair(b, other[0])),
// Layer 1 rotates the blocks so each layer and mip differs.
std::array::from_fn(|i| pair(blocks[(i + 2) % 5], other[(i + 1) % 5])),
]
}
fn single(block: [u8; 8], _: [u8; 8]) -> Vec<u8> {
block.to_vec()
}
/// BC5 with the first block in red and a different block in green.
fn red_green(red: [u8; 8], green: [u8; 8]) -> Vec<u8> {
dual(red, green)
}
#[test]
fn reads_pitched_bc4_unorm_across_mips_and_layers() {
let blocks = unsigned_blocks();
let case = Case {
format: BcChannelFormat::Bc4Unorm,
reference: bc4_unorm,
layers: layers(blocks, blocks, single),
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
unsigned_anchors(base, 0);
// A single channel reads as (red, 0, 0, 1).
assert!(base.iter().all(|&word| word & 0xffff_ff00 == 0xff00_0000));
println!("checked 58 BC4 UNORM texels, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc4_snorm_across_mips_and_layers() {
let blocks = signed_blocks();
let case = Case {
format: BcChannelFormat::Bc4Snorm,
reference: bc4_snorm,
layers: layers(blocks, blocks, single),
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
signed_anchors(base, 0);
assert!(base.iter().all(|&word| word & 0xffff_ff00 == 0x7f00_0000));
// Layer 1 mip 1 is block 1 (-100 < 100, six-value): indices 6, 7, 2, 3.
let small: Vec<_> = reads[1][1].iter().map(|&word| sbyte(word, 0)).collect();
assert_eq!(small[..2], [-127, 127]);
println!("checked 58 BC4 SNORM texels, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc5_unorm_in_red_green_order() {
let blocks = unsigned_blocks();
let case = Case {
format: BcChannelFormat::Bc5Unorm,
reference: bc5_unorm,
layers: [
blocks.map(|b| red_green(b, blocks[1])),
layers(blocks, blocks, red_green)[1].clone(),
],
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
unsigned_anchors(base, 0);
// Green holds the six-value block 1 throughout layer 0: (0, 0) is its
// index 6, the fixed 0, and (1, 0) its index 7, the fixed 255.
assert_eq!([byte(base[0], 1), byte(base[1], 1)], [0, 255]);
assert!(base.iter().all(|&word| word & 0xffff_0000 == 0xff00_0000));
println!("checked 58 BC5 UNORM texels, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc5_snorm_in_red_green_order() {
let blocks = signed_blocks();
let case = Case {
format: BcChannelFormat::Bc5Snorm,
reference: bc5_snorm,
layers: [
blocks.map(|b| red_green(b, blocks[1])),
layers(blocks, blocks, red_green)[1].clone(),
],
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
signed_anchors(base, 0);
// Green holds the six-value block 1 throughout layer 0: (0, 0) and
// (1, 0) are its fixed -1.0 and 1.0.
assert_eq!([sbyte(base[0], 1), sbyte(base[1], 1)], [-127, 127]);
assert!(base.iter().all(|&word| word & 0xffff_0000 == 0x7f00_0000));
println!("checked 58 BC5 SNORM texels, worst channel difference {worst}");
}
/// Reads a one-mip, one-layer upload of `width`×`height` from `blocks` with
/// one padding block per row, comparing with the CPU decoder.
fn read_edge(
format: BcChannelFormat,
reference: fn(&[u8]) -> [u32; 16],
blocks: &[Vec<u8>],
(width, height): (usize, usize),
) -> Vec<u32> {
let block = format.block_bytes();
let pad = PAD.repeat(block / PAD.len());
let blocks_x = width.div_ceil(4);
let mut bytes = Vec::new();
for row in blocks.chunks(blocks_x) {
for slot in row {
bytes.extend_from_slice(slot);
}
bytes.extend_from_slice(&pad);
}
let upload = BcChannelUpload::new(
&bytes,
BcChannelUploadDesc {
width,
height,
mips: 1,
layers: 1,
format,
row_pitch: (blocks_x + 1) * block,
slice_pitch: bytes.len(),
},
)
.unwrap();
let actual = native(context().read_bc_channel_upload(&upload, 0, 0));
let decoded: Vec<_> = blocks
.iter()
.map(|block| expected_block(format, reference, block))
.collect();
let expected = crop(&decoded, blocks_x, width, height);
check_texels(
&format!("{format:?} {width}x{height}"),
format,
&actual,
&expected,
);
actual
}
#[test]
fn reads_bc4_and_bc5_edge_blocks() {
let [eight, six, ..] = unsigned_blocks();
let [s_eight, s_six, _, _, s_low] = signed_blocks();
// 5×3 is one row of two blocks (Metal's zero row stride), both cut at
// row 3 and the second at column 1; 1×1 is one block cut to texel 0.
// Row 0 of every block holds indices 6, 7, 0, 1; column 0 holds 6, 2, 6.
let wide = read_edge(
BcChannelFormat::Bc4Unorm,
bc4_unorm,
&[eight.to_vec(), six.to_vec()],
(5, 3),
);
let red: Vec<_> = wide.iter().map(|&w| byte(w, 0)).collect();
assert_eq!([red[2], red[3], red[4], red[14]], [200, 20, 0, 0]);
assert_near("six-value index 2", red[9].into(), 56.0);
let wide = read_edge(
BcChannelFormat::Bc5Snorm,
bc5_snorm,
&[dual(s_eight, s_six), dual(s_six, s_eight)],
(5, 3),
);
// Block 0: red eight-value endpoints 100, -100; green six-value 0 and 1
// indices -100, 100. Block 1: red six-value fixed -1.0 at index 6, green
// eight-value index 6 (2 * 100 + 5 * -100) / 7 = -42.9.
let texel = |i: usize| [sbyte(wide[i], 0), sbyte(wide[i], 1)];
assert_eq!([texel(2), texel(3)], [[100, -100], [-100, 100]]);
assert_eq!(texel(4)[0], -127);
assert_near(
"green eight-value index 6",
texel(4)[1].into(),
-300.0 / 7.0,
);
// Index 6 of -128 < 127 is the six-value fixed -1.0.
let one = read_edge(
BcChannelFormat::Bc4Snorm,
bc4_snorm,
&[s_low.to_vec()],
(1, 1),
);
assert_eq!(one, [0x7f00_0081]);
let one = read_edge(
BcChannelFormat::Bc5Unorm,
bc5_unorm,
&[dual(six, eight)],
(1, 1),
);
assert_eq!(byte(one[0], 0), 0);
assert_near(
"green eight-value index 6",
byte(one[0], 1).into(),
500.0 / 7.0,
);
println!("checked 32 BC4 and BC5 texels from 5x3 and 1x1 edge levels");
}
+221
View File
@@ -1,11 +1,27 @@
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"]
mod texture;
#[path = "native/texture_bc_alpha.rs"]
mod texture_bc_alpha;
#[path = "native/texture_bc_channel.rs"]
mod texture_bc_channel;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_render.rs"]
@@ -29,6 +45,17 @@ fn context() -> NativeCompute {
NativeCompute::new().expect("native Metal device and queue")
}
/// Unwraps a native result, reporting a missing device capability apart from
/// an implementation failure. Both fail the test; neither counts as a pass.
fn native<T>(result: Result<T, xenora_metal::MetalError>) -> T {
result.unwrap_or_else(|error| {
if error.is_capability_unavailable() {
panic!("CAPABILITY UNAVAILABLE on this device, not an implementation failure: {error}")
}
panic!("IMPLEMENTATION FAILURE: {error}")
})
}
fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
let actual = context()
.run_words(&fixture(body), "fixture", input)
@@ -36,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();
@@ -188,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
}
+187
View File
@@ -0,0 +1,187 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Original depth-pass fixtures shared by the CPU reference check and the
//! native Metal test, and the parser for the independently derived
//! expectations in `fixtures/depth_expected.txt`.
use xenora_ref::depth::CompareFunction;
pub const SIZE: usize = 16;
pub const RED: [u8; 4] = [255, 0, 0, 255];
pub const GREEN: [u8; 4] = [0, 255, 0, 255];
pub const BLUE: [u8; 4] = [0, 0, 255, 255];
const BLACK: [u8; 4] = [0, 0, 0, 255];
/// Four original BC1 blocks (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
];
// Triangles in pixel coordinates; no pixel centre lies on any edge.
const FULL: [[f32; 2]; 3] = [[0.0, 16.0], [32.0, 16.0], [0.0, -16.0]];
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]];
const C: [[f32; 2]; 3] = [[0.0, 8.0], [10.0, 8.0], [0.0, 16.0]];
#[derive(Clone, Copy, Debug)]
pub enum Fill {
Flat([u8; 4]),
Texture,
}
#[derive(Clone, Copy, Debug)]
pub struct Draw {
pub positions: [[f32; 4]; 3],
pub fill: Fill,
pub compare: CompareFunction,
pub write: bool,
}
#[derive(Debug)]
pub struct Case {
pub name: String,
pub clear_color: [u8; 4],
pub clear_depth: Option<f32>,
pub draws: Vec<Draw>,
}
fn draw(tri: [[f32; 2]; 3], z: f32, fill: Fill, compare: CompareFunction, write: bool) -> Draw {
Draw {
positions: tri.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, z, 1.0]),
fill,
compare,
write,
}
}
fn case(name: &str, clear_color: [u8; 4], clear_depth: Option<f32>, draws: Vec<Draw>) -> Case {
Case {
name: name.to_owned(),
clear_color,
clear_depth,
draws,
}
}
/// Every case, each exercising one feature, in fixture order.
pub fn cases() -> Vec<Case> {
use CompareFunction::{Always, Less, LessEqual};
let red = Fill::Flat(RED);
let green = Fill::Flat(GREEN);
let blue = Fill::Flat(BLUE);
let mut cases = vec![case("clear", [16, 32, 48, 255], Some(0.375), Vec::new())];
for compare in CompareFunction::ALL {
for z in [0.25, 0.5, 0.75] {
cases.push(case(
&format!("compare_{compare:?}_{z}"),
BLACK,
Some(1.0),
vec![
draw(A, 0.5, red, Always, true),
draw(B, z, green, compare, true),
],
));
}
}
for (name, write) in [("write_disabled", false), ("write_enabled", true)] {
cases.push(case(
name,
BLACK,
Some(1.0),
vec![
draw(A, 0.5, red, Always, true),
draw(B, 0.25, green, Always, write),
draw(C, 0.75, blue, LessEqual, true),
],
));
}
let painter = |depth| {
case(
if depth {
"disabled_attachment"
} else {
"no_attachment"
},
BLACK,
depth.then_some(1.0),
vec![
draw(A, 0.25, red, Always, false),
draw(B, 0.75, green, Always, false),
],
)
};
cases.push(painter(true));
cases.push(painter(false));
cases.push(case(
"textured",
BLACK,
Some(1.0),
vec![
draw(FULL, 0.5, Fill::Texture, Less, true),
draw(B, 0.75, green, Less, true),
draw(A, 0.25, red, Less, true),
],
));
cases
}
/// Independently derived colour and depth of one case.
#[derive(Debug, PartialEq)]
pub struct Expected {
pub name: String,
pub color: Vec<[u8; 4]>,
pub depth: Option<Vec<f32>>,
}
pub fn expected() -> Vec<Expected> {
let text = include_str!("../fixtures/depth_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 depthkey) = (Vec::new(), Vec::new());
let (mut color, mut depth, mut no_depth) = (Vec::new(), Vec::new(), false);
for line in lines.by_ref() {
let mut words = line.split_whitespace();
match words.next().expect("keyword") {
"palette" => {
let key = words.next().unwrap().chars().next().unwrap();
let rgba: Vec<u8> = words.map(|w| w.parse().unwrap()).collect();
palette.push((key, <[u8; 4]>::try_from(rgba).unwrap()));
}
"depthkey" => {
let key = words.next().unwrap().chars().next().unwrap();
depthkey.push((key, words.next().unwrap().parse::<f32>().unwrap()));
}
"color" => color.extend(words.next().unwrap().chars().map(|c| {
palette
.iter()
.find(|(k, _)| *k == c)
.expect("palette key")
.1
})),
"depth" => match words.next().unwrap() {
"none" => no_depth = true,
row => depth.extend(
row.chars()
.map(|c| depthkey.iter().find(|(k, _)| *k == c).expect("depth key").1),
),
},
"end" => break,
other => panic!("unexpected fixture line {other}"),
}
}
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
assert!(no_depth || depth.len() == SIZE * SIZE, "{name} depth rows");
out.push(Expected {
name,
color,
depth: (!no_depth).then_some(depth),
});
}
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
}
);
}
}
+305
View File
@@ -0,0 +1,305 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU reference for depth-tested offscreen triangle rendering.
//!
//! A pixel is covered when its centre lies strictly inside a triangle. Inputs
//! whose pixel centres lie exactly on an edge are rejected rather than resolved
//! by a fill rule, so the reference never depends on rasteriser tie-breaking.
use std::fmt;
/// Depth comparison of the fragment depth against the stored depth.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareFunction {
Never,
Less,
Equal,
LessEqual,
Greater,
NotEqual,
GreaterEqual,
Always,
}
impl CompareFunction {
pub const ALL: [Self; 8] = [
Self::Never,
Self::Less,
Self::Equal,
Self::LessEqual,
Self::Greater,
Self::NotEqual,
Self::GreaterEqual,
Self::Always,
];
#[must_use]
pub fn passes(self, fragment: f32, stored: f32) -> bool {
match self {
Self::Never => false,
Self::Less => fragment < stored,
Self::Equal => fragment == stored,
Self::LessEqual => fragment <= stored,
Self::Greater => fragment > stored,
Self::NotEqual => fragment != stored,
Self::GreaterEqual => fragment >= stored,
Self::Always => true,
}
}
}
/// Colour source of one reference draw.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RefFill {
Flat([u8; 4]),
/// Nearest texel of the pass texture at the pixel centre.
Texture,
}
/// One triangle with clip-space positions (`w` must be 1).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefDraw {
pub positions: [[f32; 4]; 3],
pub fill: RefFill,
pub compare: CompareFunction,
pub write: bool,
}
/// Decoded RGBA8 texels in row-major order.
#[derive(Clone, Copy, Debug)]
pub struct RefTexture<'a> {
pub width: usize,
pub height: usize,
pub texels: &'a [[u8; 4]],
}
#[derive(Debug, Eq, PartialEq)]
pub enum DepthRefError {
Extent,
NonUnitW,
/// A position is non-finite or its depth lies outside 0..=1: (draw).
Unclipped(usize),
/// A pixel centre lies on a triangle edge: (draw, x, y).
EdgeTie(usize, usize, usize),
MissingTexture,
/// Without a depth attachment every draw must be `Always` without writes.
DepthStateWithoutAttachment(usize),
}
impl fmt::Display for DepthRefError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for DepthRefError {}
/// Colour (row-major, top row first) and, with an attachment, stored depth.
pub type DepthRefOutput = (Vec<[u8; 4]>, Option<Vec<f32>>);
/// Render `draws` in order over a cleared target with viewport depth range 0..1.
///
/// # Errors
///
/// Returns an error for an empty extent, non-unit `w`, a non-finite position
/// or depth outside 0..=1, a pixel centre on an edge, a textured draw without texture, or a depth state without attachment.
pub fn render_depth(
[width, height]: [usize; 2],
clear_color: [u8; 4],
clear_depth: Option<f32>,
draws: &[RefDraw],
texture: Option<RefTexture<'_>>,
) -> Result<DepthRefOutput, DepthRefError> {
let pixels = width.checked_mul(height).filter(|&n| n > 0);
let pixels = pixels.ok_or(DepthRefError::Extent)?;
if let Some(texture) = texture
&& texture.width.checked_mul(texture.height).filter(|&n| n > 0)
!= Some(texture.texels.len())
{
return Err(DepthRefError::Extent);
}
let mut color = vec![clear_color; pixels];
let mut depth = clear_depth.map(|value| vec![value; pixels]);
for (index, draw) in draws.iter().enumerate() {
if depth.is_none() && (draw.compare != CompareFunction::Always || draw.write) {
return Err(DepthRefError::DepthStateWithoutAttachment(index));
}
if draw.fill == RefFill::Texture && texture.is_none() {
return Err(DepthRefError::MissingTexture);
}
if draw.positions.iter().any(|p| p[3] != 1.0) {
return Err(DepthRefError::NonUnitW);
}
// The reference does not clip, so depth must already lie in the
// viewport range 0..=1 (this also rejects non-finite depth).
if draw
.positions
.iter()
.any(|p| !p.iter().all(|v| v.is_finite()) || !(0.0..=1.0).contains(&p[2]))
{
return Err(DepthRefError::Unclipped(index));
}
// Viewport transform: NDC x, y in -1..1 map to pixels, y down.
let screen = draw.positions.map(|[x, y, z, _]| {
[
(f64::from(x) + 1.0) * 0.5 * width as f64,
(1.0 - f64::from(y)) * 0.5 * height as f64,
f64::from(z),
]
});
let area = edge(screen[0], screen[1], screen[2]);
if area == 0.0 {
continue;
}
for y in 0..height {
for x in 0..width {
let centre = [x as f64 + 0.5, y as f64 + 0.5, 0.0];
let weights = [
edge(screen[1], screen[2], centre),
edge(screen[2], screen[0], centre),
edge(screen[0], screen[1], centre),
];
if weights.contains(&0.0) {
let others_inside = weights
.iter()
.filter(|&&w| w != 0.0)
.all(|&w| (w > 0.0) == (area > 0.0));
if others_inside {
return Err(DepthRefError::EdgeTie(index, x, y));
}
continue;
}
if !weights.iter().all(|&w| (w > 0.0) == (area > 0.0)) {
continue;
}
let z = (weights[0] * screen[0][2]
+ weights[1] * screen[1][2]
+ weights[2] * screen[2][2])
/ area;
let z = z as f32;
let slot = y * width + x;
if let Some(stored) = depth.as_mut() {
if !draw.compare.passes(z, stored[slot]) {
continue;
}
if draw.write {
stored[slot] = z;
}
}
color[slot] = match (draw.fill, texture) {
(RefFill::Flat(rgba), _) => rgba,
(RefFill::Texture, Some(t)) => {
let u = ((x as f64 + 0.5) / width as f64 * t.width as f64) as usize;
let v = ((y as f64 + 0.5) / height as f64 * t.height as f64) as usize;
t.texels[v.min(t.height - 1) * t.width + u.min(t.width - 1)]
}
(RefFill::Texture, None) => return Err(DepthRefError::MissingTexture),
};
}
}
}
Ok((color, depth))
}
fn edge(a: [f64; 3], b: [f64; 3], p: [f64; 3]) -> f64 {
(b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
}
#[cfg(test)]
mod tests {
use super::*;
const RED: [u8; 4] = [255, 0, 0, 255];
fn draw(positions: [[f32; 4]; 3], compare: CompareFunction, write: bool) -> RefDraw {
RefDraw {
positions,
fill: RefFill::Flat(RED),
compare,
write,
}
}
// A 2x2 target; this triangle covers only the centre of pixel (0, 1).
const LOWER_LEFT: [[f32; 4]; 3] = [
[-1.0, -1.0, 0.25, 1.0],
[0.5, -1.0, 0.25, 1.0],
[-1.0, 0.5, 0.25, 1.0],
];
#[test]
fn covers_by_pixel_centre_and_writes_depth() {
let (color, depth) = render_depth(
[2, 2],
[0; 4],
Some(1.0),
&[draw(LOWER_LEFT, CompareFunction::Less, true)],
None,
)
.unwrap();
assert_eq!(color, [[0; 4], [0; 4], RED, [0; 4]]);
assert_eq!(depth.unwrap(), [1.0, 1.0, 0.25, 1.0]);
}
#[test]
fn compare_functions_follow_metal_semantics() {
let expect = [false, true, false, true, false, true, false, true];
let equal = [false, false, true, true, false, false, true, true];
for (function, (&less, &eq)) in CompareFunction::ALL.iter().zip(expect.iter().zip(&equal)) {
assert_eq!(function.passes(0.25, 0.5), less, "{function:?} less");
assert_eq!(function.passes(0.5, 0.5), eq, "{function:?} equal");
assert_eq!(
function.passes(0.75, 0.5),
!matches!(
function,
CompareFunction::Never
| CompareFunction::Less
| CompareFunction::Equal
| CompareFunction::LessEqual
),
"{function:?} greater"
);
}
}
#[test]
fn rejects_edge_ties_and_depth_without_attachment() {
let tie = [
[-1.0, -1.0, 0.5, 1.0],
[1.0, 1.0, 0.5, 1.0],
[-1.0, 1.0, 0.5, 1.0],
];
assert!(matches!(
render_depth(
[2, 2],
[0; 4],
Some(1.0),
&[draw(tie, CompareFunction::Always, true)],
None
),
Err(DepthRefError::EdgeTie(0, _, _))
));
let mut far = LOWER_LEFT;
far[0][2] = 1.25;
assert_eq!(
render_depth(
[2, 2],
[0; 4],
Some(1.0),
&[draw(far, CompareFunction::Always, true)],
None
),
Err(DepthRefError::Unclipped(0))
);
assert_eq!(
render_depth(
[2, 2],
[0; 4],
None,
&[draw(LOWER_LEFT, CompareFunction::Less, false)],
None
),
Err(DepthRefError::DepthStateWithoutAttachment(0))
);
}
}
+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]));
}
}
+410 -54
View File
@@ -1,7 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU execution of the synthetic gfx1030 fixture subset and reference sampling.
//! 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;
@@ -48,6 +51,12 @@ pub enum Op {
Move(u8, Source),
Add(u8, u8, u8),
ScalarMove(u8, Source),
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
Compare(Comparison, CompareSource, u8),
/// SOP2 operation writing an SGPR and SCC.
Scalar(ScalarAlu, u8, Source, Source),
CompareEqual(Source, Source),
Branch {
target: usize,
@@ -57,6 +66,52 @@ pub enum Op {
End,
}
/// Relation and operand interpretation of a VOPC integer compare.
///
/// AMD RDNA 2 ISA guide section 12.9, Tables 59 and 61: opcode 128 + offset
/// for signed and 192 + offset for unsigned 32-bit operands, with offsets
/// LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Comparison {
/// Opcode offset 1-6 within the 32-bit integer group.
pub offset: u8,
/// Whether the operands are two's-complement integers.
pub signed: bool,
}
impl Comparison {
/// The per-lane result, from an exact comparison of the widened operands.
fn holds(self, s0: u32, s1: u32) -> bool {
let widen = |bits: u32| {
if self.signed {
i64::from(bits as i32)
} else {
i64::from(bits)
}
};
let (s0, s1) = (widen(s0), widen(s1));
match self.offset {
1 => s0 < s1,
2 => s0 == s1,
3 => s0 <= s1,
4 => s0 > s1,
5 => s0 != s1,
_ => s0 >= s1,
}
}
}
/// First source of a VOPC compare.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareSource {
/// VGPR index.
Vector(u8),
/// SGPR index s0-s105, or 106 for `vcc_lo`.
Scalar(u8),
/// Inline integer or literal bits.
Immediate(u32),
}
/// Scalar condition tested by a forward branch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BranchCondition {
@@ -70,6 +125,25 @@ pub enum BranchCondition {
ExecZero,
}
/// SOP2 operations decoded by the reference interpreter.
///
/// 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.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarAlu {
Add,
Subtract,
AddWithCarry,
SubtractWithBorrow,
/// SCC = signed overflow (RDNA 2 ISA guide 12.1).
AddSigned,
SubtractSigned,
And,
Or,
Xor,
}
/// VOP2 operations decoded by the reference interpreter.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorAlu {
@@ -128,11 +202,13 @@ pub fn execute(code: &[u8], input: &[u32]) -> Result<Vec<u32>, ReferenceError> {
{
return Err(error(code.len(), "missing s_endpgm"));
}
input
.iter()
.enumerate()
.map(|(index, &word)| execute_lane(&program, word, index % 32))
.collect()
// Waves are consecutive groups of 32 dispatch indices; a final partial
// wave has absent lanes, which contribute 0 to compare masks.
let mut output = Vec::with_capacity(input.len());
for wave in input.chunks(32) {
output.extend(execute_wave(&program, wave)?);
}
Ok(output)
}
fn error(offset: usize, detail: &'static str) -> ReferenceError {
@@ -206,6 +282,35 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let (right, right_length) = decode_scalar(*right, tail, offset)?;
(Op::CompareEqual(left, right), left_length.max(right_length))
}
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
[
left,
right,
low,
high @ (0x80..=0x82 | 0x87 | 0x88 | 0x89),
tail @ ..,
] if (*left, *right) != (255, 255)
&& low & 0x7f <= 105
&& (low & 0x80 == 0 || matches!(high, 0x80..=0x82)) =>
{
let kind = match (high, low >> 7) {
(0x80, 0) => ScalarAlu::Add,
(0x80, _) => ScalarAlu::Subtract,
(0x81, 0) => ScalarAlu::AddSigned,
(0x81, _) => ScalarAlu::SubtractSigned,
(0x82, 0) => ScalarAlu::AddWithCarry,
(0x82, _) => ScalarAlu::SubtractWithBorrow,
(0x87, _) => ScalarAlu::And,
(0x88, _) => ScalarAlu::Or,
_ => ScalarAlu::Xor,
};
let (left, left_length) = decode_scalar(*left, tail, offset)?;
let (right, right_length) = decode_scalar(*right, tail, offset)?;
(
Op::Scalar(kind, low & 0x7f, left, right),
left_length.max(right_length),
)
}
[lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => {
let words = i16::from_le_bytes([*lo, *hi]);
let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?;
@@ -246,11 +351,53 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let src1 = (middle >> 1) | ((hi & 1) << 7);
(Op::Add(*dst, *lo, src1), 8)
}
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
if matches!(
(u16::from(*tag & 1) << 7) | u16::from(*upper >> 1),
129..=134 | 193..=198
) =>
{
let opcode = (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1);
let comparison = Comparison {
offset: (opcode & 0x3f) as u8,
signed: opcode < 192,
};
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
let (src0, length) = match selector {
0..=106 => (CompareSource::Scalar(*lo), 4),
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
193..=208 => (
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
4,
),
255 => {
let literal = tail
.first_chunk::<4>()
.ok_or_else(|| error(offset, "truncated literal"))?;
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
}
256..=511 => (CompareSource::Vector(*lo), 4),
_ => return Err(error(offset, "unsupported VOPC source")),
};
(Op::Compare(comparison, src0, vsrc1), length)
}
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
if packed & 0xfe == 2 && upper & 1 == 0 =>
{
let dst = (upper >> 1) | ((tag & 1) << 7);
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
if selector <= 106 {
// VOP1 SRC0 0-105 selects a normal SGPR, 106 vcc_lo.
program.push(DecodedInstruction {
offset,
byte_len: 4,
op: Op::MoveScalar(dst, *lo),
});
offset += 4;
continue;
}
let (src, length) = match selector {
128..=192 => (Source::Immediate(u32::from(selector - 128)), 4),
193..=208 => (
@@ -365,21 +512,26 @@ fn vector_alu(op: VectorAlu, a: u32, b: u32, offset: usize) -> Result<u32, Refer
Ok(result.to_bits())
}
fn execute_lane(
program: &[DecodedInstruction],
input: u32,
lane: usize,
) -> Result<u32, ReferenceError> {
let mut registers = [None; 256];
const VCC_LO: usize = 106;
const VCC_HI: usize = 107;
const EXEC_LO: usize = 126;
/// Runs one Wave32 wave in lockstep. Scalar state is shared by the lanes;
/// VGPRs, transfers and outputs are per lane.
fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32>, ReferenceError> {
let lanes = input.len();
let mut registers = vec![[None::<u32>; 256]; lanes];
let mut scalars = [None; 128];
let mut exec = u32::MAX;
scalars[126] = Some(exec);
scalars[EXEC_LO] = Some(exec);
let mut scc = None;
// Whether VCC_LO was last written by a compare with nonzero EXEC.
let mut lane_derived_vcc = false;
let mut target = 0;
let mut pending_read = None;
let mut pending_write = None;
let mut output = None;
for &DecodedInstruction { offset, op, .. } in program {
let mut pending_write = vec![None; lanes];
let mut output = vec![None; lanes];
for (position, &DecodedInstruction { offset, op, .. }) in program.iter().enumerate() {
if offset < target {
continue;
}
@@ -388,24 +540,36 @@ fn execute_lane(
.ok_or_else(|| error(offset, "read from uninitialized SGPR")),
Source::Immediate(value) => Ok(value),
};
let read = |register: u8| {
let read = |lane: usize, register: u8| {
if register == 0 {
return Err(error(offset, "v0 is reserved for the resource index"));
}
if pending_read == Some(register) {
return Err(error(offset, "VGPR read before load wait"));
}
registers[usize::from(register)]
registers[lane][usize::from(register)]
.ok_or_else(|| error(offset, "read from uninitialized VGPR"))
};
// Lanes that execute a vector ALU instruction under the current EXEC.
let executes = |lane: usize| exec & (1 << lane) != 0;
if exec != u32::MAX {
match op {
Op::Move(dst, _) | Op::Add(dst, ..) | Op::Vector(_, dst, ..) => {
if exec != 0 && registers[usize::from(dst)].is_none() {
Op::Move(dst, _)
| Op::MoveScalar(dst, _)
| Op::Add(dst, ..)
| Op::Vector(_, dst, ..) => {
if exec != 0
&& registers
.iter()
.any(|lane| lane[usize::from(dst)].is_none())
{
return Err(error(offset, "partial EXEC requires an initialized VGPR"));
}
if exec & (1 << lane) == 0 {
continue;
// As in translation, an SGPR source must be known even for an inactive lane.
if let Op::MoveScalar(_, src) = op
&& exec != 0
{
read_scalar(Source::Register(src))?;
}
}
Op::Load { .. } | Op::Store { .. } => {
@@ -414,7 +578,9 @@ fn execute_lane(
_ => {}
}
}
let set = match op {
// Per-lane results of a vector ALU instruction, applied after all lanes read.
let mut results: Vec<Option<(u8, u32)>> = vec![None; lanes];
match op {
Op::Load { data: dst, .. } => {
if dst == 0 || pending_read.is_some() {
return Err(error(
@@ -423,81 +589,271 @@ fn execute_lane(
));
}
pending_read = Some(dst);
None
}
Op::Store { data: src, .. } => {
let value = read(src)?;
if pending_write.is_some() || output.is_some() {
return Err(error(offset, "multiple writes to the output"));
for lane in 0..lanes {
let value = read(lane, src)?;
if pending_write[lane].is_some() || output[lane].is_some() {
return Err(error(offset, "multiple writes to the output"));
}
pending_write[lane] = Some(value);
}
}
Op::WaitRead => {
if let Some(dst) = pending_read.take() {
for (lane, &word) in input.iter().enumerate() {
results[lane] = Some((dst, word));
}
}
pending_write = Some(value);
None
}
Op::WaitRead => pending_read.take().map(|dst| (dst, input)),
Op::WaitWrite => {
if let Some(value) = pending_write.take() {
output = Some(value);
for lane in 0..lanes {
if let Some(value) = pending_write[lane].take() {
output[lane] = Some(value);
}
}
}
Op::Move(dst, source) => {
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let value = match source {
Source::Register(src) => read(lane, src)?,
Source::Immediate(value) => value,
};
results[lane] = Some((dst, value));
}
}
Op::Add(dst, lhs, rhs) => {
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let value = read(lane, lhs)?.wrapping_add(read(lane, rhs)?);
results[lane] = Some((dst, value));
}
}
Op::MoveScalar(dst, src) => {
for lane in (0..lanes).filter(|&lane| executes(lane)) {
results[lane] = Some((dst, read_scalar(Source::Register(src))?));
}
}
Op::Vector(operator, dst, lhs, rhs) => {
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let value = vector_alu(operator, read(lane, lhs)?, read(lane, rhs)?, offset)?;
results[lane] = Some((dst, value));
}
None
}
Op::Move(dst, Source::Register(src)) => Some((dst, read(src)?)),
Op::Move(dst, Source::Immediate(value)) => Some((dst, value)),
Op::Add(dst, lhs, rhs) => Some((dst, read(lhs)?.wrapping_add(read(rhs)?))),
Op::ScalarMove(dst, src) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
}
let value = read_scalar(src)?;
if dst == 126 {
if usize::from(dst) == EXEC_LO {
exec = value;
}
if usize::from(dst) == VCC_LO {
lane_derived_vcc = false;
}
scalars[usize::from(dst)] = Some(value);
None
}
Op::CompareEqual(lhs, rhs) => {
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
None
}
Op::Scalar(kind, dst, lhs, rhs) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
}
let (lhs, rhs) = (i64::from(read_scalar(lhs)?), i64::from(read_scalar(rhs)?));
let carry = match kind {
ScalarAlu::AddWithCarry | ScalarAlu::SubtractWithBorrow => i64::from(
scc.ok_or_else(|| error(offset, "carry-in from uninitialized SCC"))?,
),
_ => 0,
};
// Exact integer arithmetic, then reduction modulo 2^32.
let (exact, flag) = match kind {
ScalarAlu::Add | ScalarAlu::AddWithCarry => {
let sum = lhs + rhs + carry;
(sum, sum >= 1 << 32)
}
ScalarAlu::Subtract | ScalarAlu::SubtractWithBorrow => {
let difference = lhs - rhs - carry;
(difference, difference < 0)
}
// The exact signed result must fit in i32, else SCC = overflow.
ScalarAlu::AddSigned | ScalarAlu::SubtractSigned => {
let signed = |value: i64| i64::from(value as u32 as i32);
let exact = if kind == ScalarAlu::AddSigned {
signed(lhs) + signed(rhs)
} else {
signed(lhs) - signed(rhs)
};
(exact, i32::try_from(exact).is_err())
}
ScalarAlu::And | ScalarAlu::Or | ScalarAlu::Xor => {
let bits = match kind {
ScalarAlu::And => lhs & rhs,
ScalarAlu::Or => lhs | rhs,
_ => lhs ^ rhs,
};
(bits, bits != 0)
}
};
let value = exact.rem_euclid(1 << 32) as u32;
scalars[usize::from(dst)] = Some(value);
scc = Some(flag);
}
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
Op::Compare(comparison, src0, src1) => {
let mut mask = 0u32;
if exec != 0 {
// Sources are checked once for the wave, even if no present lane is active.
let check = |register: u8| {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
};
match src0 {
CompareSource::Vector(register) => check(register)?,
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?;
}
CompareSource::Immediate(_) => {}
}
check(src1)?;
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let s0 = match src0 {
CompareSource::Vector(register) => read(lane, register)?,
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?
}
CompareSource::Immediate(bits) => bits,
};
if comparison.holds(s0, read(lane, src1)?) {
mask |= 1 << lane;
}
}
}
scalars[VCC_LO] = Some(mask);
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
}
Op::Branch {
target: destination,
condition,
} => {
if condition == BranchCondition::VccZero && scalars[VCC_LO].is_none() {
return Err(error(offset, "branch with uninitialized VCC_LO"));
}
if condition == BranchCondition::VccZero && lane_derived_vcc {
check_runtime_region(
&program[position + 1..],
destination,
&registers,
&scalars,
exec,
pending_read.is_some(),
offset,
)?;
}
let take_branch = match condition {
BranchCondition::Always => true,
BranchCondition::SccZero => {
!scc.ok_or_else(|| error(offset, "branch with uninitialized SCC"))?
}
BranchCondition::VccZero => scalars[106] == Some(0),
BranchCondition::VccZero => scalars[VCC_LO] == Some(0),
BranchCondition::ExecZero => exec == 0,
};
if condition == BranchCondition::VccZero && scalars[106].is_none() {
return Err(error(offset, "branch with uninitialized VCC_LO"));
}
if take_branch {
target = destination;
}
None
}
Op::Vector(operator, dst, lhs, rhs) => {
Some((dst, vector_alu(operator, read(lhs)?, read(rhs)?, offset)?))
}
Op::End => {
if pending_read.is_some() || pending_write.is_some() {
if pending_read.is_some() || pending_write.iter().any(Option::is_some) {
return Err(error(offset, "outstanding transfer at termination"));
}
return output.ok_or_else(|| error(offset, "lane did not write its output"));
return output
.iter()
.map(|value| {
value.ok_or_else(|| error(offset, "lane did not write its output"))
})
.collect();
}
};
if let Some((dst, value)) = set {
if dst == 0 || pending_read == Some(dst) {
return Err(error(offset, "write to immutable or pending VGPR"));
}
for (lane, result) in results.into_iter().enumerate() {
if let Some((dst, value)) = result {
if dst == 0 || pending_read == Some(dst) {
return Err(error(offset, "write to immutable or pending VGPR"));
}
registers[lane][usize::from(dst)] = Some(value);
}
registers[usize::from(dst)] = Some(value);
}
}
Err(error(0, "missing decoded termination"))
}
/// docs/shaders/vector-compare.md section 6: code skipped by `s_cbranch_vccz`
/// on a lane-derived VCC_LO may hold only integer vector ALU instructions
/// whose destinations and sources are ready at the branch. Checked on the
/// code itself, whether or not the branch is taken.
fn check_runtime_region(
following: &[DecodedInstruction],
end: usize,
registers: &[[Option<u32>; 256]],
scalars: &[Option<u32>; 128],
exec: u32,
load_pending: bool,
branch: usize,
) -> Result<(), ReferenceError> {
if load_pending {
return Err(error(branch, "runtime VCC branch with an outstanding load"));
}
let ready = |register: u8| {
register != 0
&& registers
.iter()
.all(|lane| lane[usize::from(register)].is_some())
};
for instruction in following.iter().take_while(|item| item.offset < end) {
let offset = instruction.offset;
let (dst, vector_sources, scalar_source) = match instruction.op {
Op::Move(dst, Source::Register(src)) => (dst, vec![src], None),
Op::Move(dst, Source::Immediate(_)) => (dst, vec![], None),
Op::MoveScalar(dst, src) => (dst, vec![], Some(src)),
Op::Add(dst, lhs, rhs) => (dst, vec![lhs, rhs], None),
Op::Vector(kind, dst, lhs, rhs)
if !matches!(kind, VectorAlu::FloatAdd | VectorAlu::FloatMultiply) =>
{
(dst, vec![lhs, rhs], None)
}
_ => {
return Err(error(
offset,
"runtime VCC branch skips a non-integer-vector instruction",
));
}
};
if !ready(dst) {
return Err(error(
offset,
"runtime VCC branch skips a write to an uninitialized VGPR",
));
}
if exec == 0 {
continue;
}
if vector_sources.into_iter().any(|register| !ready(register)) {
return Err(error(
offset,
"runtime VCC branch skips an unready VGPR read",
));
}
if let Some(register) = scalar_source
&& scalars[usize::from(register)].is_none()
{
return Err(error(
offset,
"runtime VCC branch skips an unknown SGPR read",
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
+3
View File
@@ -223,6 +223,9 @@ fn lift(
VectorSource::Immediate(_) => {
return Err(error("graphics move requires finite FP32 bits"));
}
VectorSource::Scalar(_) => {
return Err(error("graphics move from an SGPR is unsupported"));
}
};
registers[usize::from(dst)] = Some(value);
}
+404 -26
View File
@@ -8,7 +8,14 @@ mod graphics;
pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub use xenora_decoder::Architecture;
use xenora_decoder::{DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorSource};
use xenora_decoder::{
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorCompareOp, VectorSource,
};
/// SGPR index of `vcc_lo`.
const VCC_LO: usize = 106;
/// SGPR index of `vcc_hi`.
const VCC_HI: usize = 107;
/// Entry point of all kernels produced by this compiler.
pub const ENTRY_POINT: &str = "xenora_compute";
@@ -94,6 +101,111 @@ enum Op {
target: usize,
taken: bool,
},
/// Wave32 VOPC result: bit n is EXEC[n] & (lane n exists) & test(lane n).
/// The value is wave-uniform; every thread computes it for its own wave.
LaneMask {
op: VectorCompareOp,
src0: Value,
src1: Value,
exec: u32,
},
/// `s_cbranch_vccz` on a lane-derived VCC_LO (IR annotation only).
RuntimeBranch {
mask: Value,
target: usize,
},
/// Join after a runtime `s_cbranch_vccz`: the fall-through value when the
/// mask is nonzero (branch not taken), else the value from before the branch.
JoinVccz {
mask: Value,
fallthrough: Value,
taken: Value,
},
}
impl Op {
fn operands(self) -> Vec<Value> {
match self {
Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(),
Self::Binary(_, left, right) => vec![left, right],
Self::MergeLanes {
active, inactive, ..
} => vec![active, inactive],
Self::Store(value) => vec![value],
Self::LaneMask { src0, src1, .. } => vec![src0, src1],
Self::RuntimeBranch { mask, .. } => vec![mask],
Self::JoinVccz {
mask,
fallthrough,
taken,
} => vec![mask, fallthrough, taken],
}
}
/// The MSL expression of a per-thread value, with operand names, the
/// dispatch index and the lane given by the caller.
fn expression(self, name: &dyn Fn(Value) -> String, index: &str, lane: &str) -> String {
match self {
Self::Load => format!("input[{index}]"),
Self::Constant(value) => format!("0x{value:08x}u"),
Self::Binary(operator, left, right) => {
let (left, right) = (name(left), name(right));
let (_, symbol) = operator.operator();
match operator {
Binary::FloatAdd | Binary::FloatMul => format!(
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
),
Binary::ArithmeticShiftRight => {
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
}
Binary::ShiftLeft | Binary::ShiftRight => {
format!("{left} {symbol} ({right} & 31u)")
}
_ => format!("{left} {symbol} {right}"),
}
}
Self::MergeLanes {
mask,
active,
inactive,
} => format!(
"((0x{mask:08x}u >> {lane}) & 1u) != 0u ? {} : {}",
name(active),
name(inactive)
),
Self::JoinVccz {
mask,
fallthrough,
taken,
} => format!(
"{} != 0u ? {} : {}",
name(mask),
name(fallthrough),
name(taken)
),
Self::Store(_)
| Self::ScalarBranch { .. }
| Self::LaneMask { .. }
| Self::RuntimeBranch { .. } => unreachable!("not a per-thread expression"),
}
}
}
fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
use xenora_decoder::CompareRelation;
let symbol = match op.relation {
CompareRelation::Less => "<",
CompareRelation::Equal => "==",
CompareRelation::LessOrEqual => "<=",
CompareRelation::Greater => ">",
CompareRelation::NotEqual => "!=",
CompareRelation::GreaterOrEqual => ">=",
};
if op.signed {
format!("as_type<int>({left}) {symbol} as_type<int>({right})")
} else {
format!("{left} {symbol} {right}")
}
}
#[derive(Clone, Copy)]
@@ -239,8 +351,16 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect();
let mut ir = String::new();
let has_mask = operations
.iter()
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. }));
let grid = if has_mask {
",\n uint grid [[threads_per_grid]]"
} else {
""
};
let mut msl = format!(
"#include <metal_stdlib>\nusing namespace metal;\nkernel void {ENTRY_POINT}(\n device const uint* input [[buffer(0)]],\n device uint* output [[buffer(1)]],\n uint index [[thread_position_in_grid]]) {{\n"
"#include <metal_stdlib>\nusing namespace metal;\nkernel void {ENTRY_POINT}(\n device const uint* input [[buffer(0)]],\n device uint* output [[buffer(1)]],\n uint index [[thread_position_in_grid]]{grid}) {{\n"
);
if operations.iter().any(|(_, operation)| {
matches!(
@@ -250,36 +370,32 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
}) {
msl.push_str(" #pragma clang fp contract(off)\n #pragma clang fp reassociate(off)\n");
}
for (index, (offset, operation)) in operations.into_iter().enumerate() {
// Wave-uniform values: identical in every lane of an RDNA wave.
let mut uniform = Vec::with_capacity(operations.len());
for (index, &(offset, operation)) in operations.iter().enumerate() {
let dest = Value(index);
uniform.push(match operation {
Op::Constant(_) | Op::LaneMask { .. } => true,
Op::Load | Op::MergeLanes { .. } => false,
_ => operation.operands().iter().all(|value| uniform[value.0]),
});
let thread = |value: Value| value.to_string();
let (step, statement) = match operation {
Op::Load => (
format!("{dest} = load.u32 input[index]"),
format!("uint {dest} = input[index];"),
format!(
"uint {dest} = {};",
operation.expression(&thread, "index", "")
),
),
Op::Constant(value) => (
format!("{dest} = const.u32 0x{value:08x}"),
format!("uint {dest} = 0x{value:08x}u;"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::Binary(operator, left, right) => (
format!("{dest} = {} {left}, {right}", operator.operator().0),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::Binary(operator, left, right) => {
let (mnemonic, symbol) = operator.operator();
let expression = match operator {
Binary::FloatAdd | Binary::FloatMul => format!(
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
),
Binary::ArithmeticShiftRight => {
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
}
Binary::ShiftLeft | Binary::ShiftRight => {
format!("{left} {symbol} ({right} & 31u)")
}
_ => format!("{left} {symbol} {right}"),
};
(
format!("{dest} = {mnemonic} {left}, {right}"),
format!("uint {dest} = {expression};"),
)
}
Op::ScalarBranch { target, taken } => {
let _ = writeln!(
ir,
@@ -287,6 +403,10 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
);
continue;
}
Op::RuntimeBranch { mask, target } => {
let _ = writeln!(ir, "{offset:04x}: branch.vccz {mask} -> 0x{target:04x}");
continue;
}
Op::MergeLanes {
mask,
active,
@@ -294,9 +414,32 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
} => (
format!("{dest} = merge.lanes mask=0x{mask:08x}, {active}, {inactive}"),
format!(
"uint {dest} = ((0x{mask:08x}u >> (index & 31u)) & 1u) != 0u ? {active} : {inactive};"
"uint {dest} = {};",
operation.expression(&thread, "", "(index & 31u)")
),
),
Op::JoinVccz {
mask,
fallthrough,
taken,
} => (
format!("{dest} = join.vccz {mask}, {fallthrough}, {taken}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::LaneMask {
op,
src0,
src1,
exec,
} => {
let _ = writeln!(
ir,
"{offset:04x}: {dest} = wave.mask {} {src0}, {src1} exec=0x{exec:08x}",
op.mnemonic()
);
emit_lane_mask(&mut msl, &operations, &uniform, index, op, src0, src1, exec);
continue;
}
Op::Store(value) => (
format!("store.u32 output[index], {value}"),
format!("output[index] = {value};"),
@@ -314,6 +457,59 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
})
}
/// Emit a Wave32 compare mask without any cross-thread operation: the thread
/// recomputes the lane-dependent operands of each lane of its own RDNA wave
/// (dispatch indices `(index & ~31) + n`) from those lanes' input words.
/// Absent lanes of a final partial wave contribute 0.
#[allow(clippy::too_many_arguments)]
fn emit_lane_mask(
msl: &mut String,
operations: &[(usize, Op)],
uniform: &[bool],
index: usize,
op: VectorCompareOp,
src0: Value,
src1: Value,
exec: u32,
) {
let mut cone = vec![false; index];
let mut pending = vec![src0, src1];
while let Some(value) = pending.pop() {
if uniform[value.0] || cone[value.0] {
continue;
}
cone[value.0] = true;
pending.extend(operations[value.0].1.operands());
}
let name = |value: Value| {
if cone[value.0] {
format!("l{}", value.0)
} else {
value.to_string()
}
};
let dest = Value(index);
let _ = writeln!(msl, " uint {dest} = 0u;");
let _ = writeln!(
msl,
" for (uint lane = 0u; lane < 32u; ++lane) {{\n uint lane_index = (index & ~31u) + lane;\n if (lane_index >= grid) {{ break; }}"
);
for (position, &(_, operation)) in operations[..index].iter().enumerate() {
if cone[position] {
let _ = writeln!(
msl,
" uint l{position} = {};",
operation.expression(&name, "lane_index", "lane")
);
}
}
let _ = writeln!(
msl,
" uint pass = ({}) ? 1u : 0u;\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
compare_expression(op, &name(src0), &name(src1))
);
}
fn decode_fixture(
architecture: Architecture,
bytes: &[u8],
@@ -326,7 +522,7 @@ fn decode_fixture(
fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, Op)>, CompileError> {
let mut operations = Vec::new();
let mut registers = [None; 256];
let mut registers = [None::<Value>; 256];
let mut facts = Vec::<KnownBits>::new();
let mut pending_load = None;
let mut stored = false;
@@ -336,6 +532,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
scalars[126] = Some(exec);
let mut scc = None;
let mut skip_before = 0;
// Set while VCC_LO holds a lane-derived compare mask (scalars[VCC_LO] is then None).
let mut lane_vcc: Option<Value> = None;
// An open runtime `s_cbranch_vccz` region: its end, mask and the VGPRs at the branch.
let mut region: Option<(usize, Value, [Option<Value>; 256])> = None;
// Every decoded instruction must satisfy the fixture layout and binding
// contract, even when a known branch skips it.
@@ -378,6 +578,70 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
for instruction in decoded {
let offset = instruction.offset;
let error = |reason| CompileError::Verify { offset, reason };
if let Some((end, mask, before)) = region
&& offset >= end
{
region = None;
for slot in 0..registers.len() {
if let (Some(fallthrough), Some(taken)) = (registers[slot], before[slot])
&& fallthrough.0 != taken.0
{
let next = Value(operations.len());
operations.push((
end,
Op::JoinVccz {
mask,
fallthrough,
taken,
},
));
let (left, right) = (facts[fallthrough.0], facts[taken.0]);
// Keep up to two candidate values when both edges have them.
let values = match (left.values, right.values) {
(Some([a, b]), Some([c, d])) => {
let mut union = vec![a, b, c, d];
union.sort_unstable();
union.dedup();
match union.as_slice() {
[only] => Some([*only; 2]),
[first, second] => Some([*first, *second]),
_ => None,
}
}
_ => None,
};
facts.push(KnownBits {
zero: left.zero & right.zero,
one: left.one & right.one,
values,
});
registers[slot] = Some(next);
}
}
}
// docs/shaders/vector-compare.md section 6: checked whatever EXEC is.
if let Some((_, _, before)) = &region {
let dst = match instruction.instruction {
Instruction::MoveB32 { dst, .. }
| Instruction::AddNoCarryU32 { dst, .. }
| Instruction::VectorLshlrevB32 { dst, .. }
| Instruction::VectorLshrrevB32 { dst, .. }
| Instruction::VectorAshrrevI32 { dst, .. }
| Instruction::VectorAndB32 { dst, .. }
| Instruction::VectorOrB32 { dst, .. }
| Instruction::VectorXorB32 { dst, .. } => dst,
_ => {
return Err(error(
"code skipped by a runtime s_cbranch_vccz may contain only integer vector ALU instructions",
));
}
};
if before[usize::from(dst)].is_none() {
return Err(error(
"a VGPR written under a runtime s_cbranch_vccz must be initialized before the branch",
));
}
}
let read = |register: u8| {
registers[usize::from(register)].ok_or_else(|| {
error("source register is uninitialized, pending a load wait, or reserved for indexing")
@@ -474,6 +738,36 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
dst,
src: VectorSource::Immediate(value),
} => (Some(dst), Op::Constant(value)),
Instruction::MoveB32 {
dst,
src: VectorSource::Scalar(register),
} if usize::from(register) == VCC_LO
&& let Some(mask) = lane_vcc =>
{
let slot = usize::from(dst);
if dst == 0 || pending_load.is_some_and(|(register, _)| register == slot) {
return Err(error(
"move writes the index register or replaces a pending load",
));
}
registers[slot] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
mask,
registers[slot],
)?);
continue;
}
// SGPR values are wave-uniform and known during translation.
Instruction::MoveB32 {
dst,
src: VectorSource::Scalar(register),
} => (
Some(dst),
Op::Constant(read_scalar(ScalarSource::Register(register))?),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?))
}
@@ -506,16 +800,100 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
if dst == 126 {
exec = value;
}
if usize::from(dst) == VCC_LO {
lane_vcc = None;
}
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
continue;
}
Instruction::ScalarAlu {
op,
dst,
src0,
src1,
} => {
let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?);
let carry_in = if op.reads_scc() {
scc.ok_or_else(|| error("carry-in or borrow-in reads uninitialized SCC"))?
} else {
false
};
if dst < 8 {
return Err(error("scalar ALU would modify a resource descriptor"));
}
let (value, flag) = op.evaluate(src0, src1, carry_in);
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
scc = Some(flag);
continue;
}
Instruction::ScalarCompareEqU32 { src0, src1 } => {
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
continue;
}
// docs/shaders/vector-compare.md sections 3 and 5.
Instruction::VectorCompare { op, src0, src1 } => {
if exec == 0 {
scalars[VCC_HI] = None;
scalars[VCC_LO] = Some(0);
lane_vcc = None;
continue;
}
let constant =
|operations: &mut Vec<(usize, Op)>, facts: &mut Vec<KnownBits>, bits: u32| {
let value = Value(operations.len());
operations.push((offset, Op::Constant(bits)));
facts.push(KnownBits::constant(bits));
value
};
let src0 = match src0 {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => constant(&mut operations, &mut facts, bits),
(None, None) => {
return Err(error("compare reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(&mut operations, &mut facts, bits)
}
VectorSource::Immediate(bits) => constant(&mut operations, &mut facts, bits),
};
let src1 = read(src1)?;
let mask = Value(operations.len());
operations.push((
offset,
Op::LaneMask {
op,
src0,
src1,
exec,
},
));
facts.push(KnownBits::UNKNOWN);
scalars[VCC_LO] = None;
scalars[VCC_HI] = None;
lane_vcc = Some(mask);
continue;
}
Instruction::BranchVccZero { target } if let Some(mask) = lane_vcc => {
if pending_load.is_some() {
return Err(error(
"a runtime s_cbranch_vccz requires no outstanding vector load",
));
}
region = Some((target, mask, registers));
(None, Op::RuntimeBranch { mask, target })
}
Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } => {
+28
View File
@@ -265,3 +265,31 @@ fn checks_fixture_layout_and_bindings_even_in_skipped_code() {
assert!(compiled.msl.contains("uint t1 = input[index];"));
assert!(compiled.msl.contains("output[index] = t3;"));
}
#[test]
fn scalar_alu_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-alu.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-alu.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-alu.metal")
);
}
#[test]
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
let result = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
result.ir,
include_str!("../../../fixtures/golden/vector-compare.ir")
);
assert_eq!(
result.msl,
include_str!("../../../fixtures/golden/vector-compare.metal")
);
}
+198
View File
@@ -0,0 +1,198 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoder for a bounded subset of BC6H.
//!
//! Source (public): Khronos Data Format Specification 1.3, section 20.2
//! "BC6H" (Tables 121 and 122, unquantization and final unquantization) and
//! section 20.1 (BC7 interpolation, Equation 2 and Table 119); Microsoft,
//! "BC6H Format" (Direct3D 11).
//!
//! Supported: the four single-subset modes, numbered as Khronos numbers
//! them (Microsoft's modes 11 to 14 in brackets): 3 (11, 10-bit endpoints),
//! 7 (12, 11-bit base, 9-bit deltas), 11 (13, 12-bit base, 8-bit deltas) and
//! 15 (14, 16-bit base, 4-bit deltas), for both signed and unsigned data.
//! Reserved modes 19, 23, 27 and 31 decode to zero as the specification
//! requires. The ten two-subset modes are rejected with
//! [`Bc6hError::UnsupportedMode`]; they are not implemented.
//!
//! Output texels are row-major `[r, g, b]` half-float bit patterns; the
//! format's alpha is always 1.0 and is not returned.
//!
//! Final unquantization follows the Khronos text: a negative interpolated
//! value keeps its sign bit even when its magnitude rounds to zero, so -1
//! becomes 0x8000 (-0.0). Microsoft's sample code returns 0x0000 there. This
//! is an open difference between the two public sources, not a hardware fact.
/// Khronos mode numbers this decoder implements.
pub const BC6H_SUPPORTED_MODES: [u8; 4] = [3, 7, 11, 15];
#[derive(Debug, PartialEq, Eq)]
pub enum Bc6hError {
/// A two-subset mode, identified by its Khronos mode number.
UnsupportedMode(u8),
}
/// Returns the block's Khronos mode number: the low two bits when they are
/// below two, otherwise the low five bits.
pub fn bc6h_mode(block: [u8; 16]) -> u8 {
if block[0] & 3 < 2 {
block[0] & 3
} else {
block[0] & 31
}
}
/// Decodes an unsigned (UF16) BC6H block.
pub fn decode_bc6h_ufloat(block: [u8; 16]) -> Result<[[u16; 3]; 16], Bc6hError> {
decode(block, false)
}
/// Decodes a signed (SF16) BC6H block.
pub fn decode_bc6h_sfloat(block: [u8; 16]) -> Result<[[u16; 3]; 16], Bc6hError> {
decode(block, true)
}
/// Reads the block from its least significant bit upward.
struct Bits {
bits: u128,
offset: u32,
}
impl Bits {
fn take(&mut self, count: u32) -> u32 {
let value = (self.bits >> self.offset) as u32 & ((1u32 << count) - 1);
self.offset += count;
value
}
/// `v[high..=low]`, lowest block bit first into bit `low`.
fn field(&mut self, target: &mut i32, high: u32, low: u32) {
*target |= (self.take(high - low + 1) << low) as i32;
}
/// Table 122's reversed `v[a..b]` with `a < b`: the lowest block bit
/// lands in bit `b` and each following bit one position lower.
fn reversed(&mut self, target: &mut i32, low: u32, high: u32) {
for bit in (low..=high).rev() {
*target |= (self.take(1) << bit) as i32;
}
}
}
/// Endpoint bits, delta bits and whether E1 is stored relative to E0.
fn single_subset(mode: u8) -> Option<(u32, u32, bool)> {
match mode {
3 => Some((10, 10, false)),
7 => Some((11, 9, true)),
11 => Some((12, 8, true)),
15 => Some((16, 4, true)),
_ => None,
}
}
fn sign_extend(value: i32, bits: u32) -> i32 {
let shift = 32 - bits;
(value << shift) >> shift
}
fn unquantize(x: i32, bits: u32, signed: bool) -> i32 {
if !signed {
if bits >= 15 {
x
} else if x == 0 {
0
} else if x == (1 << bits) - 1 {
0xffff
} else {
((x << 15) + 0x4000) >> (bits - 1)
}
} else if bits >= 16 {
x
} else {
let magnitude = x.abs();
let unq = if magnitude == 0 {
0
} else if magnitude >= (1 << (bits - 1)) - 1 {
0x7fff
} else {
((magnitude << 15) + 0x4000) >> (bits - 1)
};
if x < 0 { -unq } else { unq }
}
}
fn finish(i: i32, signed: bool) -> u16 {
if !signed {
((i * 31) >> 6) as u16
} else if i < 0 {
((((-i) * 31) >> 5) | 0x8000) as u16
} else {
((i * 31) >> 5) as u16
}
}
const WEIGHTS: [i32; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64];
fn decode(block: [u8; 16], signed: bool) -> Result<[[u16; 3]; 16], Bc6hError> {
let mode = bc6h_mode(block);
if matches!(mode, 19 | 23 | 27 | 31) {
return Ok([[0; 3]; 16]);
}
let (epb, delta, transformed) = single_subset(mode).ok_or(Bc6hError::UnsupportedMode(mode))?;
let mut bits = Bits {
bits: u128::from_le_bytes(block),
offset: 5,
};
let mut e0 = [0i32; 3];
let mut e1 = [0i32; 3];
for channel in &mut e0 {
bits.field(channel, 9, 0);
}
for c in 0..3 {
match mode {
3 => bits.field(&mut e1[c], 9, 0),
7 => {
bits.field(&mut e1[c], 8, 0);
bits.field(&mut e0[c], 10, 10);
}
11 => {
bits.field(&mut e1[c], 7, 0);
bits.reversed(&mut e0[c], 10, 11);
}
_ => {
bits.field(&mut e1[c], 3, 0);
bits.reversed(&mut e0[c], 10, 15);
}
}
}
debug_assert_eq!(bits.offset, 65);
let mut ends = [[0i32; 3]; 2];
for c in 0..3 {
let mut a = e0[c];
let mut b = e1[c];
if signed {
a = sign_extend(a, epb);
}
if transformed || signed {
b = sign_extend(b, delta);
}
if transformed {
b = (a + b) & ((1 << epb) - 1);
if signed {
b = sign_extend(b, epb);
}
}
ends[0][c] = unquantize(a, epb, signed);
ends[1][c] = unquantize(b, epb, signed);
}
let mut texels = [[0u16; 3]; 16];
for (texel, out) in texels.iter_mut().enumerate() {
// Texel 0 is the anchor: its implicit high index bit is zero.
let index = bits.take(if texel == 0 { 3 } else { 4 }) as usize;
let w = WEIGHTS[index];
for c in 0..3 {
let i = ((64 - w) * ends[0][c] + w * ends[1][c] + 32) >> 6;
out[c] = finish(i, signed);
}
}
Ok(texels)
}
+366
View File
@@ -0,0 +1,366 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoder for BC7 (BPTC RGBA, unsigned normalized).
//!
//! Source (public): Khronos Data Format Specification 1.3, section 20.1
//! "BC7": Table 109 (mode parameters), Table 111 (bit layout), the endpoint
//! P-bit and bit-replication text, Tables 114-118 (partitions and anchor
//! indices), the index-offset formula, Equation 2 with Table 119 (weights)
//! and Table 120 (rotation). Microsoft's "BC7 Format" pages describe the same
//! format. The partition and anchor tables below were extracted mechanically
//! from the Khronos HTML and checked for consistency (every anchor lies in its
//! subset).
//!
//! All eight modes are decoded. A block whose low byte is zero has no mode;
//! the specification says decoders return 0 for every channel of every texel,
//! and [`decode_bc7`] does so. [`bc7_mode`] tells such blocks apart.
//!
//! Output is the 8-bit value of each channel, row-major, texel 0 at the
//! top-left. The sRGB variant uses the same bytes with a different transfer
//! function, which is outside this decoder.
/// Modes this decoder implements (Khronos/Microsoft numbering).
pub const BC7_SUPPORTED_MODES: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
/// Table 109, one row per mode.
struct Mode {
subsets: usize,
partition_bits: u32,
rotation_bits: u32,
index_selection_bits: u32,
color_bits: u32,
alpha_bits: u32,
endpoint_pbits: bool,
shared_pbits: bool,
index_bits: u32,
index2_bits: u32,
}
#[rustfmt::skip]
const MODES: [Mode; 8] = [
Mode { subsets: 3, partition_bits: 4, rotation_bits: 0, index_selection_bits: 0, color_bits: 4, alpha_bits: 0, endpoint_pbits: true, shared_pbits: false, index_bits: 3, index2_bits: 0 },
Mode { subsets: 2, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 6, alpha_bits: 0, endpoint_pbits: false, shared_pbits: true, index_bits: 3, index2_bits: 0 },
Mode { subsets: 3, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 5, alpha_bits: 0, endpoint_pbits: false, shared_pbits: false, index_bits: 2, index2_bits: 0 },
Mode { subsets: 2, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 7, alpha_bits: 0, endpoint_pbits: true, shared_pbits: false, index_bits: 2, index2_bits: 0 },
Mode { subsets: 1, partition_bits: 0, rotation_bits: 2, index_selection_bits: 1, color_bits: 5, alpha_bits: 6, endpoint_pbits: false, shared_pbits: false, index_bits: 2, index2_bits: 3 },
Mode { subsets: 1, partition_bits: 0, rotation_bits: 2, index_selection_bits: 0, color_bits: 7, alpha_bits: 8, endpoint_pbits: false, shared_pbits: false, index_bits: 2, index2_bits: 2 },
Mode { subsets: 1, partition_bits: 0, rotation_bits: 0, index_selection_bits: 0, color_bits: 7, alpha_bits: 7, endpoint_pbits: true, shared_pbits: false, index_bits: 4, index2_bits: 0 },
Mode { subsets: 2, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 5, alpha_bits: 5, endpoint_pbits: true, shared_pbits: false, index_bits: 2, index2_bits: 0 },
];
/// Table 119 weights for 2-, 3- and 4-bit indices.
const WEIGHTS2: [u16; 4] = [0, 21, 43, 64];
const WEIGHTS3: [u16; 8] = [0, 9, 18, 27, 37, 46, 55, 64];
const WEIGHTS4: [u16; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64];
/// Table 114: subset of each texel (row-major) for the 64 two-subset partitions.
const PARTITION2: [[u8; 16]; 64] = [
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], // 0
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], // 1
[0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], // 2
[0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1], // 3
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1], // 4
[0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1], // 5
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1], // 6
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1], // 7
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1], // 8
[0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 9
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], // 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], // 11
[0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 12
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], // 13
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 14
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], // 15
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1], // 16
[0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], // 17
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0], // 18
[0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0], // 19
[0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], // 20
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0], // 21
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0], // 22
[0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1], // 23
[0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0], // 24
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0], // 25
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0], // 26
[0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0], // 27
[0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0], // 28
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], // 29
[0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0], // 30
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], // 31
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], // 32
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1], // 33
[0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0], // 34
[0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0], // 35
[0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], // 36
[0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0], // 37
[0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1], // 38
[0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1], // 39
[0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0], // 40
[0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0], // 41
[0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0], // 42
[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0], // 43
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0], // 44
[0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1], // 45
[0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1], // 46
[0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0], // 47
[0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], // 48
[0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0], // 49
[0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0], // 50
[0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], // 51
[0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1], // 52
[0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1], // 53
[0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0], // 54
[0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0], // 55
[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1], // 56
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1], // 57
[0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1], // 58
[0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1], // 59
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], // 60
[0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], // 61
[0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0], // 62
[0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1], // 63
];
/// Table 115: subset of each texel (row-major) for the 64 three-subset partitions.
const PARTITION3: [[u8; 16]; 64] = [
[0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 1, 2, 2, 2, 2], // 0
[0, 0, 0, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1], // 1
[0, 0, 0, 0, 2, 0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 1], // 2
[0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 1, 0, 1, 1, 1], // 3
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2], // 4
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2], // 5
[0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1], // 6
[0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1], // 7
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], // 8
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2], // 9
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2], // 10
[0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2], // 11
[0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2], // 12
[0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2], // 13
[0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2], // 14
[0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0, 2, 2, 2, 0], // 15
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2], // 16
[0, 1, 1, 1, 0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0], // 17
[0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2], // 18
[0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1], // 19
[0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2], // 20
[0, 0, 0, 1, 0, 0, 0, 1, 2, 2, 2, 1, 2, 2, 2, 1], // 21
[0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2], // 22
[0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 1, 0, 2, 2, 1, 0], // 23
[0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1, 0, 0, 0, 0], // 24
[0, 0, 1, 2, 0, 0, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2], // 25
[0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 0, 1, 1, 0], // 26
[0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1], // 27
[0, 0, 2, 2, 1, 1, 0, 2, 1, 1, 0, 2, 0, 0, 2, 2], // 28
[0, 1, 1, 0, 0, 1, 1, 0, 2, 0, 0, 2, 2, 2, 2, 2], // 29
[0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1], // 30
[0, 0, 0, 0, 2, 0, 0, 0, 2, 2, 1, 1, 2, 2, 2, 1], // 31
[0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 2, 2, 2], // 32
[0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 2, 0, 0, 1, 1], // 33
[0, 0, 1, 1, 0, 0, 1, 2, 0, 0, 2, 2, 0, 2, 2, 2], // 34
[0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0], // 35
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0], // 36
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0], // 37
[0, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 1, 0, 1, 2, 0], // 38
[0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1], // 39
[0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1], // 40
[0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2], // 41
[0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1], // 42
[0, 0, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2, 1, 1, 2, 2], // 43
[0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 1, 1], // 44
[0, 2, 2, 0, 1, 2, 2, 1, 0, 2, 2, 0, 1, 2, 2, 1], // 45
[0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1], // 46
[0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1], // 47
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2], // 48
[0, 2, 2, 2, 0, 1, 1, 1, 0, 2, 2, 2, 0, 1, 1, 1], // 49
[0, 0, 0, 2, 1, 1, 1, 2, 0, 0, 0, 2, 1, 1, 1, 2], // 50
[0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2], // 51
[0, 2, 2, 2, 0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2], // 52
[0, 0, 0, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2], // 53
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2], // 54
[0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2], // 55
[0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2, 2], // 56
[0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2], // 57
[0, 0, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2], // 58
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2], // 59
[0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1], // 60
[0, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 1, 2, 2, 2], // 61
[0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], // 62
[0, 1, 1, 1, 2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 2, 0], // 63
];
/// Table 118: anchor index of subset 1, two-subset partitions.
const ANCHOR2: [u8; 64] = [
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8,
2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2,
2, 15, 15, 15, 15, 15, 2, 2, 15,
];
/// Table 116: anchor index of subset 1, three-subset partitions.
const ANCHOR3_2: [u8; 64] = [
3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5,
15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5,
10, 8, 13, 15, 12, 3, 3,
];
/// Table 117: anchor index of subset 2, three-subset partitions.
const ANCHOR3_3: [u8; 64] = [
15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6,
10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8,
];
/// Reads the block's bits in increasing order, starting at bit 0 of byte 0.
struct Bits {
value: u128,
pos: u32,
}
impl Bits {
fn read(&mut self, n: u32) -> u32 {
let v = if n == 0 {
0
} else {
((self.value >> self.pos) & ((1u128 << n) - 1)) as u32
};
self.pos += n;
v
}
}
/// Returns the block's mode (the position of the lowest set bit of byte 0),
/// or `None` when byte 0 is zero, which the specification reserves.
pub fn bc7_mode(block: &[u8; 16]) -> Option<u8> {
(block[0] != 0).then(|| block[0].trailing_zeros() as u8)
}
/// Appends the P-bit (when present) below the stored bits and fills the rest
/// of the byte by replicating the top bits.
fn expand(stored: u32, bits: u32, pbit: Option<u32>) -> u8 {
let (v, width) = match pbit {
Some(p) => ((stored << 1) | p, bits + 1),
None => (stored, bits),
};
let high = v << (8 - width);
(high | (high >> width)) as u8
}
fn weights(bits: u32) -> &'static [u16] {
match bits {
2 => &WEIGHTS2,
3 => &WEIGHTS3,
_ => &WEIGHTS4,
}
}
/// Equation 2.
fn interpolate(e0: u8, e1: u8, weight: u16) -> u8 {
(((64 - weight) * u16::from(e0) + weight * u16::from(e1) + 32) >> 6) as u8
}
/// Decodes one BC7 block to sixteen RGBA8 texels, row-major.
pub fn decode_bc7(block: [u8; 16]) -> [[u8; 4]; 16] {
let Some(mode_number) = bc7_mode(&block) else {
return [[0; 4]; 16];
};
let mode = &MODES[usize::from(mode_number)];
let mut bits = Bits {
value: u128::from_le_bytes(block),
pos: u32::from(mode_number) + 1,
};
let partition = bits.read(mode.partition_bits) as usize;
let rotation = bits.read(mode.rotation_bits);
let index_selection = bits.read(mode.index_selection_bits);
// Endpoint fields: channel-major, then subset, then endpoint.
let endpoints = 2 * mode.subsets;
let mut raw = [[0u32; 4]; 6];
for channel in 0..3 {
for e in raw.iter_mut().take(endpoints) {
e[channel] = bits.read(mode.color_bits);
}
}
for e in raw.iter_mut().take(endpoints) {
e[3] = bits.read(mode.alpha_bits);
}
let mut pbits = [None; 6];
if mode.endpoint_pbits {
for p in pbits.iter_mut().take(endpoints) {
*p = Some(bits.read(1));
}
}
if mode.shared_pbits {
for subset in 0..mode.subsets {
let p = bits.read(1);
pbits[2 * subset] = Some(p);
pbits[2 * subset + 1] = Some(p);
}
}
let mut colors = [[0u8; 4]; 6];
for (e, color) in colors.iter_mut().enumerate().take(endpoints) {
for channel in 0..3 {
color[channel] = expand(raw[e][channel], mode.color_bits, pbits[e]);
}
color[3] = if mode.alpha_bits == 0 {
255
} else {
expand(raw[e][3], mode.alpha_bits, pbits[e])
};
}
let subset_of = |texel: usize| -> usize {
match mode.subsets {
2 => usize::from(PARTITION2[partition][texel]),
3 => usize::from(PARTITION3[partition][texel]),
_ => 0,
}
};
let is_anchor = |texel: usize| -> bool {
texel == 0
|| match mode.subsets {
2 => texel == usize::from(ANCHOR2[partition]),
3 => {
texel == usize::from(ANCHOR3_2[partition])
|| texel == usize::from(ANCHOR3_3[partition])
}
_ => false,
}
};
let mut read_indices = |width: u32| -> [u32; 16] {
let mut out = [0u32; 16];
if width > 0 {
for (texel, index) in out.iter_mut().enumerate() {
*index = bits.read(width - u32::from(is_anchor(texel)));
}
}
out
};
let primary = read_indices(mode.index_bits);
let secondary = read_indices(mode.index2_bits);
// Index selection: colour from the secondary indices when the bit is one;
// alpha from the secondary indices when they exist and the bit is zero.
let (color_index, color_bits, alpha_index, alpha_bits) = if mode.index2_bits == 0 {
(primary, mode.index_bits, primary, mode.index_bits)
} else if index_selection == 1 {
(secondary, mode.index2_bits, primary, mode.index_bits)
} else {
(primary, mode.index_bits, secondary, mode.index2_bits)
};
let mut out = [[0u8; 4]; 16];
for (texel, px) in out.iter_mut().enumerate() {
let subset = subset_of(texel);
let (e0, e1) = (colors[2 * subset], colors[2 * subset + 1]);
let wc = weights(color_bits)[color_index[texel] as usize];
let wa = weights(alpha_bits)[alpha_index[texel] as usize];
for channel in 0..3 {
px[channel] = interpolate(e0[channel], e1[channel], wc);
}
px[3] = interpolate(e0[3], e1[3], wa);
// Table 120.
if rotation > 0 {
px.swap(3, rotation as usize - 1);
}
}
out
}
+10 -1
View File
@@ -8,13 +8,22 @@
#![forbid(unsafe_code)]
mod bc;
mod bc6h;
mod bc7;
pub mod sampler;
mod upload;
pub use bc::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
pub use bc6h::{
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
};
pub use bc7::{BC7_SUPPORTED_MODES, bc7_mode, decode_bc7};
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
pub use upload::{
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
BcChannelFormat, BcChannelUpload, BcChannelUploadDesc,
};
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
+365 -37
View File
@@ -32,56 +32,219 @@ pub struct Bc1Subresource<'a> {
impl<'a> Bc1Upload<'a> {
pub fn new(bytes: &'a [u8], desc: Bc1UploadDesc) -> Result<Self, TextureError> {
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
if desc.format != 1
|| desc.usage != 1
|| desc.width == 0
|| desc.height == 0
|| desc.layers == 0
|| desc.mips == 0
|| desc.mips > max_mips
{
if desc.format != 1 || desc.usage != 1 {
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(desc.width, desc.height, 0);
let tight_row = blocks_x
.checked_mul(BLOCK_BYTES)
.ok_or(TextureError::SizeOverflow)?;
if desc.row_pitch < tight_row || !desc.row_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = desc
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if desc.slice_pitch < minimum_slice || !desc.slice_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let size = desc
.slice_pitch
.checked_mul(desc.mips as usize)
.and_then(|size| size.checked_mul(desc.layers))
.ok_or(TextureError::SizeOverflow)?;
if bytes.len() != size {
return Err(TextureError::InvalidByteLength);
}
Self::layout(desc).validate(bytes.len(), BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.desc.layers || mip >= self.desc.mips {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: Bc1UploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// A block-compressed format whose 16-byte block holds an alpha half followed
/// by a BC1-style colour half.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BcAlphaFormat {
/// Explicit 4-bit alpha per texel.
Bc2,
/// Interpolated alpha from two 8-bit endpoints and 3-bit indices.
Bc3,
}
/// A layer-major BC2 or BC3 upload with the same pitch rules as
/// [`Bc1UploadDesc`], measured in 16-byte blocks.
#[derive(Clone, Copy, Debug)]
pub struct BcAlphaUploadDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub layers: usize,
pub format: BcAlphaFormat,
pub row_pitch: usize,
pub slice_pitch: usize,
}
#[derive(Debug)]
pub struct BcAlphaUpload<'a> {
bytes: &'a [u8],
desc: BcAlphaUploadDesc,
}
impl<'a> BcAlphaUpload<'a> {
/// Size of one BC2 or BC3 block in bytes.
pub const BLOCK_BYTES: usize = 16;
pub fn new(bytes: &'a [u8], desc: BcAlphaUploadDesc) -> Result<Self, TextureError> {
Self::layout(desc).validate(bytes.len(), Self::BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn format(&self) -> BcAlphaFormat {
self.desc.format
}
/// Selects one level; the returned rows hold 16-byte blocks.
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: BcAlphaUploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// A single- or dual-channel block-compressed format: BC4 stores one 8-byte
/// red block, BC5 a red block followed by a green block.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BcChannelFormat {
Bc4Unorm,
Bc4Snorm,
Bc5Unorm,
Bc5Snorm,
}
impl BcChannelFormat {
/// Size of one block in bytes.
pub const fn block_bytes(self) -> usize {
match self {
Self::Bc4Unorm | Self::Bc4Snorm => 8,
Self::Bc5Unorm | Self::Bc5Snorm => 16,
}
}
}
/// A layer-major BC4 or BC5 upload with the same pitch rules as
/// [`Bc1UploadDesc`], measured in the format's block size.
#[derive(Clone, Copy, Debug)]
pub struct BcChannelUploadDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub layers: usize,
pub format: BcChannelFormat,
pub row_pitch: usize,
pub slice_pitch: usize,
}
#[derive(Debug)]
pub struct BcChannelUpload<'a> {
bytes: &'a [u8],
desc: BcChannelUploadDesc,
}
impl<'a> BcChannelUpload<'a> {
pub fn new(bytes: &'a [u8], desc: BcChannelUploadDesc) -> Result<Self, TextureError> {
Self::layout(desc).validate(bytes.len(), desc.format.block_bytes())?;
Ok(Self { bytes, desc })
}
pub fn format(&self) -> BcChannelFormat {
self.desc.format
}
/// Selects one level; the returned rows hold blocks of this format.
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: BcChannelUploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// Format-independent pitch rules shared by the pitched uploads.
struct PitchedLayout {
width: usize,
height: usize,
mips: u32,
layers: usize,
row_pitch: usize,
slice_pitch: usize,
}
impl PitchedLayout {
fn validate(&self, len: usize, block_bytes: usize) -> Result<(), TextureError> {
let max_mips = usize::BITS - self.width.max(self.height).leading_zeros();
if self.width == 0
|| self.height == 0
|| self.layers == 0
|| self.mips == 0
|| self.mips > max_mips
{
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(self.width, self.height, 0);
let tight_row = blocks_x
.checked_mul(block_bytes)
.ok_or(TextureError::SizeOverflow)?;
if self.row_pitch < tight_row || !self.row_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = self
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if self.slice_pitch < minimum_slice || !self.slice_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let size = self
.slice_pitch
.checked_mul(self.mips as usize)
.and_then(|size| size.checked_mul(self.layers))
.ok_or(TextureError::SizeOverflow)?;
if len != size {
return Err(TextureError::InvalidByteLength);
}
Ok(())
}
fn subresource<'a>(
&self,
bytes: &'a [u8],
layer: usize,
mip: u32,
) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.layers || mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
// Construction proved that the complete array fits in the source span.
let offset = (layer * self.desc.mips as usize + mip as usize) * self.desc.slice_pitch;
let width = (self.desc.width >> mip).max(1);
let height = (self.desc.height >> mip).max(1);
let offset = (layer * self.mips as usize + mip as usize) * self.slice_pitch;
let width = (self.width >> mip).max(1);
let height = (self.height >> mip).max(1);
let rows = height.div_ceil(4);
Ok(Bc1Subresource {
bytes: &self.bytes[offset..offset + rows * self.desc.row_pitch],
bytes: &bytes[offset..offset + rows * self.row_pitch],
width,
height,
row_pitch: self.desc.row_pitch,
row_pitch: self.row_pitch,
})
}
}
@@ -182,4 +345,169 @@ mod tests {
);
}
}
const ALPHA_DESC: BcAlphaUploadDesc = BcAlphaUploadDesc {
width: 5,
height: 5,
mips: 2,
layers: 2,
format: BcAlphaFormat::Bc3,
row_pitch: 48,
slice_pitch: 112,
};
#[test]
fn selects_bc_alpha_subresources_in_sixteen_byte_blocks() {
let mut bytes = [0; 448];
// Layer 1 starts at 224; its base row 1, block 1 is at 224 + 48 + 16.
bytes[288..304].fill(0x5c);
bytes[336] = 0xa7; // Layer 1, mip 1, block 0.
let upload = BcAlphaUpload::new(&bytes, ALPHA_DESC).unwrap();
assert_eq!(upload.format(), BcAlphaFormat::Bc3);
let base = upload.subresource(1, 0).unwrap();
assert_eq!((base.width, base.height, base.row_pitch), (5, 5, 48));
assert_eq!(base.bytes.len(), 96);
assert_eq!(base.bytes[64..80], [0x5c; 16]);
let small = upload.subresource(1, 1).unwrap();
assert_eq!((small.width, small.height, small.bytes.len()), (2, 2, 48));
assert_eq!(small.bytes[0], 0xa7);
assert_eq!(
upload.subresource(2, 0).unwrap_err(),
TextureError::OutOfBounds
);
assert_eq!(
upload.subresource(0, 2).unwrap_err(),
TextureError::OutOfBounds
);
}
#[test]
fn rejects_bc1_pitches_for_sixteen_byte_blocks() {
let bytes = [0; 448];
// Each pitch is a valid BC1 multiple of 8 but not of 16, or is
// shorter than two 16-byte blocks.
for desc in [
BcAlphaUploadDesc {
row_pitch: 24,
..ALPHA_DESC
},
BcAlphaUploadDesc {
row_pitch: 40,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 104,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 80,
..ALPHA_DESC
},
BcAlphaUploadDesc {
mips: 4,
..ALPHA_DESC
},
BcAlphaUploadDesc {
width: 0,
..ALPHA_DESC
},
BcAlphaUploadDesc {
height: 0,
..ALPHA_DESC
},
BcAlphaUploadDesc {
layers: 0,
..ALPHA_DESC
},
BcAlphaUploadDesc {
mips: 0,
..ALPHA_DESC
},
] {
assert_eq!(
BcAlphaUpload::new(&bytes, desc).unwrap_err(),
TextureError::InvalidLayout
);
}
// Short, oversized, and one block too few or too many for the layout.
let long = [0; 449];
for bytes in [&bytes[..447], &long[..], &bytes[..432], &[0; 464][..]] {
assert_eq!(
BcAlphaUpload::new(bytes, ALPHA_DESC).unwrap_err(),
TextureError::InvalidByteLength
);
}
assert_eq!(
BcAlphaUpload::new(
&bytes,
BcAlphaUploadDesc {
width: usize::MAX,
..ALPHA_DESC
}
)
.unwrap_err(),
TextureError::SizeOverflow
);
}
#[test]
fn sizes_bc4_and_bc5_pitches_by_their_block() {
let desc = BcChannelUploadDesc {
width: 5,
height: 5,
mips: 2,
layers: 2,
format: BcChannelFormat::Bc4Unorm,
row_pitch: 24,
slice_pitch: 56,
};
let mut bytes = [0; 224];
bytes[144] = 0x3c; // Layer 1, mip 0, row 1, block 1.
let upload = BcChannelUpload::new(&bytes, desc).unwrap();
assert_eq!(upload.format(), BcChannelFormat::Bc4Unorm);
let base = upload.subresource(1, 0).unwrap();
assert_eq!((base.bytes.len(), base.bytes[32]), (48, 0x3c));
// A BC4 pitch holds only half a BC5 row, and 24 is not a 16-byte multiple.
for format in [BcChannelFormat::Bc5Unorm, BcChannelFormat::Bc5Snorm] {
assert_eq!(
BcChannelUpload::new(&bytes, BcChannelUploadDesc { format, ..desc }).unwrap_err(),
TextureError::InvalidLayout
);
}
let bc5 = BcChannelUploadDesc {
format: BcChannelFormat::Bc5Snorm,
row_pitch: 48,
slice_pitch: 112,
..desc
};
let bytes = [0; 448];
assert_eq!(
BcChannelUpload::new(&bytes, bc5)
.unwrap()
.subresource(1, 1)
.unwrap()
.bytes
.len(),
48
);
// Short, oversized, and one block too few or too many for the layout.
for len in [447, 449, 432, 464] {
assert_eq!(
BcChannelUpload::new(&vec![0; len], bc5).unwrap_err(),
TextureError::InvalidByteLength
);
}
for desc in [
BcChannelUploadDesc { width: 0, ..bc5 },
BcChannelUploadDesc { height: 0, ..bc5 },
BcChannelUploadDesc { layers: 0, ..bc5 },
BcChannelUploadDesc { mips: 0, ..bc5 },
BcChannelUploadDesc { mips: 4, ..bc5 },
] {
assert_eq!(
BcChannelUpload::new(&bytes, desc).unwrap_err(),
TextureError::InvalidLayout
);
}
}
}
+237
View File
@@ -0,0 +1,237 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! BC6H subset tests.
//!
//! Hand-worked expectations follow the Khronos Data Format Specification 1.3,
//! section 20.2 (Tables 121 and 122, unquantization and final unquantization)
//! and the BC7 weight table (Table 119). The known-answer file holds vectors
//! produced by a separate clean-room reference decoder, not by this crate.
use xenora_texture::{
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
};
/// Packs fields into a block from bit 0 upward, as Table 122 reads them.
#[derive(Default)]
struct Writer {
bits: u128,
offset: u32,
}
impl Writer {
fn put(&mut self, value: u64, count: u32) -> &mut Self {
self.bits |= u128::from(value & ((1 << count) - 1)) << self.offset;
self.offset += count;
self
}
/// Table 122's reversed field `v[low..high]`: the first block bit holds
/// bit `high` of `value`, the next `high - 1`, down to `low`.
fn reversed(&mut self, value: u64, low: u32, high: u32) -> &mut Self {
for bit in (low..=high).rev() {
self.put(value >> bit, 1);
}
self
}
/// Writes the 63 index bits: texel 0 is the anchor (3 bits, implicit top
/// bit 0), every other texel 4 bits.
fn indices(&mut self, indices: [u64; 16]) -> [u8; 16] {
assert_eq!(self.offset, 65);
assert!(indices[0] < 8);
self.put(indices[0], 3);
for &index in &indices[1..] {
self.put(index, 4);
}
assert_eq!(self.offset, 128);
self.bits.to_le_bytes()
}
}
/// Index t for texel t, except the anchor texel 0, which must be below 8.
const RAMP: [u64; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// Mode 3 (Microsoft mode 11): 10-bit endpoints stored directly.
fn mode3(e0: [u64; 3], e1: [u64; 3], indices: [u64; 16]) -> [u8; 16] {
let mut w = Writer::default();
w.put(3, 5);
for value in e0.into_iter().chain(e1) {
w.put(value, 10);
}
w.indices(indices)
}
#[test]
fn mode3_unsigned_spans_zero_to_the_largest_half() {
let block = mode3([0; 3], [1023; 3], RAMP);
assert_eq!(bc6h_mode(block), 3);
let texels = decode_bc6h_ufloat(block).unwrap();
// Endpoint 0 unquantizes to 0 and the all-ones endpoint to 0xffff, which
// the final (i * 31) >> 6 maps to 0x7bff, 65504.0.
assert_eq!(texels[0], [0; 3]);
assert_eq!(texels[15], [0x7bff; 3]);
// Index 8 has weight 34: i = (34 * 0xffff + 32) >> 6 = 34815, and
// (34815 * 31) >> 6 = 16863 = 0x41df.
assert_eq!(texels[8], [0x41df; 3]);
// Index 1 has weight 4: i = (4 * 0xffff + 32) >> 6 = 4096, then
// (4096 * 31) >> 6 = 1984 = 0x07c0.
assert_eq!(texels[1], [0x07c0; 3]);
}
#[test]
fn mode3_signed_sign_extends_and_saturates_both_ends() {
// 0x201 is -511 in 10 bits; |x| >= 2^9 - 1 unquantizes to -0x7fff, and
// the final step gives ((0x7fff * 31) >> 5) | 0x8000 = 0xfbff (-65504.0).
// 511 gives 0x7fff -> 0x7bff (65504.0).
let block = mode3([0x201, 0x201, 0], [511, 0, 0x201], RAMP);
let texels = decode_bc6h_sfloat(block).unwrap();
assert_eq!(texels[0], [0xfbff, 0xfbff, 0x0000]);
assert_eq!(texels[15], [0x7bff, 0x0000, 0xfbff]);
// Index 8 between -0x7fff and 0x7fff: i = (30 * -32767 + 34 * 32767 + 32)
// >> 6 = 2048, so (2048 * 31) >> 5 = 1984 = 0x07c0 in red.
assert_eq!(texels[8][0], 0x07c0);
// Unsigned data reads 0x201 as 513: ((513 << 15) + 0x4000) >> 9 = 32864,
// and (32864 * 31) >> 6 = 15918 = 0x3e2e.
assert_eq!(decode_bc6h_ufloat(block).unwrap()[0][0], 0x3e2e);
}
#[test]
fn mode7_wraps_the_transformed_endpoint_at_eleven_bits() {
// Mode 7 (Microsoft 12): R0[9:0], G0[9:0], B0[9:0], then per channel
// R1[8:0] and R0[10]. E0 = 2047 in every channel, delta +1, so
// E1 = (2047 + 1) & 0x7ff = 0.
let mut w = Writer::default();
w.put(7, 5);
for _ in 0..3 {
w.put(0x3ff, 10);
}
for _ in 0..3 {
w.put(1, 9).put(1, 1);
}
let block = w.indices(RAMP);
let texels = decode_bc6h_ufloat(block).unwrap();
assert_eq!(texels[0], [0x7bff; 3]);
assert_eq!(texels[15], [0; 3]);
// Signed: E0 = 2047 is -1 in 11 bits and the delta +1 makes E1 = 0.
// -1 unquantizes to -((1 << 15) + 0x4000) >> 10 = -48, final -(48 * 31 >> 5)
// = -46 -> 0x802e.
let texels = decode_bc6h_sfloat(block).unwrap();
assert_eq!(texels[0], [0x802e; 3]);
assert_eq!(texels[15], [0; 3]);
}
#[test]
fn mode15_reads_its_reversed_high_bits() {
// Mode 15 (Microsoft 14): E0[9:0] per channel, then per channel E1[3:0]
// and E0[10..15] reversed. E0 = 0x8000 has only bit 15 set, which is
// the first bit of the reversed field. 16-bit endpoints are not
// unquantized, so E0 reads (0x8000 * 31) >> 6 = 0x3e00 unsigned.
let mut w = Writer::default();
w.put(15, 5);
for _ in 0..3 {
w.put(0, 10);
}
for _ in 0..3 {
w.put(1, 4).reversed(0x8000, 10, 15);
}
let block = w.indices(RAMP);
let texels = decode_bc6h_ufloat(block).unwrap();
assert_eq!(texels[0], [0x3e00; 3]);
// E1 = 0x8001: (0x8001 * 31) >> 6 = 0x3e00 as well.
assert_eq!(texels[15], [0x3e00; 3]);
// Swapping the reversed order would place bit 15 at bit 10: E0 = 0x400,
// which would read (0x400 * 31) >> 6 = 0x1f0 instead.
assert_ne!(texels[0][0], 0x01f0);
// Signed: 0x8000 is -32768 and passes through unquantization; the final
// step gives ((32768 * 31) >> 5) | 0x8000 = 0xfc00, negative infinity.
assert_eq!(decode_bc6h_sfloat(block).unwrap()[0], [0xfc00; 3]);
}
#[test]
fn mode11_places_its_two_reversed_bits() {
// Mode 11 (Microsoft 13): E1[7:0] then E0[10..11] reversed. E0 = 0x800
// (bit 11 only) and delta 0; 12-bit 0x800 = 2048 unquantizes to
// ((2048 << 15) + 0x4000) >> 11 = 32776, final (32776 * 31) >> 6 = 15875.
let mut w = Writer::default();
w.put(11, 5);
for _ in 0..3 {
w.put(0, 10);
}
for _ in 0..3 {
w.put(0, 8).reversed(0x800, 10, 11);
}
let block = w.indices([0; 16]);
assert_eq!(decode_bc6h_ufloat(block).unwrap()[5], [15875; 3]);
}
#[test]
fn reserved_modes_decode_to_zero() {
for mode in [19, 23, 27, 31] {
let block = [
mode, 0xff, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 1, 2, 3, 4, 5, 6,
];
assert_eq!(bc6h_mode(block), mode);
assert_eq!(decode_bc6h_ufloat(block).unwrap(), [[0; 3]; 16]);
assert_eq!(decode_bc6h_sfloat(block).unwrap(), [[0; 3]; 16]);
}
}
#[test]
fn rejects_every_two_subset_mode() {
let two_subset = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30];
for mode in 0..32u8 {
let block = [mode, 0xaa, 0x55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let number = bc6h_mode(block);
if two_subset.contains(&number) {
assert!(!BC6H_SUPPORTED_MODES.contains(&number));
assert_eq!(
decode_bc6h_ufloat(block),
Err(Bc6hError::UnsupportedMode(number))
);
assert_eq!(
decode_bc6h_sfloat(block),
Err(Bc6hError::UnsupportedMode(number))
);
}
}
// Two-bit modes: the low bits 0 and 1 select modes 0 and 1 whatever the
// next three bits hold.
assert_eq!(
bc6h_mode([0b11100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
0
);
assert_eq!(
bc6h_mode([0b11101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
1
);
}
fn hex16(text: &str) -> u16 {
u16::from_str_radix(text, 16).unwrap()
}
#[test]
fn matches_independent_known_answers_by_mode() {
let text = include_str!("fixtures/bc6h_vectors.txt");
let mut per_mode = std::collections::BTreeMap::<u8, usize>::new();
for line in text.lines().filter(|line| !line.starts_with('#')) {
let fields: Vec<_> = line.split(' ').collect();
let hex = fields[2];
let block: [u8; 16] =
std::array::from_fn(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap());
let want: Vec<[u16; 3]> = fields[3..]
.iter()
.map(|t| [0, 1, 2].map(|c| hex16(&t[4 * c..4 * c + 4])))
.collect();
let got = if fields[1] == "1" {
decode_bc6h_sfloat(block)
} else {
decode_bc6h_ufloat(block)
}
.unwrap();
assert_eq!(got[..], want[..], "vector {line}");
*per_mode.entry(bc6h_mode(block)).or_default() += 1;
}
// 16 vectors (8 unsigned, 8 signed) for each supported and reserved mode.
let expected: Vec<_> = [3, 7, 11, 15, 19, 23, 27, 31].map(|m| (m, 16)).into();
assert_eq!(per_mode.into_iter().collect::<Vec<_>>(), expected);
}
+340
View File
@@ -0,0 +1,340 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! BC7 tests. Expected values are worked by hand from the Khronos Data Format
//! Specification 1.3, section 20.1 (Table 109 parameters, Table 111 field
//! order, P-bits and bit replication, anchor indices, Equation 2 with the
//! Table 119 weights, Table 120 rotation). Blocks are packed by a test-local
//! bit writer; the production decoder never produces an expected value.
//!
//! Equation 2 rounding used below: `((64 - w) * e0 + w * e1 + 32) >> 6`.
//! With e0 = 0 and e1 = 255 the 2-bit weights give 0, 84, 171, 255; the 3-bit
//! weights give 0, 36, 72, 108, 147, 183, 219, 255; the 4-bit weights give
//! 0, 16, 36, 52, 68, 84, 104, 120, 135, 151, 171, 187, 203, 219, 239, 255.
use xenora_texture::{BC7_SUPPORTED_MODES, bc7_mode, decode_bc7};
/// Packs fields from bit 0 upward, starting with the mode's unary bits.
struct Block {
bits: u128,
pos: u32,
}
impl Block {
fn new(mode: u32) -> Self {
Block {
bits: 1 << mode,
pos: mode + 1,
}
}
fn put(&mut self, value: u32, n: u32) -> &mut Self {
assert!(
n == 32 || value < (1 << n),
"value {value} wider than {n} bits"
);
self.bits |= u128::from(value) << self.pos;
self.pos += n;
self
}
fn finish(&self) -> [u8; 16] {
assert_eq!(self.pos, 128, "fields must fill the block");
self.bits.to_le_bytes()
}
}
const W4: [u8; 16] = [
0, 16, 36, 52, 68, 84, 104, 120, 135, 151, 171, 187, 203, 219, 239, 255,
];
const W3: [u8; 8] = [0, 36, 72, 108, 147, 183, 219, 255];
#[test]
fn every_mode_is_listed_as_supported() {
assert_eq!(BC7_SUPPORTED_MODES, [0, 1, 2, 3, 4, 5, 6, 7]);
}
#[test]
fn mode_is_the_lowest_set_bit_of_byte_zero() {
for mode in 0..8u8 {
let mut block = [0xffu8; 16];
block[0] = 1 << mode;
assert_eq!(bc7_mode(&block), Some(mode));
// Higher bits of byte 0 belong to later fields, not the mode.
block[0] = 0xff << mode;
assert_eq!(bc7_mode(&block), Some(mode));
}
}
#[test]
fn zero_low_byte_is_invalid_and_decodes_to_zero() {
// Section 20.1: a low byte of 0 is reserved; decoders return 0 for all
// channels of all texels, whatever the other 15 bytes hold.
for fill in [0x00u8, 0xff, 0x5a] {
let mut block = [fill; 16];
block[0] = 0;
assert_eq!(bc7_mode(&block), None);
assert_eq!(decode_bc7(block), [[0; 4]; 16]);
}
}
#[test]
fn mode6_four_bit_indices_anchor_and_endpoint_pbits() {
// Mode 6: 7-bit RGBA endpoints, one P-bit per endpoint, 4-bit indices
// (3 bits for the anchor texel 0). e0 = 0 with P = 0 gives 0;
// e1 = 127 with P = 1 gives 0b1111_1111 = 255.
let indices: [u32; 16] = core::array::from_fn(|t| t as u32);
let block = |p1: u32| {
let mut b = Block::new(6);
for _ in 0..4 {
b.put(0, 7).put(127, 7); // R, G, B, A for e0 and e1
}
b.put(0, 1).put(p1, 1);
b.put(indices[0], 3);
for &i in &indices[1..] {
b.put(i, 4);
}
b.finish()
};
let out = decode_bc7(block(1));
for t in 0..16 {
assert_eq!(out[t], [W4[t]; 4], "texel {t}");
}
// With P = 0, e1 = 0b1111_1110 = 254: the P-bit is the lowest bit and no
// bit is replicated into an 8-bit value.
let out = decode_bc7(block(0));
assert_eq!(out[15], [254; 4]);
assert_eq!(out[0], [0; 4]);
}
#[test]
fn mode1_partition_shared_pbits_and_anchor() {
// Mode 1, partition 0 (Table 114: columns 2 and 3 are subset 1; Table 118
// anchor 15). 6-bit endpoints, one shared P-bit per subset, 3-bit indices,
// 2 bits for texels 0 and 15. Subset 0 (P = 0): 0 -> 0, 63 -> 0b1111110
// -> 252 | 1 = 253. Subset 1 (P = 1): 0 -> 0b0000001 -> 2, 63 -> 255.
// Equation 2 for subset 0: 0, 36, 71, 107, 146, 182, 217, 253;
// for subset 1: 2, 38, 73, 109, 148, 184, 219, 255.
let idx: [u32; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 3];
let mut b = Block::new(1);
b.put(0, 6);
for _ in 0..3 {
b.put(0, 6).put(63, 6).put(0, 6).put(63, 6);
}
b.put(0, 1).put(1, 1);
for (t, &i) in idx.iter().enumerate() {
b.put(i, if t == 0 || t == 15 { 2 } else { 3 });
}
let expected: [u8; 16] = [
0, 36, 73, 109, 146, 182, 219, 255, 0, 36, 73, 109, 146, 182, 219, 109,
];
let out = decode_bc7(b.finish());
for t in 0..16 {
let v = expected[t];
assert_eq!(out[t], [v, v, v, 255], "texel {t}");
}
}
#[test]
fn mode4_rotation_and_index_selection() {
// Mode 4: 5-bit colour, 6-bit alpha, 2-bit primary and 3-bit secondary
// indices. e0 = (0, 0, 31, 0) -> (0, 0, 255, 0); e1 = (31, 0, 31, 63) ->
// (255, 0, 255, 255). Primary indices are all 1 (weight 21 -> 84);
// secondary index of texel t is t % 8 (texel 0 is the anchor).
let block = |rotation: u32, selection: u32| {
let mut b = Block::new(4);
b.put(rotation, 2).put(selection, 1);
b.put(0, 5).put(31, 5); // R
b.put(0, 5).put(0, 5); // G
b.put(31, 5).put(31, 5); // B
b.put(0, 6).put(63, 6); // A
b.put(1, 1);
for _ in 1..16 {
b.put(1, 2);
}
b.put(0, 2);
for t in 1..16 {
b.put(t % 8, 3);
}
b.finish()
};
for t in 0..16 {
let s = W3[t % 8];
// Selection 1: colour from the 3-bit indices, alpha from the 2-bit
// ones, so RGBA = (s, 0, 255, 84); rotation 1 swaps A and R.
assert_eq!(decode_bc7(block(1, 1))[t], [84, 0, 255, s], "texel {t}");
// Selection 0: colour from the 2-bit indices (84, 0, 255), alpha s.
assert_eq!(decode_bc7(block(0, 0))[t], [84, 0, 255, s], "texel {t}");
assert_eq!(decode_bc7(block(2, 0))[t], [84, s, 255, 0], "texel {t}");
assert_eq!(decode_bc7(block(3, 0))[t], [84, 0, s, 255], "texel {t}");
}
}
#[test]
fn mode2_worked_example_index_bit_position() {
// Section 20.1 example: mode 2, partition 6, texel (1, 2) = index 9 is in
// subset 1 (endpoints 2 and 3) and its two index bits are block bits 115
// and 116. Endpoint 3 is all ones (5 bits -> 255), every other endpoint 0.
let mut b = Block::new(2);
b.put(6, 6);
for _ in 0..3 {
b.put(0, 5)
.put(0, 5)
.put(0, 5)
.put(31, 5)
.put(0, 5)
.put(0, 5);
}
b.put(0, 29);
let mut block = b.finish();
let mut bits = u128::from_le_bytes(block);
bits |= 0b11 << 115;
block = bits.to_le_bytes();
let out = decode_bc7(block);
for (t, px) in out.iter().enumerate() {
let want = if t == 9 {
[255, 255, 255, 255]
} else {
[0, 0, 0, 255]
};
assert_eq!(*px, want, "texel {t}");
}
}
#[test]
fn mode0_three_subset_anchors_store_one_bit_less() {
// Mode 0, partition 1: Table 116 anchor 3 and Table 117 anchor 8, plus
// texel 0. Endpoints 4 bits + P-bit: e0 = 0 (P 0) -> 0, e1 = 15 (P 1) ->
// 0b11111 -> 255. All 45 index bits set: anchors read 2 bits (index 3,
// weight 27 -> 108), the rest 3 bits (index 7 -> 255).
let mut b = Block::new(0);
b.put(1, 4);
for _ in 0..3 {
for _ in 0..3 {
b.put(0, 4).put(15, 4);
}
}
for _ in 0..3 {
b.put(0, 1).put(1, 1);
}
b.put(u32::MAX, 32).put((1 << 13) - 1, 13);
let out = decode_bc7(b.finish());
for (t, px) in out.iter().enumerate() {
let v = if [0, 3, 8].contains(&t) { 108 } else { 255 };
assert_eq!(*px, [v, v, v, 255], "texel {t}");
}
}
#[test]
fn mode7_alpha_endpoints_with_pbits() {
// Mode 7, partition 0: 5-bit RGBA + per-endpoint P-bit = 6 bits.
// Subset 0: 0 (P 0) -> 0, 31 (P 0) -> 0b111110 -> 251.
// Subset 1: 0 (P 1) -> 0b000001 -> 4, 31 (P 1) -> 255.
// Indices all 3, except anchors 0 and 15 (1 bit, set to 1, weight 21):
// subset 0 -> (21 * 251 + 32) >> 6 = 82; subset 1 -> (43 * 4 + 21 * 255 +
// 32) >> 6 = 86.
let mut b = Block::new(7);
b.put(0, 6);
for _ in 0..4 {
b.put(0, 5).put(31, 5).put(0, 5).put(31, 5);
}
b.put(0, 1).put(0, 1).put(1, 1).put(1, 1);
for t in 0..16 {
if t == 0 || t == 15 {
b.put(1, 1);
} else {
b.put(3, 2);
}
}
let out = decode_bc7(b.finish());
for (t, px) in out.iter().enumerate() {
let v = match t {
0 => 82,
15 => 86,
_ if t % 4 < 2 => 251,
_ => 255,
};
assert_eq!(*px, [v; 4], "texel {t}");
}
}
#[test]
fn mode3_eight_bit_endpoints_need_no_replication() {
// Mode 3: 7 bits + P-bit = 8 bits. Subset 0 e0 = 85 (P 1) -> 171,
// subset 1 e0 = 42 (P 0) -> 84; all indices 0. Alpha is 255.
let mut b = Block::new(3);
b.put(0, 6);
for _ in 0..3 {
b.put(85, 7).put(0, 7).put(42, 7).put(0, 7);
}
b.put(1, 1).put(0, 1).put(0, 1).put(0, 1);
b.put(0, 30);
let out = decode_bc7(b.finish());
for (t, px) in out.iter().enumerate() {
let v = if t % 4 < 2 { 171 } else { 84 };
assert_eq!(*px, [v, v, v, 255], "texel {t}");
}
}
#[test]
fn mode5_rotation_with_eight_bit_alpha() {
// Mode 5: 7-bit colour (-> 8 bits by replication), 8-bit alpha, 2-bit
// colour and alpha indices. e0 = (127, 0, 0, 10), e1 = (127, 0, 0, 200);
// 127 -> 255. Colour indices 0; alpha indices 3 (anchor texel 0 has 1
// bit, set to 1: (43 * 10 + 21 * 200 + 32) >> 6 = 72). Rotation 3 swaps
// A and B.
let mut b = Block::new(5);
b.put(3, 2);
b.put(127, 7)
.put(127, 7)
.put(0, 7)
.put(0, 7)
.put(0, 7)
.put(0, 7);
b.put(10, 8).put(200, 8);
b.put(0, 31);
b.put(1, 1);
for _ in 1..16 {
b.put(3, 2);
}
let out = decode_bc7(b.finish());
assert_eq!(out[0], [255, 0, 72, 0]);
for (t, px) in out.iter().enumerate().skip(1) {
assert_eq!(*px, [255, 0, 200, 0], "texel {t}");
}
}
#[test]
fn all_one_payloads_saturate() {
// Every field all ones: maximum endpoints expand to 255 and every index
// selects e1 (weight 64), so every channel is 255 in every mode.
for mode in 0..8u32 {
// Modes 4 and 5 also get rotation 3 (swap A and B, both 255).
let bits = u128::MAX << mode;
let out = decode_bc7(bits.to_le_bytes());
assert_eq!(out, [[255; 4]; 16], "mode {mode}");
}
}
/// Known-answer vectors from an independent clean-room reference decoder.
#[test]
fn independent_known_answer_vectors() {
let text = include_str!("fixtures/bc7_vectors.txt");
let mut count = 0;
for line in text
.lines()
.filter(|l| !l.starts_with('#') && !l.is_empty())
{
let mut fields = line.split_whitespace();
let tag = fields.next().unwrap();
let hex = fields.next().unwrap();
let block: [u8; 16] =
core::array::from_fn(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap());
let want: Vec<[u8; 4]> = fields
.map(|t| {
let v = u32::from_str_radix(t, 16).unwrap();
v.to_be_bytes()
})
.collect();
assert_eq!(want.len(), 16, "{tag}");
assert_eq!(decode_bc7(block).to_vec(), want, "{tag} {hex}");
count += 1;
}
assert!(count >= 300, "only {count} vectors");
}
+132
View File
@@ -0,0 +1,132 @@
# BC6H known-answer vectors from an independent clean-room reference decoder (Python, written
# from the Microsoft BC6H and Khronos BPTC texts by a separate reviewer; not Xenora's decoder).
# Seeded random and extreme-payload blocks for the four single-subset modes and the four
# reserved modes. Fields: reference-mode signed block-hex then 16 texels of rrrrggggbbbb half bits.
11 0 83ea63de09bae256474d77a3922fc7ec 66c326ab27f8 669f2b222b59 6541558e4b6a 669f2b222b59 662739a53651 662739a53651 66c326ab27f8 65af48294149 66e822342498 65dd42943d11 64ee5f9a5302 66e822342498 662739a53651 65665117480a 65665117480a 65135b234fa2
11 0 a38d3e6a3f3c6083660b71f11402542b 20ca1f096214 34512ee0512e 53de487735e2 0d420f3272fa 134414126dc7 3a5433c04bfb 134414126dc7 6d685d2e1fc9 26cc23e95ce1 134414126dc7 1ac71a296747 0d420f3272fa 26cc23e95ce1 2cce28c957ae 53de487735e2 1ac71a296747
11 0 23f083505649414fbb1eaf43a6e55411 54e12a335c6b 376936f055a1 28ae3d4f523c 682521de60dc 24253f455131 3bf234fa56ad 5df226475e82 596a283d5d77 4f362ca65b1d 3bf234fa56ad 54e12a335c6b 28ae3d4f523c 596a283d5d77 54e12a335c6b 682521de60dc 682521de60dc
11 0 23690f32bae380ea09cf46f44f8cc9b1 4ead02f4389a 65e603b12216 0e7800e876da 203a017965a2 4261028f4486 4ead02f4389a 4ead02f4389a 0e7800e876da 0e7800e876da 4ead02f4389a 203a017965a2 377402364f1e 31fd020a546a 203a017965a2 606f03842762 25b101a56056
11 0 439f70784476716762c37b1bc81e24b1 21d42077428e 350f3cdb3352 29b22c143c52 4aea5d1e2202 476b57f424c7 388e4204308d 476b57f424c7 21d42077428e 3c0e472e2dc7 4aea5d1e2202 52c868bb1bc6 21d42077428e 2d31313e398d 263326eb3f17 21d42077428e 476b57f424c7
11 0 6350574c754a6d65029add620e20dd6c 4b951a6d4e8f 4dec15215229 34c84e152b6f 37b447752ff0 2dc45df920a0 2dc45df920a0 48a9210d4a0e 3eb937913abe 2ad864991c1f 4dec15215229 4dec15215229 48a9210d4a0e 2dc45df920a0 2dc45df920a0 301b58ad243a 3eb937913abe
11 0 03000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
11 0 e3ffffffffffffffffffffffffffffff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff
11 1 c395d46c7ced9691f0d4acc885a373f4 2a43670def0b 68812c714699 3acb577bbecb 5fc034ae2d0d 5bdc385821b3 54143fac0aff 4b5347ea8e8b 5bdc385821b3 3eaf53d1b371 4b5347ea8e8b 36e75b25ca25 54143fac0aff 36e75b25ca25 47704b9399e6 3acb577bbecb 68812c714699
11 1 43937ad03385b0571e6cdfc6d2eb099e 26c74bb052c6 25993d9f7192 27bb570e39e6 269949865783 28535e172a81 27ea59383529 269949865783 27bb570e39e6 25d340536ba6 27ea59383529 278d54e33ea3 28245bec2f3d 27245005494c 256b3b75764f 28245bec2f3d 27245005494c
11 1 83093e199a9a32ed37d2ff5cc8cd8e01 063ab71431ec 063ab71431ec 0a03c3153692 a18146f50121 aa0561f78953 aa0561f78953 9db83af405c7 81569f1228a1 8da307f01987 9db83af405c7 a18146f50121 9db83af405c7 a63c55f684ad 8da307f01987 0ebed2163c61 1287de174107
11 1 03983502bd75a0f1cdd1179dc599bb85 84bc28fdba0c b61f375e988f 26b81c56d785 be0539ab9333 8ca32b4ab4b0 26b81c56d785 be0539ab9333 9c712fe4a9f9 0523261dc0bf b61f375e988f 9c712fe4a9f9 9c712fe4a9f9 ae3835119dea ae3835119dea 0523261dc0bf 948a2d97af55
11 1 e386b78ba8f59c269062282366aa1efd 0d71a33d10d5 aa3512f911fb 00429666111a 98a201da119e a4590d4411dc 00429666111a 859890b11139 00429666111a 98a201da119e 98a201da119e b1871a1b1222 b1871a1b1222 ca6d325c12a6 07959d8810f4 c31a2b3a127f d049381112c5
11 1 c3109d78f27e3cf0872579410fdde78e 1842547b3b7b 0ad461e91fbf 1324599930eb 1ad151ec40c4 084564781a77 0d635f5a2508 1e044eb9475e 15b3570a3633 885b751987df 20934c2b4ca7 82996f570403 82996f570403 0d635f5a2508 85cc728a8296 85cc728a8296 0ad461e91fbf
11 1 03000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
11 1 e3ffffffffffffffffffffffffffffff 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d
12 0 4719bf7e97173176f49b3193b40bf322 4c5216233c1a 58e90fe44862 550511d24496 52f512d84294 4b2d16b43afc 4d3c15ae3cff 4d3c15ae3cff 52f512d84294 4e27153a3de3 550511d24496 550511d24496 4a4217283a18 4d3c15ae3cff 58e90fe44862 4c5216233c1a 4c5216233c1a
12 0 07e5075c8bf908672b6ebe426d2f4f46 6ad702595c28 6d30018b59d1 633304f763c2 69dc02af5d21 633304f763c2 65bf04186139 6d30018b59d1 6b9f02145b60 642e04a262c8 69dc02af5d21 626b053c6489 6d30018b59d1 626b053c6489 6b9f02145b60 69dc02af5d21 6b9f02145b60
12 0 0725049118dd6e2b2d1c3a38a1ab0e3b 4daa5a1e4481 4f295c56431f 4b7756db4689 4f995cfe42b7 4c2b57e645e3 4ecf5bd14372 4cf559134527 4ecf5bd14372 4f995cfe42b7 4c2b57e645e3 4bd157604636 4c2b57e645e3 4aac55ae4745 4ff35d834263 4bd157604636 4ecf5bd14372
12 0 878f0383b3b8154de52389f31c1312f4 438b20ed5a86 3841294661f5 42a921955b1c 438b20ed5a86 3d2025ac5ec0 3e0225045e2b 42a921955b1c 375e29ed628a 3a3f27cd60a5 44a7201b59cc 42a921955b1c 44a7201b59cc 438b20ed5a86 44a7201b59cc 41c6223c5bb1 375e29ed628a
12 0 2796cdd98ea6c5ea5361ee419c855a8d 0b89761572e8 0ee676cf7237 0b89761572e8 0fe377057202 169c787870a0 169c787870a0 0b89761572e8 0e1b76a37260 14d4781670fe 124277887186 0ee676cf7237 1178775c71af 134077bf7152 0ee676cf7237 159f784170d5 1178775c71af
12 0 e7dbdbf2abaa433a0cc366276aed86fd 285359522175 2c88589c1e9b 2a6e58f72008 24485a022434 285359522175 285359522175 27ad596e21e6 2b1358db1f98 259359ca2353 285359522175 23a25a1e24a4 22d35a412530 285359522175 2708598b2256 23a25a1e24a4 222d5a5d25a1
12 0 07000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
12 0 e7ffffffffffffffffffffffffffffff 7bf47bf47bf4 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8
12 1 2790511ac1a5c8da3a085661d5dafcbf 16fee5940e28 1435e69f0f4a 1b84e3e20c4f 0faee8521122 18bbe4ed0d71 16fee5940e28 1113e7cc1091 18bbe4ed0d71 16fee5940e28 22d4e1230954 1ea6e2b40b08 22d4e1230954 216fe1a909e6 25f6dff7080d 25f6dff7080d 200be22f0a77
12 1 67453d894c03fb16d40428501029b19e 450eaff74710 4e32b3734afa 46a5b09247be 4344af49464b 4a05b1dc4930 450eaff74710 4344af49464b 4771b0e04815 4344af49464b 440faf9746a2 4ad1b2294987 450eaff74710 440faf9746a2 4c9bb2d84a4c 4f30b3d44b67 4ad1b2294987
12 1 87f6bd8a558e4a02b1b7bb756a77c20a 72dbce2aa634 6e0ec6b2a5d9 6fcac965a5fa 6e0ec6b2a5d9 6e0ec6b2a5d9 6e0ec6b2a5d9 70b6cad4a60b 6fcac965a5fa 6e76c754a5e1 7033ca08a602 6fcac965a5fa 6fcac965a5fa 71f0ccbca623 6da5c60fa5d1 6e76c754a5e1 72dbce2aa634
12 1 e78483d81d0a717b7cae055d7f7be30d 8490e21d66bd 8600e306689a 90c9e9d67690 8aace5f96ea7 82c4e0fb6469 04c8dc365aa3 8efde8b3743d 82c4e0fb6469 9239eabe786d 8600e306689a 8c1ce6e27083 8600e306689a 001cdf2a60b0 90c9e9d67690 8efde8b3743d 04c8dc365aa3
12 1 272e57ad460aaafa44bc46ce904b1597 299c5022674a 26d34d78671f 1afd4225666a 1c61437a667f 23b14a7966ee 26d34d78671f 17db3f266639 1afd4225666a 2cbe53216779 1f83467a66af 1c61437a667f 26d34d78671f 256e4c23670a 2b5a51cc6764 224c492466d9 1f83467a66af
12 1 e7a766408e14e948d9dae05c3676bdb1 d0c4e9279685 c657f6628c18 c9a1f2348f62 c657f6628c18 d56ee33c9b2f c4f8f8208ab9 c770f4fd8d31 cfabea8c956c ce4cec49940d d1dce7c3979d ce4cec49940d cd33edae92f4 c657f6628c18 c889f3998e4a d455e4a19a16 c889f3998e4a
12 1 07000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
12 1 e7ffffffffffffffffffffffffffffff 803d803d803d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d
13 0 6b31b4dfc2ca480e4ea472e570cb0c28 4b383a680b85 4aae39fa0b59 4aae39fa0b59 4bc33ad60bb1 4a5939b60b3e 4b383a680b85 4ad83a1c0b67 4c783b660beb 49f939690b20 4b383a680b85 4bed3af80bbf 4c183b1a0bcd 4c183b1a0bcd 49f939690b20 4b633a8a0b93 4a5939b60b3e
13 0 6b679c16a44d26a504fe8344e4fe6bc4 56ba47ac4e2a 570d47754dd9 54e448e14ff2 54c048f95016 569547c44e4d 55d448434f09 567047dd4e71 567047dd4e71 567047dd4e71 54e448e14ff2 54e448e14ff2 54c048f95016 555c48924f7e 561d48134ec2 567047dd4e71 553748aa4fa2
13 0 ab608b9ccb22086871d5aaa82b943a66 176a086e2d00 18ae095a2c52 184c09132c86 19bb0a1f2bc0 193a09c02c06 193a09c02c06 18d9097a2c3a 193a09c02c06 196509e02bef 17cb08b52ccc 182108f42c9d 190409992c23 193a09c02c06 17f608d42cb4 1883093b2c69 1883093b2c69
13 0 6ba60019822463ca99808fdb2d43a5b8 08686cbe6442 074b6cfe632f 094f6c8b6520 07826cf26364 05eb6d4d61db 07826cf26364 06d16d1a62ba 06656d326251 06656d326251 08d56ca664ab 089e6cb26476 08686cbe6442 08326ccb640e 07076d0d62ee 07826cf26364 06d16d1a62ba
13 0 2b8516af9a0c7e187cb6875e7cdf38ae 3dea6dae0afd 3db56da60b14 3dea6dae0afd 3cd56d850b77 3db56da60b14 3d816d9e0b2b 3c296d6c0bc2 3e2c6db70ae0 3ca06d7d0b8e 3db56da60b14 3bf46d640bda 3c6b6d760ba5 3d816d9e0b2b 3e966dc70ab1 3c296d6c0bc2 3d096d8d0b60
13 0 cb052921e4da656ec2d5658533352657 5e946f150fee 60a0701b0f21 5f526f740fa4 60cd70310f10 5f526f740fa4 5f8a6f900f8e 5f526f740fa4 5fe36fbc0f6b 5ef96f480fc7 5ef96f480fc7 5f526f740fa4 5ef96f480fc7 5f8a6f900f8e 5ecc6f310fd8 5fb66fa60f7d 5f526f740fa4
13 0 0b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
13 0 ebffffffffffffffffffffffffffffff 7bfa7bfa7bfa 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4
13 1 2b0c715b69ee4aef53a67f9dfa8ded8f f6596b0bb3af f72b6c71b43a f7686cdbb464 f83b6e40b4ef f93e6ffbb59d f79a6d2fb485 f8cf6f3db552 f7fd6dd7b4c7 f83b6e40b4ef f93e6ffbb59d f8cf6f3db552 f7cb6d83b4a6 f8cf6f3db552 f90d6fa6b57c f93e6ffbb59d f7cb6d83b4a6
13 1 2b1a5a0e55b33017bab63f4e31db8f45 4ccaf393281e 4f66f6992940 4d4af4272855 4f66f6992940 511af89429fd 4bfdf2a527c5 50b3f81d29d0 4c64f31c27f2 4b15f1982760 4bfdf2a527c5 4f66f6992940 5033f7872999 511af89429fd 4e18f51628af 4ccaf393281e 4c64f31c27f2
13 1 0bd0b66082241211b9999a5a46bc7f66 24fa145850fc 21cc113251f3 22c1122451a8 22c1122451a8 2239119d51d2 22c1122451a8 2239119d51d2 248e13ec511d 240613665145 24fa145850fc 216010c65214 21cc113251f3 1fff0f68527e 239a12fb5166 240613665145 240613665145
13 1 2be0cc4e41fce4957fa4feace520cc83 92e0a428b2b2 92e0a428b2b2 9166a4a3b339 9459a3aeb22b 9648a30db17a 96bca2e7b150 9542a362b1d8 9459a3aeb22b 91daa47db310 9648a30db17a 8f78a544b3eb 907da4efb38d 9542a362b1d8 9542a362b1d8 90f2a4c9b363 9354a402b288
13 1 ab9e0f74fab2380f7278f84b656558f3 4d39eadf1327 4f8f878c13e4 4fec07bb1401 4f8f878c13e4 4fec07bb1401 529d7a5514db 511639651460 4e64b9351386 4ec0a9ed13a3 4f3396d413c7 4ec0a9ed13a3 4f3396d413c7 4fec07bb1401 4ec0a9ed13a3 4e08c87d1369 529d7a5514db
13 1 cb54a21d4ea20bc7fabf633794dada44 2a87347ecef2 2d803847d395 2d803847d395 2c5336c8d1bf 29fa33cace15 2ae034efcf7c 2b273549cfeb 29fa33cace15 2a413424ce83 2bb535fed0c7 2c0d366ed151 2ce1377cd29c 2c0d366ed151 2ce1377cd29c 2a413424ce83 2a413424ce83
13 1 0b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
13 1 ebffffffffffffffffffffffffffffff 801e801e801e 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026
14 0 cf9b72f4638f22774cd1b4cb76061a92 3a8a424f3734 3a8b424f3734 3a8b424e3735 3a8a42503734 3a8b424f3734 3a8a42503734 3a8a42503734 3a8a42503734 3a8a424f3734 3a8a424f3734 3a8a424f3734 3a8b424e3735 3a8a42503734 3a8b424e3735 3a8b424f3735 3a8a424f3734
14 0 4f2fcdb4011321c629c9322cc3712f9d 312704a50df9 312704a60df9 312704a40df8 312704a30df8 312704a60df9 312704a50df9 312704a30df8 312704a60df9 312704a50df9 312704a30df8 312704a60df9 312704a40df8 312704a20df7 312704a60df9 312704a30df8 312704a40df8
14 0 cf610b8e57f3db527a0602bf3801aaaf 31e9573a2895 31e9573a2895 31e9573a2895 31ea573a2894 31ea573a2894 31ea573a2894 31e7573a2896 31e8573a2896 31e9573a2895 31ea573a2894 31ea573a2894 31ea573a2894 31e8573a2895 31e8573a2895 31e7573a2896 31e8573a2895
14 0 0ff230463c4a36297b2ffa54d5e7f73c 151a68cf5079 151b68cf5079 151d68cf5079 151a68ce5078 151c68cf5079 151d68cf5079 151a68cf5079 151a68cf5079 151a68cf5079 151c68cf5079 151b68cf5079 151d68cf5079 151b68cf5079 151d68cf5079 151c68cf5079 151a68ce5078
14 0 0f851bf05ca784cd51d54cebcc5f0dbb 36531f1a4cc2 36521f1b4cc1 36521f1b4cc1 36511f1c4cc0 36511f1c4cc0 36521f1b4cc1 36511f1c4cc0 36501f1d4cbf 36511f1c4cc0 36511f1c4cc0 36501f1d4cbf 36521f1b4cc1 36511f1c4cc0 36531f1a4cc2 36511f1c4cc0 36511f1c4cc0
14 0 6f0820d1556445ac7020163d1f18ce0c 07e0220752c8 07df220652c6 07e0220752c8 07df220652c7 07df220652c6 07e0220752c8 07de220552c4 07df220652c7 07dd220452c4 07e0220752c8 07df220552c6 07e0220752c8 07dd220452c4 07de220552c5 07de220552c5 07e0220752c8
14 0 0f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
14 0 efffffffffffffffffffffffffffffff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff
14 1 af4c414be3c07228605bc7eeb0957b8a f9aede72db68 f9b0de70db68 f9b1de6edb68 f9afde70db68 f9b0de6fdb68 f9b1de6ddb68 f9b2de6cdb68 f9b2de6cdb68 f9aede72db68 f9b1de6edb68 f9afde70db68 f9b0de6edb68 f9b1de6edb68 f9b0de6fdb68 f9b1de6edb68 f9b0de6fdb68
14 1 4f6aa14737501798d887942209199542 0719ab5ab2ba 071cab5cb2ba 071aab5ab2ba 071aab5ab2ba 0719ab5ab2ba 071bab5bb2ba 0718ab59b2ba 0718ab59b2ba 071bab5bb2ba 0717ab58b2ba 071bab5bb2ba 0717ab58b2ba 0719ab5ab2ba 071bab5bb2ba 0718ab59b2ba 0719ab5ab2ba
14 1 0f0d596fbf57f16ea872a24e726bc203 8b391dbac9e7 8b361db8c9e8 8b3a1dbbc9e6 8b381db9c9e7 8b3a1dbbc9e6 8b361db8c9e8 8b341db6c9e9 8b391dbac9e7 8b3a1dbbc9e6 8b381db9c9e7 8b361db8c9e8 8b381dbac9e7 8b3a1dbbc9e6 8b351db7c9e8 8b3a1dbbc9e7 8b3b1dbcc9e6
14 1 6fcc6e37b0d0073e092082fe83f765bd f5cebb3a9b06 f5d0bb399b05 f5d0bb399b05 f5cfbb399b06 f5cfbb399b06 f5cdbb3a9b07 f5cabb3b9b09 f5cabb3b9b09 f5cfbb399b06 f5cdbb3a9b07 f5cdbb3a9b07 f5cabb3b9b09 f5cebb3a9b06 f5cebb3a9b07 f5cbbb3b9b08 f5ccbb3a9b08
14 1 0f11cbaac2b462c4e95bc38d350f580b e81eeed51c68 e823eed11c63 e822eed21c64 e81feed41c67 e81eeed51c68 e822eed21c64 e823eed21c63 e820eed31c66 e81feed41c67 e81eeed51c68 e824eed11c62 e81ceed61c6a e820eed31c66 e81feed41c67 e822eed21c64 e81ceed61c6a
14 1 cf30ad6326db44472f4aa329cefa56a0 6a1b45221676 6a1a45201677 6a1c45231676 6a1a45211676 6a1a45201677 6a1c45231676 6a1b45231676 6a1a45201677 6a1d45251675 6a1c45241675 6a1c45231676 6a1d45251675 6a1b45211676 6a1a45211676 6a19451f1677 6a1c45231676
14 1 0f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
14 1 efffffffffffffffffffffffffffffff 800080008000 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001
reserved-10011 0 f351b28e379ef3cc23974fa11ae4df33 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 136d3b2575b7f255ada473da3e079db7 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 738e7213274477d61d1288ffbad50f9d 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 53286139206ef3ad8dceeebe4d8a5e8f 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 b3672b029498bda7a4171ab3067700b2 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 13dee0deed18b2d04c440be48e712020 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 13000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 f3ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 334b9a4d612c8f435384c7d34bdcdf2c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 731ad86fe0c6571bac7901208b1d6211 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 73c7fe9ff7cf8cfefd1869d16c9286ab 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 733887ce778dea855219e2339f561dab 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 d3a34181b9c6f3c837ac3e662c1c0eb3 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 33e3ef5b9d235bdd1247a95d46ee5749 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 13000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 f3ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 b7e1c82e010d600773774898d2f1dd53 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 f7ed84566d20896f394b75c4261f0c01 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 9724d37fd990b9919d90f5de8789a80c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 7728dbdb91480829c667bcaeff7bc13f 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 17ab206a9b7cd3f895da02b0dc0c85c9 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 b7d5da7364a2528ffa357b90325e8481 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 17000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 f7ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 d7642aa07f2eebb2431a378aef9961c2 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 b77c89a3d43e94836c10e90ab59a6f2c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 97a43f042a1e8d895de78928890f80d1 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 576df55ec42f850f4040db46b0cfae02 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 7758c6643576e926f533604fa2d1fa39 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 77996f1d78b2075dcfe7bab71ae59cdd 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 17000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 f7ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 bbfbaab673450835f6f954e64b3ef165 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 bb33f23e11b54443763775f6f83fd552 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 fb2d49b386fcadb7509d353a7ecfa604 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 7babfdaef421280052611eb416267772 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 7b2d89d90ceb76c968fcb08a06c393a5 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 dba41c8d2d0b283afd0fe1fb6c6e6cb9 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 1b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 fbffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 3b184617e7dfd7240f702fc183f37a5a 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 7bda84a6f91c1989aad47f10e2be1b39 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 1bf330718d597451452b016d3ac795dc 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 bb6d54956d076d18b1bf809d335e454f 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 1b96d95f746f8a0ef7ad8fc57fb4e2ab 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 7b758dd2449220bd382e73950a393ac2 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 1b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 fbffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 df8ff83cf4500003054962a613d93b54 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 5fe853ef0ba6fb775778568e3a33dd9d 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 dffc945c8158f47286ef2d6dca151fb0 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 bf109d944fe398e8d7b4b83d468ea650 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 ff2173b367f78590be5b344185d78d37 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 1ff003040b5bf3b2369db6a47d09a9f0 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 1f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 ffffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 7f970d19eefc041391f19d826eb79422 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 bf20a023685369cd0bbbda81cb11a99c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 9fe9f522ed3df999af7ec51b14f818a4 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 5fb49d03bd442dc50b8cbaefb59339df 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 bfdd210cc4870122ace8a5ccaff19a97 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 5f92c889004afbd953188d19ef334ae6 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 1f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 ffffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
+435
View File
@@ -0,0 +1,435 @@
# BC7 known-answer vectors: <mode/tag> <block, 16 bytes in memory order> <16 texels as RRGGBBAA>, row-major.
# Generated by a separate clean-room reference decoder (Python, written by an independent OpenAI Codex CLI run from
# the Khronos Data Format Specification 1.3 section 20.1 text, without access to this crate). Seed 1717.
# Covers random blocks, all-zero and all-one payloads per mode, every partition of modes 0, 1, 2, 3 and 7, every
# rotation of modes 4 and 5, both index-selection values of mode 4, and invalid blocks (low byte 0).
m0/random0 1d2b85c77a33222c266d903abce250f1 7e8b2fff 6fad48ff 74ac19ff 63a71eff 857b24ff 52a223ff 219431ff 9c1086ff 84b015ff 31992cff b1108dff 701078ff 74ac19ff b1108dff 46106aff 87107fff
m0/random1 896533f0252d8837e25ed81dd743be0b 84a0c2ff 3f46beff 5563c0ff 84a0c2ff 6b80c1ff 84a0c2ff 5563c0ff 2929bdff b59410ff a27810ff 532dbfff 8442f7ff 9d7110ff a77f10ff 201786ff 101073ff
m0/random2 4fff78897e2d1739f268829a53114425 ad4a8cff dcb3b2ff 8a9e35ff 969248ff f3e6c5ff b96395ff af7a6fff 8a9e35ff bd9c7bff aca073ff 73b510ff 7fa923ff 9aa36bff 65ae52ff a3865cff 73b510ff
m0/random3 83117a868e05214824f1068c7f35ee72 ce4a18ff ce4a18ff a86635ff 25b628ff a86635ff 8c7b4aff d62121ff 9c5223ff 396798ff 391b8eff 08ce29ff d62121ff 391b8eff 392d91ff 394093ff 5f8526ff
m0/random4 59efad71866d92df69c76da7a2a00aa7 9f32ceff c1a4a9ff 6b6b4aff ab6f6dff 9933d6ff eac0d8ff d5b2c1ff c14f92ff a531c6ff d5b2c1ff 958778ff c14f92ff a531c6ff 6b6b4aff a99590ff c14f92ff
m0/random5 b9d9705c8de5402f96832fe62e7e365a d49c9eff 70b72fff 8740a6ff a23965ff cf8990ff 8c29bdff 74a046ff 397bceff c66373ff 8c29bdff 7e6f77ff bc284bff d49c9eff 74a046ff 79885eff 536bb4ff
m0/random6 7fc58f788d0737c768d60a6cbc421706 a1ab87ff b5b594ff a77353ff deb865ff 7e9d6dff 648a5fff 296b39ff cca25fff 5b924aff 4a8c39ff 508053ff 7a966eff 5b924aff 92a481ff 5b924aff b5b594ff
m0/random7 67774eb590eeff7c100d49cbc81e6ec7 b55983ff a5f77bff a5f776ff a5f77fff b57dd7ff b55273ff a5f77fff a5f776ff b584e7ff b55983ff 5c6366ff 505a57ff b567a4ff 7b7b8cff 314231ff 505a57ff
m0/random8 4f720a74f4b686cb9d69ceb2ca5227eb 3949beff 8c9d6aff 3a86e7ff 4dace7ff 495aadff 7c8c7bff 4499e7ff 49a2e7ff 085aceff 7f426fff 4dace7ff 367ce7ff 1f55bbff 4e4c96ff 49a2e7ff 3f8fe7ff
m0/random9 755f6300cd5033de7c1dc6008ced95fe b58410ff ee68d7ff b58410ff b58410ff a56363ff 257fd4ff a56363ff 257fd4ff 0f9ee8ff 0f9ee8ff 24a6d2ff 16a1e1ff 1da3daff 0f9ee8ff 089cefff 24a6d2ff
m0/random10 afbbebf43dc3492be2ebd989be79ef16 def88aff def166ff cb8918ff cb8918ff defb96ff deef5aff a66418ff a66418ff 81b9c9ff a54252ff 6d2b18ff a66418ff a54252ff 9e5969ff b97718ff de9c18ff
m0/random11 af15c58a28160c3ffea52ecd4ccf8aee d6499bff d6499bff 3f89b8ff 7d2e37ff c647b9ff ad43e8ff 4e7399ff 309fd8ff 6432a5ff 614183ff 3f89b8ff 6e4457ff 614183ff 5c5d47ff 3f89b8ff 5f5a76ff
m0/random12 198ae4a4a2785d8863238431312199fa 085a29ff 2f955dff 3d62acff 33e72eff 332f37ff 4252c6ff 348379ff 48d75aff 085a29ff 397393ff 397393ff 33e72eff 332f37ff 397393ff 21c610ff 54cd73ff
m0/random13 4f92e9601921391289dbfdce60d0ca38 55c04bff 9cce9cff 5d1b53ff bb7983ff 55c04bff 21b510ff 5d1b53ff ce8c8cff 7394c6ff 26bed7ff 6f2d5dff a96779ff 17c6dbff 7394c6ff 4a084aff ce8c8cff
m0/random14 0bd444334d98caf3776ffad4e99d176b 4e87ccff ad6b9cff 3d80d1ff 504fe4ff 9672a8ff 1f95e3ff 3498c8ff 21c6b5ff 9672a8ff 1f95e3ff 945273ff 9b5088ff 089cefff 4e87ccff 9b5088ff a94bb3ff
m0/random15 7750be659d58afd7e7525e7c9cac5382 57cdcbff 4bc5cfff 9d8e7eff 297b9cff 3ebdd2ff 7fe7c1ff 3f55cdff ab9f84ff 7fe7c1ff 4bc5cfff f7c631ff 75908eff 4bc5cfff 4bc5cfff 2142e7ff ab9f84ff
m0/zero 01000000000000000000000000000000 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff
m0/ones ffffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m0/part0 a17257e2c8d0f6c15668d466c42de72a 6d6dbaff 93512bff b57fa9ff b56363ff 766697ff 805f70ff b56363ff b584b5ff 93512bff 1e7c2dff 19b044ff b5686fff 18bd4aff 1e7c2dff 1ba43eff 216321ff
m0/part1 a3a41cb89770450f20df6d5ec321eac5 4cd29fff 41cb93ff 2fc181ff 996608ff 46cf99ff 41cb93ff 5a4a08ff ef8c08ff 00b594ff 7764d2ff 5a4a08ff c57908ff b13df0ff 577ac1ff 1da1a3ff da8308ff
m0/part2 25d4b17b6ae652da35e8e5e762feda75 183929ff ad5adeff ad5adeff 6e4c92ff d98428ff 2d3e42ff 9855c5ff b639c9ff d98428ff de9c4aff a839c0ff 9a39b6ff dd9642ff dc903aff 9a39b6ff e139e6ff
m0/part3 87e065f77c9e48f5e91f07bb962a7a04 4273a5ff bd4affff bd4affff bd4affff 13c6a5ff 09d7a5ff bd4affff bd4affff 13c6a5ff 2f94a5ff 80a893ff 46e262ff 26a4a5ff 80a893ff f731f7ff f731f7ff
m0/part4 49201636f8f7ac203d48aa2ca5aa394a 1d2b48ff 0f991dff 137e27ff 0f991dff 137e27ff 1a453dff 1a453dff 0f991dff 3ee4abff 3ee4abff 51712aff 9d663cff 27eea0ff 3ee4abff 20781eff 20781eff
m0/part5 4ba8ba1fbb1fb2052e1b8f0ccc37617a 2690bdff 34b36dff a3ee47ff 66dc11ff 2184d6ff 34b36dff 66dc11ff deff7bff 2fa78aff 2fa78aff e732afff de089cff 2fa78aff 2a9ba3ff ff9cdeff e31da5ff
m0/part6 ed811bd77223750743c98d1086fde610 d56ba4ff 6d846dff 8494a5ff 949b8bff f763b5ff 2a944aff 8494a5ff b5a957ff dc2f28ff de1818ff da4639ff d0a67cff de1818ff cebd8cff d38f6bff cebd8cff
m0/part7 0f279d39d6b8a4f354b4dfef11ee1ab5 665abfff 3e9f9eff efceadff d8b29fff 31b594ff 8c18deff a87982ff cca498ff ce4561ff ce309aff d8b29fff e3c0a6ff ce5a29ff ce3788ff e3c0a6ff b38789ff
m0/part8 919629804e3c61c9d0f5b8bd4309348e 7b5f8cff 9d6d6aff 9d6d6aff bd7b4aff ad745aff 5a51adff 8c667bff 6a589dff a75e72ff ce296bff ce296bff 69b27dff 0e7fdeff 0215aeff 0e7fdeff 0c6ad4ff
m0/part9 53acaceeca91c73f1ab9fb25b3bc2c04 416af2ff 6352f7ff 535ef5ff 4b63f4ff 64b68aff 5ce134ff 61c56cff 5ce134ff 61c56cff 61c56cff 5ce134ff 61c56cff 5eb894ff 6873aeff 5ace8cff 5ace8cff
m0/part10 5509de2e83f34bafbbf2dfac26e6dccc 836498ff 582b82ff 745090ff 663d89ff 4dc0deff 70b9deff 4dc0deff 08cedeff 72b976ff 797193ff 6de863ff 7b5a9cff 797193ff 74a080ff 6de863ff 72b976ff
m0/part11 57efb3e7aee16ac802ab1f793d32b508 95783dff ad7b39ff f1c05fff 395a5aff 83753fff 7b7441ff d58448ff de7b8cff a57a3aff 95783dff e3a254ff 676368ff 83753fff ad7b39ff f1c05fff de7b8cff
m0/part12 99a58d883dc76a1c526a837fd71763d0 cece39ff 985f5aff 6b399cff 425252ff 57e6bcff a96e42ff c78716ff 425252ff 88dc86ff c78716ff 7a4686ff 4a6b29ff 88dc86ff d69400ff b87a2cff 47603aff
m0/part13 1b6b55c75d92bbcdc0325e7ec95f1793 74ecaaff b14147ff 49dc95ff 39de9cff 62e986ff b52163ff 9dd072ff 39de9cff 52e763ff aa741cff 49dc95ff 5ada8eff 8cefdeff ae5239ff 8cd379ff 8cd379ff
m0/part14 dda8933b1ff7403ebb34b08db8b62b50 5fb663ff 4eddbdff a7a7c3ff cd8b9dff 53d1a0ff d68494ff 94b5d6ff cb5369ff ba99b0ff ba99b0ff d600a5ff cb5369ff cd8b9dff c67352ff cb5369ff c8635eff
m0/part15 ffa3e456982238b2add70586d550679d f72110ff f72110ff 301f7bff 5a4adeff 9e7ec8ff 579d75ff b85237ff 4535adff 7310d6ff 8845cfff 579d75ff 996a4bff b3b3c1ff 8845cfff bdcebdff 768561ff
m1/random0 be553e451703ec9d1cf70be87385a543 7f528eff 565e76ff 565e76ff 7f528eff e732cbff 4b66dbff 4c45d5ff 934b9aff be3eb3ff 4e02c7ff 47cef0ff 7f528eff 7f528eff e732cbff 565e76ff 7f528eff
m1/random1 ee35a40a854d943ca984f6231e8393ed c030e4ff 40d991ff 40d991ff ab122aff 942537ff 55bd9fff 9667c9ff 7f86baff 942537ff ab122aff 0a9787ff 7f86baff 7f86baff 37726dff 37726dff 674a51ff
m1/random2 eaf90a7ac6f86ec1de9b178396f78a6d df2a27ff 82b4eaff 7b79a8ff 83bff7ff 7e90c2ff 7b79a8ff 80a8ddff b77fceff 7f9dd0ff af8fefff bf6eadff d73b48ff c75e8dff bf6eadff bf6eadff 82b4eaff
m1/random3 aadd0bf4fff94c4b137decab5e945aab 93d52fff b3ab33ff 67435cff b0486cff 89e22eff a8b832ff f54c7cff 89e22eff 9ec631ff 454154ff 89e22eff a8b832ff b0486cff d34a74ff 89e22eff a8b832ff
m1/random4 061488b4a521e62014fba47364546d59 578378ff 5e726fff 811840ff 76bee3ff 656066ff 6c4d5bff 6c4d5bff 3596ccff 5e726fff 733b52ff 5e726fff 5fb0dbff 656066ff 578378ff 656066ff 3596ccff
m1/random5 ea27e6b0d36d74d2cb987af7a8a274e0 8c7569ff b3769bff a2698cff 915c7dff b3769bff 3a1a32ff 915c7dff 8c7569ff 4b2741ff 8c7569ff 946058ff 71b49cff 838979ff 9d4c48ff 7aa08cff 6d415eff
m1/random6 3286fd11c17586560723a8f406d02e8a 4e1d60ff 4e1d60ff 33105cff 2e8c4dff d95c74ff 1f8837ff 7c9dc1ff 7c9dc1ff 7c9dc1ff 2e8c4dff 2e8c4dff 4e937dff 6d9aaaff 5e9694ff 6d9aaaff 5e9694ff
m1/random7 66dabf38da356591891ef90598f9664c 94675eff ff5e9bff a9656aff 7f6852ff 2c4ca1ff 6a6a46ff a9656aff ea608fff 2c4ca1ff ff5e9bff a9656aff a9656aff 36612fff 2c4ca1ff a9656aff 94675eff
m1/random8 8a6315da83d26d99cf48aef8be344f8e 7518a3ff 9f7439ff 851079ff cf6f47ff db6e4aff 5c24e4ff aa733cff 6420cfff 6c1cbaff cf6f47ff 6c1cbaff db6e4aff b87140ff 6c1cbaff aa733cff 6c1cbaff
m1/random9 ea57295819bb4c6dc80be6a6a64e7738 646faeff 4f4a2bff 44454cff 1533d2ff 44454cff 4f4a2bff 38416cff 6c7aa8ff 5a4e0aff 7d9199ff 8da68cff 859b93ff 7484a1ff 5c64b5ff 95b185ff 0a2ef3ff
m1/random10 6243e6faa3f4860fda8af2f463c411f1 0c8d3cff 6448a1ff c4b7b1ff cdafabff 6448a1ff 6448a1ff 0c8d3cff d6a7a4ff 3f6576ff 0c8d3cff 6448a1ff bbbfb7ff 18834aff 257a58ff 3f6576ff 6448a1ff
m1/random11 e27ab18eb8c9e4baea275c3dcb04cf7a 8fc3ceff 96b260ff a463bdff 1499a9ff a949dbff a07c9fff cbd7e0ff 8fc3ceff a463bdff ad30f9ff 32a3b2ff 8fc3ceff 92cc42ff adcdd7ff 1499a9ff a949dbff
m1/random12 7a5310c12f25bc1f5d4c0a8614ec2d70 389e94ff 460a16ff 460a16ff 7b562eff 4cbd7cff 42ae88ff 186fb9ff 460a16ff 8e7336ff 186fb9ff 0450d1ff 0e5fc5ff 693d26ff 460a16ff 8e7336ff 2e8fa0ff
m1/random13 cad58ed05f1b9b4421b22126aec0f2ea 567e12ff 818e13ff ae9f14ff 6c8613ff 6c8613ff d9af15ff 39bf8fff c4a715ff 567e12ff 20c589ff 6bb29aff 39bf8fff efb716ff c4a715ff 52b994ff efb716ff
m1/random14 5a576dc7a71d50dbb7ca3af126f9d517 7eae71ff 8fb673ff 7eae71ff a2c075ff d5d97cff c4d17aff a2c075ff a2c075ff db06afff d5d97cff d5d97cff 7eae71ff cd3dc3ff c752cbff b3c878ff 5c9d6cff
m1/random15 96a4dd3dbc97d3cf7f03a690dd7e6910 9be057ff 66e1a1ff 9be057ff 56db5fff bbabacff 4ed940ff afbe8dff 5edf82ff 5edf82ff d978fdff 4ed940ff bbabacff 46d621ff 91f13cff 56db5fff 91f13cff
m1/zero 02000000000000000000000000000000 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff
m1/ones feffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m1/part0 020f6527ec6340c96d8c6294b363d9e5 3cb124ff 4d4cc3ff db1a1aff 59376eff 486d8fff 448072ff 3f3c7fff 3f3c7fff 3fa13eff 4d4cc3ff a8253bff 3f3c7fff 4d4cc3ff 4a5da9ff 72315eff 8f2b4bff
m1/part1 0662a0f744639e10b47c9266eee98397 891040ff 761540ff 292a40ff ed9c39ff 511f40ff 172f40ff 292a40ff f79f7eff 3c2540ff 172f40ff 043440ff eb9b2eff 3c2540ff 043440ff 641a40ff ee9c45ff
m1/part2 0a1fff2656b9844fa74fd3009bf2ae70 7e5a3eff 516e7aff a93bd5ff bf2eebff 7e5a3eff 7e54a9ff 7e54a9ff 9447bfff 8e6346ff 26874eff 516e7aff 7e54a9ff d28666ff bf2eebff 3c7a64ff a93bd5ff
m1/part3 0e92074b1e5d132ba189653543d8d04e 518799ff 73c628ff 589383ff 6a4780ff 518799ff 5ea06dff c1d568ff b0b96dff 66ad54ff 6dba3eff b0b96dff 7b637bff 73c628ff 592c84ff b0b96dff b0b96dff
m1/part4 12cf80bfcee742947fb36f0f547675de 2a5799ff 1574e3ff 1574e3ff 2a5799ff 3e3a52ff 2261b4ff 314d82ff deaad9ff 2a5799ff 0e7efbff 314d82ff c964bfff 2a5799ff 1574e3ff d488ccff d488ccff
m1/part5 164dc4465118573b1f5719f78dcc8cc7 3b58f0ff 384ff0ff 536464ff 637474ff 4687f3ff 637474ff a2b5b5ff 92a5a5ff 447ef2ff 728484ff a2b5b5ff 839595ff 728484ff 445454ff b1c5c5ff 839595ff
m1/part6 1af64f0f38fe10cd305963332a165603 dbe336ff fae314ff fae314ff 612555ff e0e330ff e5e32bff 451e57ff d33e4eff eae325ff b73850ff 612555ff 451e57ff 9c3251ff 802b53ff d33e4eff d33e4eff
m1/part7 1e6c18f4e4fea6f984c2594d9b699a82 a7adbcff 93d579ff a7adbcff a0baa6ff a7adbcff a0baa6ff a0baa6ff d3a8bdff 9ac88fff 8de264ff 8fafb4ff d3a8bdff 9ac88fff 48b6aaff 04bda1ff 48b6aaff
m1/part8 223305a46d1ea83c0431e2925546da10 cdb5f1ff 62de59ff 73d872ff 85d18bff 85d18bff 73d872ff aac3bfff bbbcd8ff 98c9a6ff 85d18bff 85d18bff 909434ff 62de59ff cdb5f1ff 30343eff 020642ff
m1/part9 269ea26930813277550c72f2cb18ac29 78c1ddff 281054ff 6a6211ff 6a6211ff 281054ff 6a7313ff 6a9315ff 6a7313ff 6a6211ff 6a9315ff 6aa316ff 6a7313ff 6a5210ff 6a9315ff 6a5210ff 6aa316ff
m1/part10 2a2421a9f5e8724a074111891dc7353b 93d72aff 81cd35ff 6fc33fff 6fc33fff 48ad56ff 36a361ff 5db94aff 808f40ff 5db94aff 808f40ff 719a40ff 8e8540ff 56af40ff 719a40ff a97040ff 48b940ff
m1/part11 2ed9b3857e8d9a8fad5a411af42ab333 66fb3eff 4fe699ff 4fe699ff 44dcc5ff 66fb3eff 4fe699ff 44dcc5ff 55ec80ff 49e1afff 5bf16aff 44dcc5ff 7a9c7aff 49e1afff 779e87ff 819a63ff 6ca1a9ff
m1/part12 32ffe545a2a9d20625244fe71afbc113 bb9232ff a2943aff 75994aff 73b10eff 5e9b52ff 6bb612ff 64bc16ff 5cc21aff 55c81eff 46d326ff 64bc16ff 7aab0aff 4dcd22ff 64bc16ff 6bb612ff 7aab0aff
m1/part13 36567dcdf3281b305e8294381c2578be 6ac4c6ff 6ac4c6ff 6ac4c6ff c396ddff 6ac4c6ff a0a8d4ff 8db2cfff a0a8d4ff 7c978fff 7c978fff 5cc995ff bd3184ff 8c7e8dff bd3184ff cd1881ff 7c978fff
m1/part14 3abc99baacd4bc30fe82df765bba8ad3 ce87d1ff b468daff b468daff b468daff af70a6ff af70a6ff af70a6ff aa49b7ff b59894ff af70a6ff b59894ff ad5daeff b3859cff af70a6ff ad5daeff af70a6ff
m1/part15 3e8db5f83238f41d08a16585c5138773 3bc178ff 558d81ff 40b77aff 3bc178ff 4ba17eff 50977fff 36cb76ff 5a8383ff 3bc178ff 3bc178ff 558d81ff 3bc178ff a39378ff 826e69ff dcd493ff 492d4eff
m1/part16 42d1081d022122ff217abfe89d95899d 650da0ff 650da0ff 500bdfff 5b0cc0ff 1e227aff 7a105dff 650da0ff 85113eff 386d86ff 3d7c89ff 335f84ff 5b0cc0ff 2d4e81ff 28407fff 335f84ff 386d86ff
m1/part17 46dfd704356f843fabcd52e68a350dae 7cd5fdff 1468b3ff 361a6aff 224895ff 7cedbcff 7ce9c6ff 7cdde8ff 1a59a4ff 7ce9c6ff 7cedbcff 7ce5d1ff 7cedbcff 7cd5fdff 7ce5d1ff 7ce1ddff 7ce9c6ff
m1/part18 4aa553288b2f3e300ac76e45a4d92d88 6e82b4ff 45dca6ff 7b66b8ff 8849bdff 7b66b8ff 5fa3afff 5fa3afff 45dca6ff 168bc3ff 6e82b4ff 38f9a1ff 45dca6ff 1c75c4ff 168bc3ff 1c75c4ff 5fa3afff
m1/part19 4e6c103cb02e62ce16ad230a9358fa2d b3c33aff 167f64ff 068b46ff 2e6e91ff b3c33aff 1ee567ff 267383ff 267383ff b3c33aff 6ad450ff 9bc941ff 2e6e91ff 06eb6eff 6ad450ff 6ad450ff 9bc941ff
m1/part20 52c89e3fc3647110ba4ef6fc988d1ea7 3d154eff ed4ca1ff cf5da1ff 566f5cff ed4ca1ff 3d154eff d04393ff 856877ff b33a86ff 3d154eff 5a1e5bff ed4ca1ff 3d154eff d04393ff 3d154eff b33a86ff
m1/part21 56dc762c5ba6fdae93a244a5894128f8 6f6ba7ff 6e676eff 6f6a95ff 6f6ba7ff 28d3a2ff 6f6ba7ff 6f6ba7ff 6d654aff 1c68a5ff 1c68a5ff 6f6ba7ff 6e676eff 2192a4ff 1c68a5ff 2ae8a2ff 6c6438ff
m1/part22 5aed9991f22bab477164af38d887f1a2 adc61bff b0c81cff b4c91dff a2c117ff b4c91dff b7cb1eff adc61bff 9fbf16ff 79be3cff b7cb1eff a2c117ff b7cb1eff 93ab66ff 86b452ff b7cb1eff a6c218ff
m1/part23 5eb45a52ba7495f01c557ce7893fe64a c0a5c6ff 509554ff 5a8d52ff 8b6446ff a948cdff cbd2c3ff 8b6446ff 5a8d52ff a948cdff c0a5c6ff 6d7d4dff 8b6446ff a948cdff c6bcc4ff cbd2c3ff 8b6446ff
m1/part24 62e25408a5af2cb9de42ea2cc63badb8 78b1e6ff 55ebe8ff 142ba7ff 0c2d52ff 78b1e6ff 66cfe7ff 80a3e6ff 0c2d52ff 6fbfe7ff 4cf9e9ff 66cfe7ff 0c2d52ff 78b1e6ff 80a3e6ff 55ebe8ff 5ddde8ff
m1/part25 66eb7029ad7890ab081502d067d666b1 adb5adff adb5adff adb5adff 509c98ff 31831cff 0c8989ff 509c98ff 96afa8ff 484f2fff 80a9a3ff 69a29eff 69a29eff 31831cff 4f3f36ff 509c98ff 399593ff
m1/part26 6adb5cafaeffcbacc1a36503efd87411 7cc49dff b3d0acff caeedbff 7cc49dff 6ebbb3ff b3d0acff c4e7cfff cffb1aff 6ebbb3ff c4e7cfff c4e7cfff 89cd88ff cffb1aff caeedbff bedfc3ff 6ebbb3ff
m1/part27 6e1ee938d9b55a3c75f1c323bb6d7d5b 7a66f3ff 886196ff 3a8b9dff 3aa373ff 8164c6ff 3a66deff 3a66deff 8c607fff 8c607fff 3a72c9ff 3a72c9ff 8f5f69ff 3a5af3ff 3a66deff 8f5f69ff 8164c6ff
m1/part28 72d2f397c0ff6e7494b2e1b82c501b91 4a02d3ff 40db5aff 4826bfff a477afff 41b86eff c18eacff b283aeff fdbda5ff fdbda5ff e0a6a8ff b283aeff 41b86eff eeb2a7ff 4749abff 439481ff 439481ff
m1/part29 76307b58500869c13710247a89063916 bf4a15ff bd5326ff b86849ff b37b6bff 35510eff 24460dff 24460dff 2d4b0dff 35510eff 1c400cff 3f570eff 3f570eff ba5d37ff b86849ff b6725aff c14004ff
m1/part30 7a49b27c37f71559fa6f61297535693e 26df66ff 712380ff 435fd4ff 5a40a9ff 26c078ff 26c078ff 269195ff 4e50c0ff 663195ff 26819eff 26a08cff 26a08cff 712380ff 5a40a9ff 7c146cff 26d06fff
m1/part31 7e91dada3e81093c110bd8fedbfbead3 60b7b2ff 8d524fff ba54aaff d90808ff d90808ff a91010ff 9b3130ff d41423ff c43b75ff a91010ff 6f9792ff cf213dff d41423ff d90808ff 7e726fff 9b3130ff
m1/part32 823eb45749bd0770a7d8cd0ed5d04c82 ad71a3ff 95668eff 76a58cff ac8b73ff fb26c3ff 7f46a7ff c758adff ac8b73ff fb26c3ff 7f46a7ff e13fb8ff ac8b73ff c758adff c2ab5aff fb26c3ff c2ab5aff
m1/part33 86309b692f02492fb8833adf6f54fdc1 bd91acff ba7ba4ff b33689ff b12081ff 694992ff 6a4a83ff 6948a1ff 6743e0ff bd91acff b64c92ff bd91acff b12081ff 6a4a83ff 6743e0ff 6642efff 6845c1ff
m1/part34 8acbc9136b470f4e76e3fbacfc9e82c6 4e9f46ff 120ee3ff 3ea740ff 9480e1ff 5145e2ff 6f8e53ff 9480e1ff 9f7666ff 8f7e60ff 9480e1ff 4e9f46ff d3b7e0ff f3d3dfff 7f865aff d3b7e0ff 8f7e60ff
m1/part35 8e9e1652df84c651ac646206db1575db 787c44ff 6a53b3ff 68b84dff 80a832ff 787c44ff 71687aff 71b243ff 52c766ff 78ad3bff 78ad3bff 6f608fff 746f68ff 52c766ff 59c25eff 6a53b3ff 6a53b3ff
m1/part36 920eae3305cbb1e1b67a1d8837c3a968 81587cff 522c83ff e970adff 7e968eff e970adff 30b178ff b38775ff 522c83ff 81587cff 3a1687ff 30b178ff 7e968eff b5829eff cf79a6ff 6a4280ff 81587cff
m1/part37 96ff91e7b299b128d248c26e727f12dc fdc9a1ff e79342ff 5ba744ff e7863eff 9eb56bff e77c3cff 3ca032ff e79d44ff e7863eff 1c9920ff e77139ff ddc28fff e77139ff fdc9a1ff e7b34aff 3ca032ff
m1/part38 9a8d47074224b232bcb899f5c242e781 491bc9ff b48f40ff 7b9a67ff 6735c5ff 04b1b9ff 491bc9ff 360acbff 7b9a67ff 4012caff 5aa07eff 21aba5ff 4012caff 04b1b9ff 4012caff 360acbff 979454ff
m1/part39 9e313cf595e8cdd8b8d4e827aa291733 c4636dff ddc1bdff c1898dff 648444ff 648444ff c4636dff c5b5a5ff c28287ff aea98eff c4636dff ddc1bdff c27a80ff c55460ff 939c73ff c28287ff 4c782cff
m1/part40 a2578836d9bc5b9073faffcc5d9478c1 6f923fff 365afbff 94daacff 456feeff 76a33dff 6f923fff 365afbff 84c5b9ff 6499d4ff 84c5b9ff 6a8440ff 76a33dff 365afbff 84c5b9ff a3ef9fff 81c03bff
m1/part41 a61ccb811c20958cd169bac9385bb796 825129ff 8b4126ff 8b4126ff 776073ff a8101bff 707030ff 83976aff 7c776fff 745574ff 796a71ff 9f201fff 8b4126ff 796a71ff 9f201fff 9f201fff 962f22ff
m1/part42 aa89df412037b3734149aef06988606c 7e7a7fff 607c99ff 6fcb51ff 76cf52ff f97014ff 7e7a7fff 67c750ff 7e7a7fff 2481cdff 6fcb51ff 607c99ff 2481cdff 49b74bff 76cf52ff 7e7a7fff 7e7a7fff
m1/part43 ae9dd7185fa4ecb6ed55517dc642bd86 767edbff 7956dbff 2c5f6eff 1cd159ff 18ed54ff 785edbff 304473ff 1cd159ff 2c5f6eff 342878ff 7956dbff 1cd159ff 287b69ff 20b65eff 7776dbff 785edbff
m1/part44 b2068fc194c9030795404255a5377b5c 18501cff 9a6836ff 7daf2eff 55652bff a8463aff 55652bff 375a23ff a8463aff c30242ff d28f49ff 957a3aff a8463aff f19950ff 62f326ff c30242ff 55652bff
m1/part45 b6377e31b679095dc476de817ca72fb8 dfbe60ff e0ab52ff 4b3b99ff 5e5eb3ff 452d90ff 452d90ff e19944ff e0ab52ff 4b3b99ff 5246a2ff e19944ff dfbe60ff ded06dff ddd974ff 320a76ff 5246a2ff
m1/part46 baec0881bd13ce6635987654d5ef5298 acda8fff 83cf9bff 42870eff 976d67ff a7c086ff 71bb73ff 549b36ff 8d3854ff 83cf9bff 92535eff 976d67ff 68b160ff 549b36ff b1f599ff a2a57cff 549b36ff
m1/part47 bef780a5eaa1c4af71b2973f5d6f8781 c297a8ff c297a8ff 0e1e1aff 0e1e1aff c297a8ff 949badff 7f6ca7ff a48391ff 0e1e1aff 949badff 949badff 877079ff dfabbfff 877079ff dfabbfff 665960ff
m1/part48 c2a9c379b0c54b4f307971fad7d5e4df a7c33eff 784878ff 68861eff 49690eff 784878ff 784878ff 72c158ff 49690eff 597816ff 72c158ff 799726ff 88a52eff 49690eff 3a5a06ff 3a5a06ff 49690eff
m1/part49 c6fd15277298f406e3ba9aaa7b6d05d7 cab61fff dfbf1bff b043bbff 879829ff cab61fff 26f7bbff 3ddabbff 837ebbff 879829ff 879829ff 53bcbbff cab61fff f5c918ff 728f2dff 879829ff 728f2dff
m1/part50 caea3c26d54a2feb16c76281f47833b1 a954adff c8a075ff b36d9bff a954adff be8787ff be8787ff 71a5c7ff cdad6cff a954adff 262ec7ff 445cc7ff 80bcc7ff b87a92ff b36d9bff 5274c7ff c3947eff
m1/part51 ce482887b71b10615cb7643efbba68e7 2ed88eff 77bebcff 5ac8aaff 85b9c5ff 2ed88eff ac09c8ff 85b9c5ff 4bcea0ff bf06d1ff 8510b5ff b607ccff 5ac8aaff 77bebcff 8f0ebaff 2ed88eff 85b9c5ff
m1/part52 d29e0dfbcc919230d36801ea8583ec74 7a32c3ff c1a534ff e19952ff 952c9aff f99168ff e99759ff 7a32c3ff cd2146ff c9a23bff 7a32c3ff 882fafff d99d4aff db1e32ff b2266fff f19461ff c9a23bff
m1/part53 d646a481d7e467bc766ffb9b32d1f950 265accff 464e6aff 83666eff 7f7b7eff 3355a4ff 71d1bfff 7f7b7eff 3355a4ff 6afbdfff 7c908eff 2d57b9ff 40507dff 83666eff 1a5ef3ff 265accff 6ee6cfff
m1/part54 dac21351f23a8972208898b4918cce39 17c192ff 46551aff 46551aff 17c192ff 1ebd76ff 1ebd76ff 4b6f53ff 4b6f53ff 4b6f53ff 0fc5adff 17c192ff 508989ff 4b6f53ff 49663eff 35b120ff 0fc5adff
m1/part55 deb4b411c0711f337c54253e9b3b41a6 c006cdff ac0accff 6cdd1cff 101c54ff 458c34ff 5d1ac5ff 5d1ac5ff 376d3cff 458c34ff 101c54ff 8412c8ff d302cfff 8412c8ff 376d3cff 5fc224ff 7116c6ff
m1/part56 e252155b9a526fdf9f27d71fb406763c 4c6190ff 798c5cff 5a6e26ff 562affff c7d7e7ff 889a77ff 5433edff 4d58a2ff 99ab96ff c7d7e7ff 5145c9ff 533cdbff 99ab96ff 5145c9ff 562affff c7d7e7ff
m1/part57 e6757dc7a83e03b49601b663a285dc8c d5abc2ff d5793cff c70202ff d5a1d1ff d5bfa5ff d5b5b3ff d1582cff ca1f10ff d5b5b3ff d5a1d1ff dcb258ff c70202ff ca1f10ff d5cb94ff d5abc2ff d8954aff
m1/part58 eaca8d3810519f14125908ff993229de 5b3343ff 20d544ff 35a555ff 389d58ff 389d58ff 23cd47ff 2abd4cff 5b3343ff 23cd47ff 742c3cff 5b3343ff 5b3343ff 413949ff c41727ff 742c3cff 2abd4cff
m1/part59 ee70c83622acfed4daefb549c1b5bda4 bb935fff aaa379ff aaa379ff 8ec1f3ff 8ec1f3ff bb935fff c38b52ff 87c3afff 8ec1f3ff 7cccf2ff 7cccf2ff 87c3afff 98b395ff 69daf0ff 69daf0ff 8ec1f3ff
m1/part60 f2421c77c768379730251eab1554c77e 584c39ff 232c50ff aa7d14ff 3d3c44ff 8d6431ff 8d6431ff b0ad43ff c7db4eff 3d3c44ff 906d20ff 814d2cff bcc448ff aa7d14ff aa7d14ff 763626ff bcc448ff
m1/part61 f6ae6c5440cf2916bb0392e1119cc22a b90058ff bb2265ff 33548bff 1a72efff c7d3a4ff c0677eff 3d4866ff 1a72efff 3d4866ff 33548bff 2b5eacff 2268ceff c28e8bff c5b098ff be4571ff bb2265ff
m1/part62 fa274755c9b66d24d5aba007ad00eae2 9d2491ff 90387fff 526cd5ff 8a4276ff 9d2491ff 90387fff 526cd5ff 7d5862ff 506cf5ff 506cf5ff 506cf5ff 7d5862ff 536cb4ff 536cbeff 506cf5ff 706c50ff
m1/part63 fed7faed3cbfd4e09bf5d2eaf71c80ee 5cf181ff cfa7ceff 96f1acff 73f192ff adf1bdff efd7f7ff a2f1b5ff 7ef19aff a2f1b5ff 8e467aff 7e2e66ff 7e2e66ff 8bf1a4ff dfbfe3ff cfa7ceff ae75a3ff
m2/random0 dcce5103bc6041fdab6ac916ea97a17f 3941baff 397cc9ff 39b5d6ff 39b5d6ff 3941baff 3f3984ff 520094ff 39b5d6ff 520094ff 00ff5aff 28c952ff 2b7473ff 18ad63ff 7b5a42ff 7b5a42ff 3f3984ff
m2/random1 f4fe6870d20814bc8aecea565d31fd5c b35e5fff b35e5fff 73629aff 73629aff ff8c21ff 848473ff 9cbd5aff 9f9a75ff 1800deff 848473ff 9f9a75ff 9f9a75ff 642ea0ff 1800deff 7c7486ff 6b52adff
m2/random2 0c918290d95c89e439ae885c3a5d0cf4 47c37cff b5ce4aff 63e773ff 7edf66ff 4db86aff 52ad5aff 9ad657ff 63e773ff 4db86aff 47c37cff 84218cff 63e773ff 4db86aff 4db86aff 849442ff 844774ff
m2/random3 a46259f14bae2914e4017c8b15213959 8ce77bff 6a9ac3ff 5aa5c6ff 6a9ac3ff 8ce77bff 5aa5c6ff 6a9ac3ff 7c8fc0ff 8ce77bff 9421b5ff dc1657ff b71b87ff 8ce77bff 9421b5ff b71b87ff ff1029ff
m2/random4 cc96d940561f30d3e27d33380108d3f0 5af77bff 5af77bff dec631ff 94d6e7ff 3e56d4ff 5af77bff dec631ff ad1021ff dec631ff 498320ff a55162ff 9c95a6ff 94d6e7ff a55162ff ad1021ff 9c95a6ff
m2/random5 1c348a88068a5b91404024b13103dc65 d6a510ff 080031ff a594c6ff 716395ff a5b036ff d6a510ff a594c6ff a594c6ff 73bb5eff 42c684ff 5a3f79ff 422994ff 73bb5eff 8c6b42ff 422994ff 8c6b42ff
m2/random6 0cfde08cec68132ab633005cfbb27ab2 ae99c1ff deb56bff deb56bff 212973ff ae99c1ff 61a891ff 5f5770ff 5f5770ff ae99c1ff 18b563ff 634200ff 212973ff ae99c1ff 61a891ff bc4700ff bc4700ff
m2/random7 348927a736910dbd07073f5b6080f0ff 2110c6ff 317fbaff 97924bff 2110c6ff adbd6bff 2110c6ff 317fbaff adbd6bff 2131f7ff adbd6bff f7ce08ff 39a59cff f7ce08ff 39a59cff 6b3908ff f7ce08ff
m2/random8 84668472af60d9a1287d814a82b1dd87 9c084aff 9c084aff 917cc4ff 895520ff 9c084aff 917cc4ff 895520ff 943942ff 917cc4ff 943942ff 8f4732ff 5a424aff 943942ff 846310ff dea529ff b38534ff
m2/random9 8ceb01cae4c5369040c65c5419c91607 875d91ff 656345ff 319452ff 656345ff ad5a94ff 1b9598ff 37495fff 1b9598ff 39638cff 9a3136ff 319452ff 9a3136ff 39638cff 00deceff 00deceff 00deceff
m2/random10 8458a34052e281ea6f87b18b35f73d72 6321deff 6bf708ff 6321deff 6f1b59ff 6bf708ff 68b14eff 0052deff 0052deff 68b14eff 0052deff 6f1b59ff 94ef29ff 6f1b59ff 36379dff a57bb5ff 94ef29ff
m2/random11 c452d9af68e58785dcc039425cb784dd 3f884cff be4c71ff 62a433ff 62a433ff 29f784ff de189cff d6e78cff 9dc761ff 4a5231ff 3f884cff de189cff 9b8143ff 3f884cff 29f784ff 3f884cff 29f784ff
m2/random12 ccd283a6386d9d9c504089b5c4dfc504 4ad610ff 4ad610ff 3194c6ff 738494ff 7bb584ff 5acb36ff 3194c6ff 4194c0ff 697ea4ff 847394ff 5b8caaff 4194c0ff 5b8caaff 299cd6ff 299cd6ff 299cd6ff
m2/random13 bc9aebbd3cdc26e9eada6e4b78450830 6ea8baff 736bb5ff 6ea8baff 6ea8baff ef74dcff ef9cefff 6ea8baff 6bc6bdff 29ef29ff 44bb1eff ef9cefff 6bc6bdff 29ef29ff 29ef29ff ef21b5ff 6bc6bdff
m2/random14 3cfc0e87317bab4d7a3a9582ea48c03c efb88fff e6ba80ff 39b54aff 08ad52ff e6ba80ff f7b59cff 18b04fff 08ad52ff 634a08ff 634a08ff 29b24dff 18b04fff 63a83aff 63d652ff 18b04fff 08ad52ff
m2/random15 8cab5582376fdf9709cafbe3394f51dc b0e189ff 6b4a39ff e7948cff be7c71ff b5b594ff 3ca6d3ff 26d4e9ff 26d4e9ff adf784ff 946254ff 946254ff e7948cff b2cb8fff 10ffffff 26d4e9ff 3ca6d3ff
m2/zero 04000000000000000000000000000000 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff
m2/ones fcffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m2/part0 04aa7d7299811090b7a0141eb20ea01e ad1829ff b54242ff 8c161eff 7b424aff b54242ff b02631ff 7b424aff 7b424aff ad1829ff 5a947bff 4da168ff 832c34ff 31bd42ff 31bd42ff 5a947bff 5a947bff
m2/part1 0c7845d12e0ba54c0c4c325285ed0084 e7b500ff e7b500ff c09469ff 5a941eff c09469ff d4a533ff 8c9418ff 5a941eff b54a4aff b54a4aff 429421ff 429421ff b54a4aff 97526aff b54a4aff 74941bff
m2/part2 144e14e0e3ac121add67a7fb3ae50897 54a5eaff 8c52ceff 39cef7ff 54a5eaff ec5fbeff 717bdbff 8c52ceff 104a73ff ff18efff ec5fbeff 104a73ff 0545b6ff c6ef5aff d9a88bff 104a73ff 0b4793ff
m2/part3 1c8a91842734b2fadf415e623a475544 2c3479ff 4aff4aff e7ff8cff b3ff76ff 311884ff 294273ff 7eff60ff 7eff60ff 2e267eff 2e267eff 477b67ff 94cee7ff 2e267eff 94cee7ff 477b67ff 94cee7ff
m2/part4 240479100828397acc6bfedf382ca78b 1689ecff 2194d6ff 1084f7ff 1084f7ff 2194d6ff 1b8fe1ff 1084f7ff 2194d6ff 7eb1efff 7be7e7ff 05735bff 106318ff 7eb1efff 7eb1efff 007b7bff 05735bff
m2/part5 2c3cc15814070a792621e0b4fefff70a b14d47ff 210042ff c62173ff c62626ff 210042ff 210042ff c62173ff c62173ff 210042ff 672645ff 2931d6ff 1863d6ff b14d47ff b14d47ff 107bd6ff 107bd6ff
m2/part6 3496f3ba4d6afc85f4250fcea94e4af5 627f6bff 6b575aff 8c9a39ff 6b8439ff 73314aff 627f6bff 8c9a39ff 6b8439ff ece4a6ff ece4a6ff e1d051ff e1d051ff e1d051ff e1d051ff d6bd00ff ece4a6ff
m2/part7 3c18142c52e9a2d20a0da02bd990fb31 6e8934ff 6e8934ff 6352d6ff 108c00ff 639442ff 6e8934ff 486590ff 6352d6ff 8cd6adff a55221ff 6352d6ff 6352d6ff 8cd6adff 9d7d4fff 2b7946ff 108c00ff
m2/part8 44a05ab45e22f161095b3f57c461f6f0 8421c6ff 8421c6ff 5294b5ff 7447c0ff 8421c6ff 626ebbff 7447c0ff 626ebbff 7398d9ff 8c67baff a5399cff 7398d9ff ad635aff b8527cff bd4a8cff b25b6aff
m2/part9 4caaba039d719a3032a664d23ad725e3 8f2376ff 52394aff ad188cff 52394aff 874d42ff 874d42ff 181031ff 874d42ff 874d42ff bd6b4aff 874d42ff 4e2e39ff 3f514fff 42314aff 39945aff 3f514fff
m2/part10 5490a29ca8e6d75afc05c639237960ee 426b7bff 4dc92eff 426b7bff 479955ff d15abcff e75ae7ff bb5a8eff a55a63ff 215ae7ff 215ae7ff 52e763ff 215ae7ff 52e763ff 3188bcff 52e763ff 3188bcff
m2/part11 5c14eb19c66851e1d8b8b75d5874f587 589947ff 589947ff e43a9bff 84e773ff 589947ff 63b573ff e43a9bff 89d12bff 5da85dff 5da85dff ce29deff 8cc608ff 63b573ff 528c31ff ef427bff 87dc50ff
m2/part12 6486fa68bccd4a6ad9e03180c1b8c5fc 18de31ff ff2918ff 424a18ff 186b00ff 3f8b95ff 424a18ff ff2918ff 7bce31ff 3f8b95ff ff2918ff 803f18ff 388b10ff 3f8b95ff 424a18ff 424a18ff 388b10ff
m2/part13 6ccac82405e1901370227a2979e5e4f9 23307eff 2173bdff 34367aff 34367aff 23307eff ce42a5ff 088421ff 34367aff 1e5360ff ce42a5ff 088421ff 088421ff 29109cff 2173bdff 088421ff 34367aff
m2/part14 7470e9fc735ebd553e3a135c12c2bd86 c6e78cff 92d484ff eff731ff eff731ff 92d484ff eff731ff eacb15ff e7f74aff eacb15ff e7b508ff f78866ff f78866ff e7b508ff ff5273ff ff5273ff f78866ff
m2/part15 7c7a73304598aaeca3bb97cc86e824d4 ef84efff ef84efff 7e9c5aff 73ad7bff 4aef31ff c471c6ff 6b4a73ff 79a56bff 4aef31ff 60a86aff 965d9cff ef84efff 4aef31ff 60a86aff 60a86aff 6b4a73ff
m2/part16 845c2182ac7603dd9fc1283ba7f9a53e 736b63ff 41a279ff 41a279ff 1b3c8fff 736b63ff 29bd84ff 10a594ff 10a594ff 41a279ff 21088cff 1b3c8fff 34e9ecff 10a594ff 10a594ff 34e9ecff 21deefff
m2/part17 8c70cf2b03ee2ce657aa34fa5bcebdca d3c17eff a8bb3aff a8bb3aff ceb54aff ef7352ff d3c17eff 80c028ff 5ac618ff cee7efff ef7352ff ef7352ff 80c028ff 44cba1ff 44cba1ff c6e794ff ef7352ff
m2/part18 94109bf2282b455b626e158ccc36d5bd 4daab2ff 42b59cff 6394deff 589fc8ff 992e3aff 946b08ff 395a31ff 414251ff 992e3aff 974d20ff 4a2874ff 521094ff 974d20ff 946b08ff 414251ff 414251ff
m2/part19 9c766d67ad15bb3cf734606a14c1bbc4 de5a39ff ce6a49ff 5a39adff 5a64a2ff de5a39ff de5a39ff 5a9297ff 5abd8cff ce6a49ff ad8c6bff 5a64a2ff 5a64a2ff 49b221ff 6bef00ff 49b221ff 5bd110ff
m2/part20 a47cb089d57cc983da50e9ede44a10d1 f7ce31ff 6d5dd7ff 4a7bf7ff b52194ff a9c857ff 923fb4ff 6d5dd7ff b52194ff f7ce31ff 95bba4ff 6384b5ff 95bba4ff f7ce31ff 95bba4ff 95bba4ff 7b9fadff
m2/part21 acc09b0ba4b581a34ef47f90b5e15a15 005a10ff 7bdeefff 53b3a6ff 8626beff 005a10ff 005a10ff 7bdeefff 8626beff 189568ff 32838fff 189568ff 8626beff 189568ff 189568ff 189568ff 9c00ffff
m2/part22 b4c43f004321a36b5be3a87e499cf176 5e3bd1ff 1010d6ff 5e3bd1ff 1010d6ff ff94c6ff 5e3bd1ff 398c8cff 007352ff 1010d6ff 137b65ff 84de29ff b091b9ff ff94c6ff 137b65ff 84de29ff c66bffff
m2/part23 bc74c29799fa3dbb3a3b2f84bf9d97b8 a8c8b0ff 4aff73ff 78e491ff a8c8b0ff bd6310ff c3c6abff 78e491ff 4aff73ff 53c55cff 41ceabff c6f7f7ff 78e491ff 63bd10ff 41ceabff bd6310ff 78e491ff
m2/part24 c41010d576665ca717e8512b7849196f 2c5346ff adefadff c8ad74ff c8ad74ff 426300ff 449c49ff b5a5adff c8ad74ff 2c5346ff 164190ff 449c49ff 107318ff 0031d6ff 0031d6ff 164190ff 2c5346ff
m2/part25 cc60c362192ac86f929e4baf36d74f8e 84a5a5ff 6b1039ff c621bdff 3194d6ff 7c7482ff 7c7482ff 10ffa5ff 3194d6ff 8a6ab5ff 8a6ab5ff 3e87ceff 5a6bbdff 3194d6ff 4d78c5ff 5a6bbdff 4d78c5ff
m2/part26 d4e8fff607b627553b766353c95f4fea c38bacff ff9c31ff b5a5b5ff ffdeefff b5a5b5ff ae803fff ae803fff cda28aff e79f5cff 08de29ff ff524aff e79f5cff e1b6cfff cda28aff cda28aff ffdeefff
m2/part27 dc04503f5ea1fa518e99b2205b2c5201 0b2653ff 0b2653ff 0b2653ff 101063ff 005231ff c6754aff 52ef29ff 101063ff 8bb339ff ad686eff 8c5284ff 8bb339ff 8bb339ff 8c5284ff 8c5284ff 52ef29ff
m2/part28 e4c4584eb931d335493e55fdf09e381a 101894ff 189c7bff 734a18ff 684261ff 73bdadff 627070ff 157183ff 5231f7ff 5a4a52ff 73bdadff 13438cff 5231f7ff 13438cff 189c7bff 5231f7ff 5231f7ff
m2/part29 ec923f3987e45da9cbe3a747798fa9d8 8383e7ff ce29d6ff 6a5b99ff f7f7c6ff f7f7c6ff 39737bff 39737bff f7f7c6ff cead18ff 8383e7ff 8383e7ff 8d921eff cead18ff 085a29ff 497523ff 8d921eff
m2/part30 f4cea7b29492f3f78bcd191020c9b389 392963ff be9889ff a5ce9cff 9fde6bff be9889ff a5ce9cff 295a00ff 295a00ff 392963ff 94ff08ff 29f742ff 295a00ff 392963ff 7a5f76ff a5ce9cff 9fde6bff
m2/part31 fc3e7f9a7437a51d6c25955ca6db91ae ff735aff ef8f4fff ef8f4fff e79c4aff ab4ab0ff f78055ff e79c4aff f78055ff 211873ff ab4ab0ff 7b9452ff 999f4fff ef63ceff 653191ff 653191ff 999f4fff
m2/part32 04b39bbb37764a8d4cc3f962af233626 b055bbff 91479fff 91479fff 733984ff ce63d6ff 91479fff ce63d6ff 9670cfff b25491ff c88286ff c47facff ef8c8cff dead7bff ef8c8cff c47facff ef8c8cff
m2/part33 0cdf7fb0fbf17fa731c800a15fed95c4 a66436ff f29daaff f29daaff f29daaff d4b366ff a66436ff f78cf7ff f78cf7ff d4b366ff d4b366ff 7bff08ff f29daaff d4b366ff 7b1808ff 81f45bff 7efa31ff
m2/part34 148d1850f2c7d6d771afc445f4fdbd66 317bdeff 10635aff 84ffe7ff 3b907eff 1b6b85ff 10635aff 84ffe7ff e78c8cff 1b6b85ff 10635aff afbe39ff afbe39ff 10635aff 94d610ff e78c8cff 94d610ff
m2/part35 1c0baeeaaa5c4901e68dd7bb66154eba 29ce7bff 7026c9ff 9a10e7ff 5dc35bff 5dc35bff 8f24a1ff bd00efff 29ce7bff c6ad18ff 8f24a1ff bd00efff 5dc35bff 92b838ff 7026c9ff 5231d6ff 92b838ff
m2/part36 243917484e609c8e542bec8d738fbe9b e700d6ff e73152ff e710abff e73152ff 42d6f7ff 1073c6ff 1073c6ff 2093d6ff 9ca573ff 9ca573ff 979447ff 999d5dff e73152ff e7217dff e710abff e7217dff
m2/part37 2c7731b6c69e79ee7544326f57ac0b10 deef18ff 5cdf49ff a2d9cdff deef18ff b5ce9cff 97c3dfff 64d966ff b5ce9cff adefbdff a3e43eff 31e721ff adefbdff deef18ff 31e721ff a2d9cdff deef18ff
m2/part38 3479de3fe544e6ae42f8a19310f770ec e74a10ff e9b256ff 4aad4aff ce21f7ff 757937ff ce21f7ff ffded6ff 4aad4aff de9c18ff 4aad4aff ce21f7ff e9b256ff e74a10ff ffded6ff a34423ff ce21f7ff
m2/part39 3c21167e0bd1b2f495b5f16c0d3e3f7a 9a2e66ff 841063ff 10ce18ff aba75bff 10adadff 10adadff 841063ff c66b6bff f7947bff f7947bff def7b5ff def7b5ff 9a2e66ff c66b6bff f7947bff 10ce18ff
m2/part40 442bcd305464cda49a0f3cde322c0ae8 ad42e7ff a5b518ff ce31c6ff ce31c6ff 849c18ff 9c7951ff 08a57bff 08a57bff 3eb570ff 3eb570ff ad42e7ff ad42e7ff ad42e7ff aa68a3ff 849c18ff b6548dff
m2/part41 4c9b38487288c07ba5f83a2c60a794f4 6b8429ff 3f5349ff 4d6e6dff 3c287cff 1042f7ff 3900adff 4d6e6dff 3c287cff cc443bff cc443bff 947bb5ff af607aff cc443bff cc443bff e72900ff af607aff
m2/part42 54a1a330bf328a0e01bfd74fbe2a54a9 7e23adff 73187bff 791e94ff 791e94ff 791e94ff 791e94ff 8429c6ff 8429c6ff b3086aff 8f9dc9ff 96089dff 8f9dc9ff ce0839ff 9a62a1ff b3086aff 9a62a1ff
m2/part43 5c4b1e430f0e96e25cbf8765ea2d22ba 5f9bb8ff 984c99ff 18e74aff 98e77cff 1852c6ff 185a7bff 98e77cff d6e794ff 5f9bb8ff 29e7d6ff 98e77cff d6e794ff 185794ff 1852c6ff 98e77cff 98e77cff
m2/part44 6427d093bdaaf9f390d7d73809f98548 69bad4ff 9cade7ff 63f7e7ff 6bd1a6ff 9cade7ff 00d6adff 9c7b6bff 9c7b6bff 33c9c0ff 9cade7ff 63f7e7ff 6bd1a6ff 9cade7ff 69bad4ff af9e70ff d6e77bff
m2/part45 6c055c4965aa5bc425df15e9320697c3 10a5ceff ce295aff 52c6a5ff 5ec6c3ff 55766aff 52c6a5ff 52c6a5ff 4f817cff 84d6bdff a55d73ff 52c6a5ff 84d6bdff 55766aff 52c6a5ff a55d73ff 55766aff
m2/part46 74e3b763d8dadfbcc3d91b8938b8a2a0 b2c389ff 189c8cff 8cad73ff b57bbdff 814e16ff b51810ff 18bd21ff 4c871bff 4c871bff 18bd21ff 4c871bff 4c871bff 8cad73ff b57bbdff b2c389ff 8186adff
m2/part47 7cbb495360ff0b2df2076ae461e0d38f eff7ffff 6ffc59ff b1faaeff eff7ffff 102994ff 817c57ff c69439ff 9ca531ff 102994ff 817c57ff 8a7157ff 9ca531ff c69439ff 65527fff 102994ff 65527fff
m2/part48 847d9af504b038c36c5e9654c265c380 f7009cff 9ce763ff 4a5abdff a2bc5bff 833cb2ff 9ce763ff 4a5abdff a78e52ff be1ea7ff 9ce763ff 833cb2ff a2bc5bff 39c652ff 39c652ff 39c652ff 29a64fff
m2/part49 8ca7788099c05d09a572ea8d38eaaa54 6e51c0ff 312910ff 630831ff 630831ff 6e51c0ff 535bc0ff 0029f7ff 535bc0ff 6e51c0ff 531326ff 531326ff 531326ff 3e9ed4ff 2841dcff 2841dcff 7b73a5ff
m2/part50 94b57a6703aeb75aefe4b2747e40b942 abe16aff 52d6ceff abe16aff de5ad6ff 7bde29ff 7bde29ff 4f804aff 4970d1ff d6e739ff 52d6ceff abe16aff 9565d3ff 65b039ff 7bde29ff 4f804aff de5ad6ff
m2/part51 9c59b1e9b52c9c182811c2eea26146ca 63ce4aff 3c4e2eff 3c4e2eff 50903dff 7b18bdff b57321ff 4a1063ff 7b18bdff 6b425aff b57321ff 6d304dff 7b18bdff 76269dff 925337ff 6d304dff 76269dff
m2/part52 a46b70b2a7b7aa9c2197edcf36f6906d ad7bceff 4a08deff ef9c39ff 8039a8ff 777098ff 7ea5e6ff 9494f7ff 7ea5e6ff ad7bceff 899cefff 73addeff 9494f7ff 3e655fff b96b6fff 4a08deff ef9c39ff
m2/part53 ac4717ee9b7a4a0fdac2cdbb426ff359 18adb5ff 18adb5ff 5f87a5ff 31d652ff 73efe7ff 53aee4ff 306ae1ff 31d652ff 1029deff 53aee4ff 73efe7ff 31d652ff 18adb5ff ef3984ff a85f94ff ff08efff
m2/part54 b4f9b24b3ba415d2e06b4ab115f8c0cf e742ffff 974da5ff b552a5ff e742ffff 88a5e3ff 974da5ff 5a42a5ff b973f2ff e742ffff b552a5ff 7847a5ff 5ad6d6ff 7300b5ff b690c0ff 9346bbff b690c0ff
m2/part55 bc6b1319394c34a1b5c69e7570c6d4cd adc6adff 6b218cff 9790a2ff 815797ff 9790a2ff adc6adff 6b218cff adc6adff 52a892ff 4e9be4ff 4e9be4ff 73ad08ff 63aa4cff 4e9be4ff 905cd9ff 52a892ff
m2/part56 c43503d9f5c349c884671e2b851ca048 d639e7ff 0021e7ff 8a10aaff d639e7ff 63e7ceff 4419c9ff 0021e7ff d639e7ff 73ceadff 73ceadff 9c95aaff 9c95aaff 73ceadff 9c95aaff c65aa8ff 73ceadff
m2/part57 ccf5aee2cc2a73ef5c2427127a5ce3fd d9a523ff de944aff 59ec47ff 39ef4aff de944aff d9a523ff 79d953ff 10ef10ff d6ad10ff db9c37ff 79d953ff 10ef10ff db9c37ff de944aff 9ce742ff 59ec47ff
m2/part58 d477d64d8a0c872800c65688f7d4d4e0 dece84ff ce848cff 1000f7ff 942921ff b31555ff b31555ff 1000f7ff 942921ff b31555ff 8e133fff 3b0db1ff 691c67ff dece84ff dece84ff 1000f7ff 691c67ff
m2/part59 dc63d67807b39460fa021263d4747d57 8c31bdff a23e7fff ce5a00ff 8c31bdff a23e7fff ce5a00ff a23e7fff a23e7fff ce5a00ff ce5a00ff a23e7fff ce5a00ff 98898cff d13c44ff cb2669ff de638cff
m2/part60 e4d3d21a0228331cfa1744eba1ada548 4a84ffff 558f6fff 558f6fff 595687ff 558f6fff 4f89b9ff 4f89b9ff d684a5ff 558f6fff 4a84ffff 4f89b9ff 595687ff 4a84ffff 4f89b9ff 558f6fff d6ce42ff
m2/part61 eccdcc99312aa294622b1fc142febb2e 31a5deff 639400ff 63691eff 633b3cff ce948cff 63105aff 63105aff 63105aff 794180ff 63105aff 633b3cff 633b3cff ce8fd4ff 63691eff 63691eff 639400ff
m2/part62 f46b2a4874839dd8d688bdfb2989e9f3 8d6226ff 3a30deff ad3131ff 3153deff 10deefff 59d1b3ff 10deefff efb539ff 10deefff 59d1b3ff efb539ff efb539ff 59d1b3ff a6c275ff efb539ff 59d1b3ff
m2/part63 fc4561cdf56cd9a54eede2d2e3414b99 10ce52ff 689f5bff 6bbd73ff 668141ff 73a54aff 10ce52ff 689f5bff 689f5bff 9c955aff c6836bff 10ce52ff 668141ff 9c955aff c6836bff 9c955aff 21bdb0ff
m3/random0 887cf917c50567b2b837009f48dc8702 be2edcff d144a6ff e65b6dff be2edcff e65b6dff f97137ff e65b6dff f97137ff f97137ff be2edcff be2edcff 254229ff d144a6ff be2edcff 2e4c00ff 2e4c00ff
m3/random1 e84e9027036c3f54530dc342757f3d95 499275ff 22bb33ff 0cd40aff 6ec540ff 90f60cff 0cd40aff 0cd40aff 6ec540ff 22bb33ff 90f60cff 499275ff 22bb33ff 22bb33ff 6ec540ff 2761a9ff 39a05eff
m3/random2 98574908759f23ae5d9da32a5bb08a26 aafaaeff d56babff 95898aff aafaaeff aafaaeff 6878a2ff 51a768ff 51a768ff 8abaa8ff 8abaa8ff 11c547ff 51a768ff d56babff aafaaeff 8abaa8ff 11c547ff
m3/random3 b8df9acb23dd55128923c950c3c9b8c2 6fe9c5ff 6fe9c5ff 8c8a57ff 8f4543ff 974b93ff 7dbb90ff 8c8a57ff 7dbb90ff 974b93ff 8f4543ff 944979ff 7dbb90ff 7dbb90ff 974b93ff 92475dff 944979ff
m3/random4 0881eb7fbb6fd65ce18b4bf2e4b41996 cf76d0ff c17df1ff eb678bff cf76d0ff f26cb8ff dd6eacff cf76d0ff eb678bff fe9a96ff ec56c8ff fe9a96ff c17df1ff ec56c8ff f26cb8ff fe9a96ff f884a6ff
m3/random5 c87e13f01adcdec681dd958ee348c256 bee0c0ff e1db2bff bab830ff 13edddff e1db2bff 4be9d3ff bee0c0ff bab830ff 929436ff bee0c0ff bee0c0ff 6b713bff 4be9d3ff bab830ff bab830ff 86e4caff
m3/random6 28e6a3a3a936d2f3d209071c6c797d7b d8849fff 66902eff a22208ff 87a650ff 467a0eff a22208ff 66902eff d8849fff d8849fff a6bc70ff a22208ff 66902eff a6bc70ff bc5252ff a6bc70ff d8849fff
m3/random7 a851ef25400792cd144a54e230fa6917 a93b0bff 185c93ff 32889eff a93b0bff d82a36ff 185c93ff 003288ff ef214bff c03220ff 185c93ff 185c93ff c03220ff ef214bff 32889eff 32889eff a93b0bff
m3/random8 f874db8e9c3bf21539f6c08ce156be0e badc1cff badc1cff db23f7ff c59f64ff db23f7ff d060afff d060afff badc1cff db23f7ff db23f7ff c59f64ff c59f64ff 724432ff 399767ff 1dbf81ff 1dbf81ff
m3/random9 e8f5d0352394ad6e0d8e2a06f927dee9 7aa006ff 8c5a18ff 76ad41ff 8c5a18ff d0d88eff 96b233ff b4c661ff 6bd555ff 81822cff d0d88eff 96b233ff d0d88eff 76ad41ff 81822cff 81822cff d0d88eff
m3/random10 a84a458429d33d831f320991b283778c a4980eff 64c627ff 3c8e23ff 73b934ff 45dd33ff a4980eff 086612ff 64c627ff 45dd33ff 3c8e23ff 45dd33ff 85af1aff 086612ff a7e145ff a4980eff 64c627ff
m3/random11 782f9b17ae028b273ead9260bfd8cb60 9848a3ff 9ab0acff 5ccf44ff 8cab64ff 2ff125ff 997da8ff 9848a3ff b98983ff b98983ff 8cab64ff 97159fff 9ab0acff 97159fff 2ff125ff 8cab64ff 9848a3ff
m3/random12 98643eef02e879ebc157646fda0d4b52 3341e1ff 3e9e56ff 5077c1ff 0b7bbdff 3a7f84ff 9972c4ff de6ec8ff 5077c1ff 9972c4ff 9972c4ff 5077c1ff de6ec8ff 9972c4ff 5077c1ff 5077c1ff de6ec8ff
m3/random13 28d2d940250534604341b534eb743901 e828a0ff 884c8dff d84040ff 884c8dff 8e94b1ff dd3860ff 884c8dff e33081ff e33081ff 8e94b1ff d84040ff 81076bff 884c8dff e828a0ff 81076bff e828a0ff
m3/random14 38089362a01be0a359a68b678fc89793 899455ff 899455ff 85dd2dff af7644ff 85dd2dff 899455ff 977072ff 81699fff 9200a6ff 8e497eff c57d17ff 81699fff 899455ff 977072ff c57d17ff af7644ff
m3/random15 d83a512d8e280ea8fda2ce6c010c5781 9d457fff 9d457fff 5b019dff 5b019dff 4348abff 5023a4ff 9d457fff 69ae97ff 386ab2ff 4348abff 69ae97ff 69ae97ff 9d457fff 9d457fff 5b019dff 5023a4ff
m3/zero 08000000000000000000000000000000 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff 000000ff
m3/ones f8ffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m3/part0 08b8d1ee63f8014c35b20a91c908496e dcc21aff d88d4cff a86135ff c37224ff dcc21aff d88d4cff dd8115ff a86135ff dcc21aff d88d4cff a86135ff dd8115ff d11fb3ff d88d4cff 8e5244ff dd8115ff
m3/part1 18c846b9398c7c6a8ea03b0127122f26 5a8264ff 646046ff 5a8264ff 734f77ff 5a8264ff 50a682ff 646046ff c1822aff 46c8a0ff 5a8264ff 5a8264ff 734f77ff 46c8a0ff 646046ff 5a8264ff 734f77ff
m3/part2 28ece0cb62655a0bb4399e3b279d8be7 9953a5ff 976b3dff 934977ff 8f25b5ff bd7d6dff 8b03efff 976b3dff 8b03efff 9953a5ff 934977ff 976b3dff 8b03efff e0a638ff 976b3dff 8b03efff 934977ff
m3/part3 38c86d2d68fd8b0fe73a8d59a543ee45 bddc60ff e5eb73ff bddc60ff a0c266ff bddc60ff e5eb73ff 89d14dff 5bf11bff 6cbe3aff bddc60ff a0c266ff a0c266ff 94cd4dff 5bf11bff 89d14dff 5bf11bff
m3/part4 481c601de1e5764e8305f7c11152ca9e 0f2fc1ff 465a43ff 0f2fc1ff 0f2fc1ff 2a4483ff 465a43ff 465a43ff 3bcfefff 2a4483ff 2a4483ff 465a43ff 53d0a3ff 616f05ff 616f05ff 3bcfefff 53d0a3ff
m3/part5 5848d51427c35b7db55549e71432d072 b54fafff c58781ff 28aa92ff 28aa92ff b54fafff 767799ff 4e9195ff 28aa92ff a519dbff 767799ff 767799ff 4e9195ff 4e9195ff 767799ff 9c5e9cff 28aa92ff
m3/part6 6850513276d5f0cd7622352f6ef9579f 8b7632ff 8b7632ff 500c22ff b3b7a2ff a8aa3aff 500c22ff d9b3bdff d9b3bdff 500c22ff b3b7a2ff b3b7a2ff b3b7a2ff d9b3bdff d9b3bdff 64be6aff 8aba85ff
m3/part7 78c4a068f096a925b96ae65bd5c8d2ec 77ad61ff 8ca266ff 8ca266ff 77ad61ff 63b75dff 77ad61ff 8ca266ff cb91aeff 77ad61ff 8ca266ff c66c8dff cb91aeff 8ca266ff cb91aeff c0486eff cb91aeff
m3/part8 884023852d2a5af955b9ac6d0c5d0d28 776cafff 776cafff a151abff 4c87b4ff 4c87b4ff 22a2b8ff 4c87b4ff 4c87b4ff 4c87b4ff 776cafff a151abff 0a2a58ff a151abff 776cafff 424677ff 0a2a58ff
m3/part9 98d8ea03fc8ccdb791cbef44e5213f7a 968cc9ff 6d67c9ff f06c12ff f06c12ff 6d67c9ff 07f9dfff 53cb9cff a49a55ff f06c12ff f06c12ff 53cb9cff 07f9dfff 53cb9cff f06c12ff f06c12ff 07f9dfff
m3/part10 a860ec058cac42997d7249c1f13a2b89 31653fff af3e62ff ed2b73ff 6f5250ff 6f5250ff ed2b73ff 6f5250ff 245233ff 6f5250ff 173d64ff 173d64ff 245233ff 0b2993ff 173d64ff 0b2993ff 173d64ff
m3/part11 b84ce810785d425c5ade6a87cc90f5d8 66a967ff 66a967ff a966a4ff 66a967ff 26ea2cff a966a4ff 26ea2cff e925dfff a966a4ff a966a4ff e925dfff 5f8d98ff 26ea2cff e0961cff a19158ff 5f8d98ff
m3/part12 c8482aa4c23559dd39e6cf6525072daa 27a55fff 25af1dff 27a55fff 1f8799ff 2a92e6ff 49ab9fff 49ab9fff 1f8799ff 1f8799ff 349a9cff 349a9cff 49ab9fff 349a9cff 349a9cff 349a9cff 349a9cff
m3/part13 d898ec28b87220b5b225aa8de7295171 81669dff 4c94d8ff ed0725ff ed0725ff 4c94d8ff 81669dff 81669dff b83560ff 51a555ff b2aa41ff b2aa41ff b2aa41ff 51a555ff b2aa41ff e1ad37ff 51a555ff
m3/part14 e81c4873590121067dd9d941f9338f90 0f0bbfff 4810d8ff 4810d8ff 4810d8ff bc997aff 8f6c3fff bc997aff 8f6c3fff 644006ff bc997aff e7c5b3ff bc997aff e7c5b3ff 8f6c3fff e7c5b3ff bc997aff
m3/part15 f824553dfe556fec1967ab3bc23a05cd 92ae8cff 92ae8cff 68dd72ff 7ec580ff 7ec580ff 54f466ff 7ec580ff 68dd72ff 68dd72ff 92ae8cff 92ae8cff 68dd72ff cf81bdff a48688ff cf81bdff a48688ff
m3/part16 08b968951826ec93d0a6d2d3da091b82 5d3169ff 69c3a7ff 659393ff 69c3a7ff 2a7ca4ff 61617dff 5d3169ff 659393ff 3d5f88ff 63254fff 2a7ca4ff 5d3169ff 3d5f88ff 2a7ca4ff 2a7ca4ff 3d5f88ff
m3/part17 181d37e1abce5b5a868dfbc7bd3eb7ac 728db1ff ae961eff bc64b0ff b57d65ff 54a59fff 37bd8dff 37bd8dff c34bf7ff 37bd8dff 728db1ff 37bd8dff 54a59fff 8f75c3ff 37bd8dff 54a59fff 54a59fff
m3/part18 28e10cec84812c1b4401cf566a32906c 710da3ff 504a6eff 0cc800ff 710da3ff 504a6eff 2d8b35ff 504a6eff 710da3ff d8649eff 710da3ff 504a6eff 2d8b35ff d8649eff 13075bff 542671ff 504a6eff
m3/part19 3845280fd3801b2a5b57a1341829799d 2206acff 4ccad2ff 1e4242ff 1e4242ff 244090ff 267e72ff 3d9da3ff 1e4242ff 244090ff 267e72ff 28b856ff 2d6f71ff 244090ff 28b856ff 244090ff 267e72ff
m3/part20 48e5c6fcb513cef4c3e75ddc773364f2 8fb3e3ff abcbe5ff eebaa3ff eebaa3ff c7e1e7ff 739de1ff c7e1e7ff f999bbff 739de1ff 8fb3e3ff abcbe5ff 8fb3e3ff abcbe5ff 739de1ff c7e1e7ff c7e1e7ff
m3/part21 5869a6c374b656fd478dc15ba95cdf1c 35b3a3ff 5a9b9bff 5a9b9bff 5a9b9bff b9e375ff a66a8cff 818294ff 818294ff a0c67cff d2fe6eff 5a9b9bff a66a8cff 87ab83ff d2fe6eff a0c67cff 35b3a3ff
m3/part22 6845b345a09f14e8b899fce3337efaf3 a3fdddff ae84afff a8c2c7ff a3fdddff b34999ff b34999ff b34999ff a3fdddff 8815d6ff ae84afff b34999ff b34999ff 813b8fff 8b03f9ff b34999ff b34999ff
m3/part23 789131a6dd4f6927634e07eb63c5f750 c97f31ff 4ded0fff 77c9adff 69d579ff 638e45ff c97f31ff 69d579ff 77c9adff 31954fff 638e45ff 77c9adff 5be143ff c97f31ff 638e45ff 638e45ff 4ded0fff
m3/part24 88497f3d521d964603448e94b9c97789 a4ea00ff 7f6145ff 6ad22eff 59d141ff 98bd17ff 8b8e2eff a4ea00ff 48d052ff 7f6145ff 98bd17ff 7f6145ff 6ad22eff 98bd17ff 8b8e2eff a4ea00ff 8b8e2eff
m3/part25 9821c6fba84ffbb83c7411130c9bbdec 4c8e3aff 4c8e3aff 107c1eff 8aa258ff da2330ff c6b474ff 107c1eff c6b474ff f61e22ff c6b474ff c6b474ff 8aa258ff f61e22ff a22e4cff 8aa258ff c6b474ff
m3/part26 a879ab5042923267da79fd09b0704c5b bc92ecff 3ab26cff 6eccb4ff b04b9eff bc92ecff a0e6faff 089826ff b66fc6ff bc92ecff 089826ff a0e6faff b66fc6ff aa2878ff 3ab26cff 6eccb4ff b66fc6ff
m3/part27 b88903bcd320287f578679304ceadf07 842f48ff 842f48ff 78e4f2ff 6ae2e2ff 425968ff 5ce0d0ff 5ce0d0ff 028286ff 028286ff 4edec0ff 6ae2e2ff 028286ff 4edec0ff 6ae2e2ff c4062aff c4062aff
m3/part28 c8893f84f4a19b8ff8f38670bb2780a5 c50ffdff 3ebaf2ff 9947f9ff d323c3ff 3ebaf2ff 09f30dff 4baf49ff 09f30dff 09f30dff 09f30dff 09f30dff 6a82f6ff 4baf49ff 9947f9ff 6a82f6ff 6a82f6ff
m3/part29 d87121e144cb95a0a891ed7ed6dccc4b 875bbeff 525ca7ff 525ca7ff 875bbeff 4c21f0ff 1329fbff 4c21f0ff 891ae5ff c212daff 1329fbff c212daff 1329fbff 205c90ff 525ca7ff b95bd5ff 875bbeff
m3/part30 e8397a18cf000a63799682e2f3ad42e9 1d073dff 395c5fff 355e31ff 3d598bff 3c3a5bff 7ba197ff 5c6e79ff 395c5fff 395c5fff 1d073dff 1d073dff 3c3a5bff 355e31ff 395c5fff 395c5fff 7ba197ff
m3/part31 f8dd27be7fe47924c4d6ac6194742056 ad4b89ff 6876b0ff 7c8e58ff d33477ff 7c8e58ff ad4b89ff 269ed6ff a76267ff 7c8e58ff ef2363ff 6876b0ff 7c8e58ff d33477ff a76267ff ad4b89ff ad4b89ff
m3/part32 08265b5e4f9c31cb227ea70b0d2055d0 80a034ff 938044ff 92e210ff bd674fff 92e210ff bd674fff 80a034ff 669939ff 6c5a5aff 669939ff 6c5a5aff bd674fff 92e210ff 669939ff 6c5a5aff 938044ff
m3/part33 18aed393b7eb308a27c2e1819204cb6a d65c12ff d42889ff d65c12ff d5434cff a2af44ff 2646c2ff 2646c2ff a2af44ff d5434cff d5434cff d42889ff d5434cff 637a85ff 637a85ff dfe307ff 2646c2ff
m3/part34 2836d9243949202b082c7b9f34543f29 af3211ff b128a4ff af3211ff 4864f6ff b128a4ff c41b20ff 4864f6ff af3211ff d9052dff e40a7cff d9052dff 4864f6ff 7b46ceff c41b20ff b128a4ff 9a4804ff
m3/part35 382e3de882f7d8b6badb19253656bceb 78addbff 5a9ddbff 8fcb52ff d0da32ff 3c8edaff 5a9ddbff 4cbc75ff d0da32ff d0da32ff 0bad95ff 3c8edaff 5a9ddbff 0bad95ff 4cbc75ff 5a9ddbff 3c8edaff
m3/part36 486e72642fa4de2ea428b9edbb41d95f 372153ff 73eb29ff c59789ff c14fa1ff c59789ff c9db73ff 372153ff 4b6345ff 4b6345ff 5fa937ff c59789ff bd0bb7ff bd0bb7ff bd0bb7ff 4b6345ff 4b6345ff
m3/part37 5836f284038df955befdd6b5ff6de51d 6178e8ff 0f95d7ff f399fdff 0f95d7ff ac89f3ff 0bb1bbff f399fdff 0da3c9ff 09bfadff 6178e8ff 0da3c9ff f399fdff 0bb1bbff f399fdff 0bb1bbff 1a68deff
m3/part38 68eec01df65b988bb9c8b7228d0b240f 8ec07fff 6f6d78ff 3b736fff c084c8ff 6f6d78ff 8ec07fff 76de5cff 3b736fff a8a2a5ff 3b736fff 6f6d78ff a8a2a5ff d8628aff 8ec07fff 76de5cff 3b736fff
m3/part39 784a67556f3a2b95e48728baf304a915 a4d2f2ff b74fb7ff 67b387ff b17b83ff b74fb7ff a4d2f2ff aba551ff 7bbdaaff aba551ff 90c8cfff b17b83ff 67b387ff 7bbdaaff b74fb7ff a4d2f2ff aba551ff
m3/part40 885270c706596db8e41e05c25808a0a0 29c973ff 1a2e08ff 8e0c0aff 681709ff 29c973ff 59d13bff 8e0c0aff 8e0c0aff 8e0c0aff 8e0c0aff 59d13bff 59d13bff 8e0c0aff 8e0c0aff 402309ff 59d13bff
m3/part41 9886c49f8bff8c748b796770bd3e76bd 6deeacff c4ce78ff 6deeacff 39aacaff c4ce78ff c4ce78ff 39aacaff 3f91cfff 39aacaff 39aacaff c4ce78ff 6deeacff 39aacaff c4ce78ff c4ce78ff 9add91ff
m3/part42 a84293f0a1145a1fb9778e646710ce1c 9ca3bbff a1a5ddff c3b544ff c3b544ff a1a5ddff a1a5ddff c3b544ff a1a5ddff 97a298ff 874793ff a1a5ddff 92a076ff e1eb1dff 874793ff 9ca3bbff a1a5ddff
m3/part43 b83628d0402eff097c8d492d3851aa18 1a72beff 28f28cff 6c2a9dff a03e92ff 6c2a9dff 1a72beff 6c2a9dff 6c2a9dff 3616a9ff 3616a9ff 23c89cff 3616a9ff a03e92ff 3616a9ff 1f9caeff 1a72beff
m3/part44 c8ee9f41d9dbd09ada53a41dfdbcdac4 d999b9ff 64a676ff 797458ff 9e0c52ff 835b49ff 9e0c52ff 9e0c52ff 6e8d67ff 6e8d67ff bb5185ff d999b9ff 64a676ff f6deecff 797458ff 835b49ff 9e0c52ff
m3/part45 d87ae770102f20d1001ffd3ab2969f77 bc7880ff d8293eff ac2af5ff ac2af5ff 4135ebff 752ff0ff bc7880ff e6021eff 4135ebff 4135ebff bc7880ff e6021eff e6021eff d8293eff 4135ebff e024faff
m3/part46 e85a9c2d182d4a919e2260b31a49bee8 2c684eff 61a5cdff 5a28c0ff 789031ff 2c684eff 5c51c4ff 5f7cc9ff 2c684eff 61a5cdff 9da323ff 517b40ff 5c51c4ff 5a28c0ff 517b40ff 9da323ff 5c51c4ff
m3/part47 f86a3effbc4236055d61f9bc1d856c03 382f95ff 3f6561ff 3414aeff 3b4a7aff 3b4a7aff ffa7f3ff ffa7f3ff 3b4a7aff 3414aeff f240f2ff f662f2ff 382f95ff 3f6561ff 3414aeff 3414aeff 3414aeff
m3/part48 083b41ed401687b1c96cd79218b8faf7 9cb264ff 026c4aff 9cb264ff 9cb264ff da30aeff 026c4aff 93448dff 5f866aff 5f866aff 49586bff 41716dff 41716dff 41716dff 7e9d67ff 41716dff 41716dff
m3/part49 184f95ccc4d60049580d64bbfb00a94f a6b6acff 950d0dff 6d1cd5ff 950d0dff a6b6acff 9921c9ff 9921c9ff 9921c9ff a07f78ff 9b4441ff 3f18e1ff 9b4441ff 950d0dff 950d0dff a6b6acff a07f78ff
m3/part50 280fe51707910f36477be17c4d06f3c5 a6ad96ff a6ad96ff c5d487ff 8789a3ff e4f87aff 8789a3ff 2fc1c3ff 8789a3ff e4f87aff 2fc1c3ff 1cccf2ff 1cccf2ff a6ad96ff a6ad96ff 2fc1c3ff e4f87aff
m3/part51 380771a60235b31a6b0a070c4f8e0d2b 7c8126ff 7c8126ff 765918ff 82a834ff 70320aff 377c1aff 82a834ff 70320aff 4d570fff 0bc731ff 4d570fff 82a834ff 70320aff 21a226ff 765918ff 82a834ff
m3/part52 48f3b4eb2dd82ec34daa52997ccead59 8ccf52ff b67064ff b67064ff 78c026ff b67064ff cc688fff a1de7fff b5edabff c16c79ff 8ccf52ff 8ccf52ff b67064ff 78c026ff b5edabff c16c79ff d664a4ff
m3/part53 58db5ffa3f206971e6b3b7a77ccb2839 be30ddff 5f93b3ff fe9c9eff fb778eff be30ddff f7517eff fb778eff be30ddff f42c6eff f7517eff be30ddff 8d63c8ff f42c6eff 5f93b3ff be30ddff f42c6eff
m3/part54 684f29012db38ab59c7ae6f49db42eac 7e9f5dff b42cd2ff 03b1cdff 52a56dff a7994fff 7e9f5dff b42cd2ff 7a58d0ff 7a58d0ff 29ab7bff 52a56dff 03b1cdff 03b1cdff b42cd2ff 52a56dff 52a56dff
m3/part55 78dfb7400ffd99933b3c9a9e17a5129b dcd027ff c9b732ff 817335ff 817335ff 6b984cff dcd027ff c9b732ff 53c064ff 53c064ff 817335ff dcd027ff eee81cff b79f3dff 53c064ff 6b984cff c9b732ff
m3/part56 881bd0acf21939bd4d0908f21087887e 0dcfa7ff a5808cff 58a610ff 91a53dff ca6ec8ff 58a610ff 0dcfa7ff 4dbb73ff 58a610ff 7d944cff 0dcfa7ff 4dbb73ff ca6ec8ff d19109ff d19109ff 58a610ff
m3/part57 981f578dfd11b36b4f9437450d5c3d40 7c704bff 639751ff 1b776fff 8f8f27ff 694f70ff 563094ff aeba32ff aeba32ff 694f70ff 563094ff 639751ff 1b776fff 1b776fff 8f8f27ff 694f70ff 1b776fff
m3/part58 a8f3836429dadc0aaafb123261586443 f8d0d4ff c95b25ff a482c8ff c95b25ff c95b25ff a482c8ff b07593ff f8d0d4ff b07593ff f8d0d4ff 82ccfaff a9cdeeff d1cfe0ff f8d0d4ff a9cdeeff c95b25ff
m3/part59 b87708cfedd983d6e5350988e02eb72c 3acef2ff 3acef2ff 093d35ff a6b217ff b67420ff 2a9eb4ff 2a9eb4ff 196d73ff b67420ff ae921bff a6b217ff 2a9eb4ff 196d73ff a6b217ff a6b217ff 9ed012ff
m3/part60 c8c39ff31f0a78806452cb456b5d5434 e15133ff cb603dff 9e8052ff b47148ff a11b41ff 7f2117ff a11b41ff e70f97ff b47148ff b47148ff a11b41ff e70f97ff b47148ff b47148ff c5156dff e70f97ff
m3/part61 d8bb1123a9243c87831c63dff97175b5 dd2541ff 11c31dff 66e5aeff a4e07cff 9a5935ff dd2541ff a4e07cff 66e5aeff 66e5aeff 66e5aeff a4e07cff 66e5aeff 9a5935ff 9a5935ff 11c31dff 548f29ff
m3/part62 e80b6becf66c73e3a4cc45ac8d03446d 7c577aff 7c577aff d96f8bff 7346a5ff 6b37cdff 846652ff d96f8bff 846652ff d96f8bff d95d97ff d96f8bff 7c577aff d95d97ff da38b0ff da4aa4ff 7c577aff
m3/part63 f86bdea4d170df901fdf00ee04d9573d 6daca9ff 481a00ff 35878fff a7d2c5ff 35878fff 46e4b8ff a7d2c5ff dff7dfff dff7dfff 47a27cff 47a27cff 47a27cff a7d2c5ff 46e4b8ff 475c3cff 481a00ff
m4/random0 50c247b25c4f89983246260a898c2d7e 10b15a8c 5c976269 10f75a8c 5c806269 10f75a8c f7c87321 10c85a8c 5c976269 5c976269 abe06b44 5c686269 10685a8c f7c87321 10975a8c ab516b44 10b15a8c
m4/random1 50ef59e0759e3ca8066aa8867fa8ed42 7be7ec7a 7b5bd600 7bb0ec7a 7b95f7b5 7be7f7b5 7b24ec7a 7b24ec7a 7b95ec7a 7be7d600 7b5bf7b5 7b3ff7b5 7b3ff7b5 7b3fec7a 7b5bec7a 7be7d600 7bb0f7b5
m4/random2 70255cb5390205c8daad2ec6557734bc 1e9a2ee1 29bd38de 29bd20de 29bd2ede 29bd33de 1e9a2ee1 137538e4 1e9a29e1 1e9a41e1 08523ce7 137525e4 085229e7 13752ee4 1e9a20e1 1e9a41e1 1e9a38e1
m4/random3 5059f3c73e65f12a28de53a42aba6f4f ce5263e7 d353cc9e d652ff7b d15396c4 d15396c4 d15796c4 d15396c4 ce5263e7 ce5363e7 d15996c4 d15896c4 ce5963e7 d658ff7b d658ff7b d354cc9e d653ff7b
m4/random4 70ef9854c60b088e00722e861bd301f7 7b316e29 65393523 7b31be29 7b316e29 394abe18 65390023 7b311b29 6539be23 7b316e29 7b318929 7b310029 7b31be29 6539be23 4f421b1e 394a3518 7b310029
m4/random5 d027d23700da84e44a7529268a3d578a 397e18a5 75a20787 39a218a5 5c7e0e93 50581199 69a20a8d 50341199 697e0a8d 757e0787 8c7e007b 69580a8d 5c580e93 75580787 69580a8d 50341199 69580a8d
m4/random6 d09c264fd5a932f42c9409e3b6f3fb09 e79ea54a dea69962 c1a275ae de9e9962 aea65edf b8a669c6 b8aa69c6 b8a269c6 cba68293 aea25edf a5a252f7 b89e69c6 a5a652f7 cba68293 d49e8e7b e7aaa54a
m4/random7 703dd5aa0c1ab9bef68eef84918bbf9a efad7b52 4aad5f31 b9ad7b47 b9ad8847 4aada231 4aad7b31 b9ad6c47 b9ad6c47 4aad7b31 80ad953c 4aad5231 b9ad4547 4aad7b31 b9ad5f47 efad5252 4aad6c31
m4/random8 f0f36e77884fae24e5cf70d1733d442b 9cded939 b882d924 b491d928 9cded939 b491b428 bd73fb21 afa0d92b aab1b42f b491b428 bd73fb21 9cde9239 a5c09232 afa0922b b882d924 a5c0b432 a1cfd936
m4/random9 d0ba458ca21d5c4a9f92de5aef273e4b a99461a4 a90461a4 a94b61a4 89db77b6 899477b6 7a9482be a94b61a4 6b4b8cc6 6b048cc6 98046dae d6db428c 6b948cc6 a99461a4 7a4b82be b8db579c b894579c
m4/random10 d06340ecccf849259341bb0d63a68e24 188e6a8d 188831c6 18833abd 18833abd 18837384 188e3abd 18887384 188357a0 18883abd 18834daa 188e6097 187d31c6 188e7384 188e6a8d 18836a8d 18836a8d
m4/random11 50ebfeb0592770095a742c746b7ee1d5 5a56deff 9d278b59 bd756308 9d568b59 5a08deff 7a17b6ae 5a56deff 5a47deff 7a17b6ae bd086308 9d278b59 5a75deff 9d178b59 9d478b59 bd276308 5a17deff
m4/random12 909b1e19d941cf12beb9f08af7da9459 de398c58 ad876958 c65f7b97 b57a6f58 de398c58 a5946397 b57a6f1c a594631c ce5380d3 c65f7bd3 c65f7b58 ce5380d3 d646861c c65f7bd3 ad876958 ce538058
m4/random13 7087cf102fe0eef25fafe84b5b3e945e 726b009c 726b869c e708babd 726b869c 726b6c9c ae39a0ad e708a0bd e70834bd e708a0bd e708babd ae3900ad ae3934ad e7081abd 726b869c 726bba9c 726b349c
m4/random14 30f9ac73e0a4122e1bdac022a3602ae1 4d5a39ce 4d446b6a 745a39ce 5a5a39ce 67398439 9d4f529d 4d4f529d 90446b6a 4d4f529d 83398439 5a5a39ce 905a39ce 674f529d 67398439 4d446b6a aa4f529d
m4/random15 b06b387b33f341bb7ef591d50e3f5dba 3073bd5a 3086c247 64accc21 6486c247 49a2c92b 7da2c92b 498fc43e 4973bd5a 7db5ce18 7db5ce18 7d99c734 64accc21 64a2c92b 6499c734 7daccc21 7da2c92b
m4/zero 10000000000000000000000000000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
m4/ones f0ffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m4/rot0 90369b7c989ca9fe7a9b15314842bec8 bc5d45cb bc5d45aa c38c51aa b53139aa c0734b65 b5313965 bc5d4565 bc5d45aa bc5d45aa b5313965 b9473f65 cece6386 c0734baa b9473f65 bc5d45cb cab85d65
m4/rot1 30aa4bab8354b1d8d09471905d12f3da 4994d652 53aa4cbb 4b9f9286 499f9286 4b94d652 4eb508ef 55aa4cbb 4c9f9286 4c94d652 4caa4cbb 50aa4cbb 4b9f9286 55aa4cbb 52aa4cbb 5394d652 53b508ef
m4/rot2 d02e5b989f2254c709267bd914a66eb1 801ec2ae ce137b84 b4139292 a8139e99 b4089292 8028c2ae b4139292 7308ceb5 c128878b a81e9e99 8d28b7a7 ce287b84 c108878b 8d28b7a7 a81e9e99 b4139292
m4/rot3 f0b0ada4afe2cadcec807284925c0b63 805828d2 6f4c58c1 80588ad2 7d5658cf 845a8ad6 724fbac4 76518ac8 765158c8 76518ac8 795358cb 724fbac4 724f58c4 845a28d6 6f4c28c1 845a28d6 795358cb
m4/isel0 30af9216eb18051101881a44af05faeb 8439978b 6f218c7b 8e218c7b 7953a29d 64218c7b 4f53a29d 6f218c7b 5a53a29d 5a218c7b 8e218c7b 8e218c7b 5a218c7b 45218c7b 4539978b 79218c7b 4539978b
m4/isel1 b035b741df626b671d73db0e46d65a91 2c5f9fb2 654893bb db4893bb a2187bce db6ba5ad 2c3b8dc0 db5f9fb2 a25499b6 a22481c9 db5499b6 2c4893bb a22f87c5 652f87c5 a25499b6 db3b8dc0 a23b8dc0
m5/random0 602e5b417ccba50736331f17fe77d835 c7476f61 81887167 81476f61 81887167 81476f61 c7887167 81476f61 c7887167 e9c5726c a3c5726c c70a6e5c 81887167 c7c5726c c7887167 810a6e5c e90a6e5c
m5/random1 2095ce079ac2418e3d8816a5e98eb494 2f5e5c90 3aa17072 2f5e5c72 2a3e5263 2a3e5272 2f5e5c63 2a3e5290 2f5e5c72 3aa17090 35816681 2a3e5263 35816672 35816690 2a3e5281 2f5e5c81 3aa17072
m5/random2 20383a886d01a1ebb1ef56c5a64d5286 70402cc4 c1a739c4 9872339e e9d9409e e9d940c4 9872337a e9d940e8 987233c4 e9d9409e c1a739e8 c1a739c4 c1a739c4 c1a7399e 70402cc4 c1a739e8 9872339e
m5/random3 20bce9e0a871d1433d1a958e295e9891 873341f4 a78f5c86 87334186 780634f4 87334186 a78f5c50 780634be 98624fbe 98624ff4 98624f86 780634be 87334186 a78f5cbe 873341f4 780634be a78f5c86
m5/random4 20d76eaf67e2b13d5ca3880742846dfb b37a5a4d bb7a786c b77a6a6c b77a6a4d b37a5a6c af7a4c4d b37a5a6c b37a5a2e af7a4c4d b37a5a0f af7a4c2e bb7a784d bb7a780f af7a4c2e af7a4c0f af7a4c0f
m5/random5 608f1bc66dd4e3e98f93e9de94f0639f 7869af38 a369af38 a3308d1e cfddf56e 7869af38 78a4d354 fa308d1e faddf56e fa308d1e 7869af38 cfddf56e a369af38 faddf56e faddf56e a3a4d354 cf69af38
m5/random6 e0d5670d7cf0aac1fb8d976efdaa6ec1 ab6a6a0e 9fc1f0bd 9fc1f0bd 9fc1f0bd a3a4c484 a787c447 ab6ac40e 9fc1c4bd 9fc1c4bd a3a4f084 ab6ac40e a7879647 9fc196bd a7876a47 9fc16abd a3a4f084
m5/random7 e0505787f4b4683295aa88fe8ec06891 8a3f8079 73434c52 a13a9a9f 8a3f6679 8a3f9a79 8a3f9a79 8a3f9a79 8a3f4c79 a13a9a9f 8a3f6679 a13a669f 8a3f8079 5c48802c 5c489a2c 5c48802c 8a3f6679
m5/random8 205d751fdd3d97c910a32924c50f481e bbfbbb65 ccdfc854 bbfbbb65 ccdfc832 c4edc232 bbfbbb32 c4edc265 d5d1cf65 bbfbbb65 c4edc243 c4edc265 bbfbbb54 ccdfc843 bbfbbb32 c4edc254 ccdfc865
m5/random9 601fb0fa7a35433bfac18df4d31ad035 bad5af3e d0afcdc1 baafcdc1 8eafcdc1 a4d5af3e a4d5af3e babbc396 d0afcdc1 d0bbc396 d0c9b969 bad5af3e 8ec9b969 babbc396 babbc396 8eafcdc1 d0afcdc1
m5/random10 e0661bad2fa2610fc93b03b49d83485b cd68d844 ad984350 8ccba75c 6cfb7468 ad984350 6cfbd868 ad98d850 8ccb745c ad98d850 cd687444 cd68d844 cd68a744 8ccb435c 8ccb745c ad98a750 6cfba768
m5/random11 e00311f868f396059a9e4a0468c6a19d 06c1656c 448f78bd 06c1786c 1ab16e87 448f78bd 448f6ebd 06c1656c 1ab18187 1ab16e87 1ab16587 309f78a2 06c1786c 309f6ea2 06c1816c 06c16e6c 06c1786c
m5/random12 20c32887cdffbab4345c9c1460de1d3a 906de62e 9aa4d22e 906de62d 8738f92e 9aa4d22d a3d9bf2d 9aa4d22e 8738f92d 9aa4d22e a3d9bf2d 8738f92e 906de62e 9aa4d22d 9aa4d22d 8738f92d 8738f92e
m5/random13 a0cbb99d41e70fa2e37ece068fdf2f83 97a4e9ed 97e8e9ed e783f918 b1c7eea7 e7e8f918 e7e8f918 e7a4f918 97e8e9ed e7e8f918 b1e8eea7 cdc7f45e b183eea7 e7e8f918 9783e9ed 9783e9ed cdc7f45e
m5/random14 20496b2a4da72e56b332dcd04abcce5c 9352e9a3 a4a9bebd 9c7cd48b 9c7cd4a3 9c7cd48b a4a9bed5 9c7cd4d5 9352e9bd a4a9bebd add3a9d5 a4a9be8b 9c7cd4d5 9352e98b a4a9bed5 a4a9bea3 9c7cd4a3
m5/random15 2045cbb4571b36402cb3f36254971492 6c98740d 6c98740e 6c98740e 4b897d0e 6c987410 4b897d0e 6c98740e 2c7a870f 6c98740d 4b897d0e 2c7a870e 6c98740d 6c98740f 8ba76a0d 2c7a870e 8ba76a0f
m5/zero 20000000000000000000000000000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
m5/ones e0ffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m5/rot0 20ad5adb8d522bff0faefb58ec041351 5fdc7cca 5fdc7cff 5adb50ee 5adb50ff 6addd5ca 5fdc7cdb 5fdc7cca 6addd5ca 5fdc7cff 6addd5ca 6addd5db 5fdc7cca 5adb50db 6addd5ca 65dca9db 5adb50db
m5/rot1 60c1803d03c076ed2da25bceb93a7298 5db03a59 71b03a59 7bb03a59 71ed0083 71b03a59 71ed0083 7bb03a59 5d32b102 71b03a59 5d32b102 7b6f772c 67ed0083 5d32b102 71b03a59 676f772c 7132b102
m5/rot2 a0ea7c99147dc18e123f88f83ec22cf8 d5aca3cb e9a37573 d5a3a3cb e9b07573 f3a75e48 f3b05e48 dfb08ca0 d5a3a3cb d5b0a3cb dfa38ca0 d5a7a3cb dfb08ca0 d5b0a3cb f3a75e48 f3a35e48 dfa38ca0
m5/rot3 e00db0c7d282fcecbb03d0b88d3d9d49 1a3c3f5a c12cfb20 51373f47 c12cbd20 51377d47 1a3cfb5a 1a3cfb5a 1a3c3f5a 1a3c7d5a 8a31fb33 8a317d33 5137bd47 1a3c7d5a c12cbd20 51373f47 c12c7d20
m6/random0 406b5b80b769e4eba9535cc5c8c91465 b9445ee1 cca447dc b63562e2 bc525be0 d2c140da bc525be0 bc525be0 d2c140da c5824fde d2c140da c8914cdd d2c140da b9445ee1 b0146ae4 bc525be0 c06556df
m6/random1 40e7574ed9322caa80cdc308aa65e43d 9de5b72d af816342 b9432e4f b74e384c a4bf9735 b74e384c af816342 9de5b72d b3664c47 b3664c47 a8a7833a aa98763d a6b38d37 bc342252 b9432e4f a4bf9735
m6/random2 c05d9ff6f042aa3e467e4bc8edefed4e 91599ca1 9954939e f2232a7f b4457394 d7324988 9954939e bc416992 df2d4085 e7283682 f2232a7f fa1e207c f2232a7f e7283682 f2232a7f f2232a7f 9954939e
m6/random3 40182256f01c612762e9065a95ba41c2 5b5d415f 403e5d59 312e6d55 1510894f 403e5d59 60623c60 2a277354 4645575a 4645575a 312e6d55 2a277354 25217853 5b5d415f 4b4b525b 5556485d 201c7d52
m6/random4 c05163d5d6d3775bb3fe85a099987988 435ef37a 26b8eca6 1ed3eab3 1bdbe9b7 3882f08b 2f9dee99 4656f476 29afeda2 2ca5ed9d 2ca5ed9d 2f9dee99 2ca5ed9d 2ca5ed9d 3294ef94 2f9dee99 2f9dee99
m6/random5 c0fc9f9752d7f99647cbae51e0f6e4f1 f571d9d0 f66fdbc3 fc5de563 fd5be756 fe55ea3a fb5fe470 f477d6ec f76ddcb6 f379d5f9 fe55ea3a f86adea6 ff53eb2d f66fdbc3 fe55ea3a f477d6ec ff53eb2d
m6/random6 40aee738ebdea0f7cba85a6b902b25a8 9082a2bb 566f7edf 777a93ca 667488d5 667488d5 9082a2bb 5e7283da 877f9cc1 b98fbba1 6f778ecf 5e7283da a889b0ac 9082a2bb a889b0ac 777a93ca 667488d5
m6/random7 4075b64174a5b89914643277578a9a1c d02a5ba6 d3225cb1 cc385a95 c7475982 d02a5ba6 ce315b9e c54e587a c54e587a c54e587a ca3f598d bd64565e c2555771 bd64565e c05c5669 b972544d d3225cb1
m6/random8 407e5f5ffc40ad0c8b273e32cfce7b42 f9d25e7c fabc735e f9c36c67 f8e54c97 fb929b22 f9df528e f8e54c97 f9df528e fb8ba119 faa08d37 fb929b22 faa08d37 faa78740 f9c36c67 f8e54c97 f9d85885
m6/random9 c0bc6eefa00b688ef51b14dbb5b8322e e1d8c95e 751d051d 96574231 ebe9db64 d2bdac55 ebe9db64 96574231 873c2528 caaf9e50 96574231 b0837041 96574231 e1d8c95e d9cbbb5a 7d2b1322 e1d8c95e
m6/random10 c0f23952ed1400e9da243e18da4857f4 cc4f2b46 ce9711b5 cc472e39 cb36341e cea20dc5 cc3e312b cd6b2170 cb2b380e cd7e1a8d ce9711b5 cd6b2170 cc472e39 cc622463 cc4f2b46 cc472e39 ceaa0ad2
m6/random11 407fc0fb004d0efc150c25802b03f216 daa73d30 edb33f1e 363f2cc9 fdbd410f ab89385c daa73d30 fdbd410f 7869338b 45492ebb daa73d30 ca9d3c3f fdbd410f daa73d30 031f27f9 977d366e edb33f1e
m6/random12 c09873d5c805804212852851338fc916 66526b80 66526b80 75424d81 81363782 81363782 6a4e6281 66526b80 75424d81 6e4a5b81 6e4a5b81 9c1a0284 81363782 84323082 90261983 7a3e4582 66526b80
m6/random13 c08e57f089f7acec4846951ed3fbe5a1 5d14c7b8 5d14c7b8 6f1cb8be 5d14c7b8 6518c1bb 8827a5c7 b43a81d5 4309dcb0 5511ceb6 aa3689d2 9a2f96cd bc3e7ad8 6518c1bb b43a81d5 4309dcb0 922b9cca
m6/random14 40825bb5b161f082a089b0dc58dfdd1b 09556df1 97404452 86434964 79454d73 09556df1 a43e4043 b13c3c34 be3a3925 79454d73 4e4b59a3 dc363004 be3a3925 be3a3925 be3a3925 a43e4043 165369e2
m6/random15 4023c5b96cdd9ccd290f034abc87c6c6 729b609c 7f9c5e9d 29976f9b 8d9d5b9d 799c5f9d 8d9d5b9d 4a99689c 729b609c 3d986b9b 44996a9c 5e9a649c 589a669c 649b639c 3d986b9b 649b639c 3d986b9b
m6/zero 40000000000000000000000000000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
m6/ones c0ffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m7/random0 80fc15fa2d2729154ac018d2c58a9763 86657689 be5da686 4c6d448b 86657689 b89a3e20 b89a3e20 d796550c 79a21049 1475148e 4c6d448b d796550c 79a21049 86657689 be5da686 79a21049 d796550c
m7/random1 80e37084617d364c6e15d7f36ebc2c13 39cc7344 39cc7344 65df5dcf 203871eb 58d2605d 75d74d75 376f6ae2 376f6ae2 203871eb 65df5dcf 58d2605d 1cc7862c 65df5dcf 203871eb 39cc7344 1cc7862c
m7/random2 80d1aa6e3eaf9a37707ae237effcd8a7 74a1b3ae 825d8eef 825d8eef 9e6d9edf 5979f3f3 aaf33020 aaf33020 9e6d9edf 5979f3f3 8fcb7065 74a1b3ae aaf33020 aaf33020 74a1b3ae 8fcb7065 8fcb7065
m7/random3 80ece75083eab94594063d18f1bc0fe1 fb00b208 baeaa34a 9ff0a533 e3aa41d3 86f7a61c e3aa41d3 e3aa41d3 baeaa34a d3e3a261 e3aa41d3 fb00b208 86f7a61c f3388d4b 86f7a61c baeaa34a e3aa41d3
m7/random4 80030454e7853d01d061b8df421ce7ed 86cf24c7 86cf24c7 2f820f9b a2c382db 2f820f9b 045d0486 a2c382db c6e6799c 045d0486 86cf24c7 d7f7757d d7f7757d 2f820f9b b3d47ebc d7f7757d b3d47ebc
m7/random5 808d02a0fb50416056a61c4bfc2d85e7 39a92876 000861cb 000861cb 000861cb 1c5645a2 39a92876 39a92876 1c5645a2 9e389d48 00aab28a 00aab28a eb009228 eb009228 00aab28a eb009228 4d72a86a
m7/random6 805565a5f16145a339729ea1a4880835 93a27de4 aae369e3 93a27de4 93a27de4 28b2cbcb 93a27de4 aae369e3 93a27de4 28b2cbcb 54459f9a aae369e3 aae369e3 3d7db6b3 3d7db6b3 69108a82 aae369e3
m7/random7 80f11eb96cee237be7cd6a2d1e55b4e4 9bde699f 18e379aa cbf338b2 dbdb619a 9bde699f 97d24fb3 97d24fb3 97d24fb3 dbdb619a 9bde699f 2c8e7db6 58e071a5 dbdb619a 9bde699f 58e071a5 18e379aa
m7/random8 800c9ccf54c79730611dcd53622fec53 86ae143c 86ae143c 9a7130d3 4b89417e 9a7130d3 62b724b2 62b724b2 79e308e3 4b89417e 62b724b2 345d5d4d 345d5d4d 62b724b2 4b89417e 4b89417e 79e308e3
m7/random9 80c6ce60f86cb2ddd1ae4d6969c73cc0 dff7b65d d8e9c286 cbcbdbdb 1199a6a3 cbcbdbdb dff7b65d 1199a6a3 0b669aa5 d2d9cfb2 18cbb2a2 0b669aa5 04348ea6 04348ea6 04348ea6 1199a6a3 0b669aa5
m7/random10 80489a65e80a61970d960519c51b45d1 64c6ce38 49d3eb28 7fb7af49 9aaa9259 64c6ce38 9aaa9259 49d3eb28 7fb7af49 7fb7af49 49d3eb28 7fb7af49 1f837b6d 49d3eb28 7fb7af49 1f837b6d 2585747a
m7/random11 80676def390b465490e42a3164c3844b 958677c0 79008292 69b251aa 791040b3 790862a2 aa718acb 791040b3 958677c0 791040b3 aa718acb 79008292 69b251aa 958677c0 790862a2 7e9d64b5 79008292
m7/random12 807a45b4f4cb6e845eaa23409dbf74b7 8ade8a4b 28ba9200 a665f714 28ba9200 28ba9200 28ba9200 7d81d60d 8ade8a4b 519eb307 65cb8642 41ba8238 65cb8642 41ba8238 65cb8642 8ade8a4b 7d81d60d
m7/random13 8055adcab90c112f9b80dc202638d468 aa8fa643 aa71e300 aa8fa643 aa71e300 5182db69 aacb28cb aa8fa643 aa71e300 5182db69 5d6e9f73 aa8fa643 aacb28cb 5182db69 6959607c 6959607c aa8fa643
m7/random14 80f604a37963fe2118b715654a6322e9 9ef73c6d 3474c48e 1830c38a 6ab63366 00302059 9ef73c6d 51bbc692 3474c48e 51bbc692 9ef73c6d 34712960 1830c38a 3474c48e 51bbc692 34712960 00302059
m7/random15 80f466d22d7f01336536f542255557a3 b68e5464 96be2c7d 8a805057 8ac2415a 7d3e762e 7d3e762e 8ac2415a 8ac2415a 71009a08 8ac2415a 8ac2415a 7d3e762e b68e5464 df5d656d 8a805057 8a805057
m7/zero 80000000000000000000000000000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
m7/ones 80ffffffffffffffffffffffffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff
m7/part0 80001cad1895041f7461d47bedfac282 623ea39b 623ea39b 281059eb 56398dee 623ea39b 18511841 281059eb 56398dee 623ea39b 8634e7c7 3f2472ec 56398dee 623ea39b 8634e7c7 6d4da6ef 56398dee
m7/part1 80015f9933e85af1e6bfe07d3690c975 b86f6d57 8878b22e b86f6d57 cb7130f3 e7652c7d 8878b22e e7652c7d e76dfff7 e7652c7d b86f6d57 8878b22e e76dfff7 8878b22e 8878b22e 5982f308 cb7130f3
m7/part2 80027e72f1b4f6047e734d51f22ec44f c7e79ee7 6eb3e664 5ddfdf45 8185ec83 794900d3 8185ec83 8185ec83 9259f3a2 937d34da 9259f3a2 6eb3e664 5ddfdf45 794900d3 8185ec83 6eb3e664 9259f3a2
m7/part3 800316fc127c91cc2c59a54a95097c4e 8b58a795 4c8fba72 c72496b6 ba414928 c72496b6 8b58a795 e7be6555 e7be6555 4c8fba72 10c3cb51 ba414928 e7be6555 10c3cb51 d8955c46 c96a5237 e7be6555
m7/part4 8084ff6352ff0f65e6340e4c89393111 f7a6a66d f8bf8f94 f7a6a66d fbf361e3 f7a6a66d fbf361e3 f8bf8f94 71793722 f7a6a66d fada78bc f8bf8f94 71793722 f7a6a66d fada78bc 1cff3404 1cff3404
m7/part5 80855f86853f802cd577af22ee90738e c0586fee c0586fee 6504f78e 4111c365 f30892eb 540bde7a 3018aa51 6504f78e c0586fee 540bde7a 6504f78e 3018aa51 6504f78e 4111c365 3018aa51 4111c365
m7/part6 80065e01321ccf688327d871067f4486 a384355e c7651c4d c7651c4d 5d56a3d3 59c36982 59c36982 863ce7c7 088a18eb 7da45071 088a18eb 5d56a3d3 088a18eb 863ce7c7 088a18eb 088a18eb 31705cdf
m7/part7 80075df191d4b8a488dc6afe7d4dba78 8e319bb9 5d4da6ae 5d4da6ae 7540a1b3 7540a1b3 8e319bb9 7540a1b3 8e6d4534 8e319bb9 5d4da6ae 87943975 87943975 a62496be 79e320fb 79e320fb 8e6d4534
m7/part8 8088385e4166e7646c4bcd6df3a7a15c 14869e96 2c6d75bf 386161d3 386161d3 386161d3 14869e96 207a8aaa 386161d3 14869e96 14869e96 207a8aaa c2ae8dd7 2c6d75bf 386161d3 8aa6b7c6 f7b665e7
m7/part9 80c9f197345a0d53a6f70c7c69943017 3c6d65ef 787e5ee3 2030ebf3 beae3404 b79158d7 5459afa5 beae3404 8a857052 beae3404 5459afa5 8a857052 5459afa5 2030ebf3 5459afa5 beae3404 beae3404
m7/part10 800a37581ba0a93b5295e5e48d661ef4 ac24623c ac24623c e734752c ac24623c 34043c5d e734752c 34043c5d c7d79675 34043c5d d3a25192 c7d79675 c7d79675 cfb36888 cfb36888 d3a25192 cbc67f7f
m7/part11 804be6c1236cdea4131bedee317dc402 cf459e34 df9ca3a2 d770a169 df9ca3a2 df9ca3a2 e7c7a6d7 e7c7a6d7 cf459e34 df9ca3a2 cf459e34 df9ca3a2 584baa8c d770a169 0c349e75 0c349e75 0c349e75
m7/part12 80cc28eaf3fe8e03cbf00563c8d80fc9 1ce775e7 20e84fb8 24ea2688 89644c85 1ce775e7 fb38308a c34d3d87 fb38308a fb38308a 89644c85 51795982 c34d3d87 51795982 89644c85 c34d3d87 89644c85
m7/part13 800d468e74ab8c7dd20c2bc39c56a8b6 9cdca34f 45b67db6 c7efb61c 9cdca34f 45b67db6 70c99083 70c99083 c7efb61c 71519292 56467265 56467265 56467265 20303008 3b3b5035 56467265 56467265
m7/part14 80cefa15dffe29801cc37f20769b1a48 8eca2baa c6db57d3 fbeb82fb c6db57d3 b4dfda52 c7a6c786 aafbe338 b4dfda52 b4dfda52 c7a6c786 aafbe338 aafbe338 aafbe338 b4dfda52 bdc2d06c aafbe338
m7/part15 800fe620d07f9d0f2422e511ba6c3aa7 c3a2f341 e3fb0851 cebfa646 cebfa646 d9de554c cebfa646 e3fb0851 c3a2f341 cebfa646 e3fb0851 cebfa646 d9de554c 0c758e45 00ba20f3 04a344ba 04a344ba
m7/part16 8050fd1babc5de71bdf507bda7ce7680 c6554cc7 aa5138eb c6554cc7 c6554cc7 c77d6df7 c6554cc7 e35961a1 c6554cc7 c77d6df7 cf7598d2 c77d6df7 aa5138eb df65ef86 df65ef86 df65ef86 d76dc4ab
m7/part17 80d114f6509eb7fdc16831ecdbc04ad5 9ea6b6d7 3cdf34b6 b6cf0c1c 3cdf34b6 9ea6b6d7 9ea6b6d7 9ea6b6d7 3cdf34b6 41d2e754 41d2e754 9ea6b6d7 71bbce97 71bbce97 71bbce97 71bbce97 14e7ff14
m7/part18 805265f3eac22178fc00570b34828ffb 929b2825 7960514c 929b2825 aad30000 929b2825 aad30000 aad30000 61287971 a5c3ab7f 61287971 aad30000 7960514c ba823828 b0a27053 ba823828 61287971
m7/part19 80d349a0bc0d46f8b77062fcdc4e0c31 429d5ca7 281828f3 0000ba30 281828f3 47bfaf64 4ddfff24 0000ba30 0d088a70 3c7d0ce7 4ddfff24 3c7d0ce7 0000ba30 429d5ca7 3c7d0ce7 4ddfff24 3c7d0ce7
m7/part20 8054367b2f187f26255c58b340b14b39 cb59cbba cb59cbba db8a28aa dbaf1eb5 996894a9 cb59cbba 34862486 dbd613c0 34862486 66775b97 cb59cbba 996894a9 996894a9 66775b97 34862486 cb59cbba
m7/part21 80952c74f0050e2a0507092dc8837a05 92e34108 6fb63935 4b863065 28592892 75125b92 92e34108 92e34108 6fb63935 75125b92 452690a2 28592892 6fb63935 75125b92 75125b92 a2002882 92e34108
m7/part22 80566772d3645d48219f7093163e6067 bf861f2a 9169361a eba20838 eba20838 654d4d0c 654d4d0c bf861f2a eba20838 92b208ba eba20838 9169361a bf861f2a df75cf4d ab9e4996 9169361a bf861f2a
m7/part23 80575507b476f8b4141be1349c9aab42 8d69a226 00e3c3d3 3838a271 2670ad91 8d69a226 5169b210 3838a271 00e3c3d3 8d69a226 8d69a226 2670ad91 2670ad91 8d69a226 aa699a30 6e69aa1b 3838a271
m7/part24 8018ebfdf51abbe80de9e89580feaf1f 61eb10d3 61eb10d3 eb8a69f3 9ecb4e86 c0c2a6a5 efaeef8e efaeef8e 79eb4151 efaeef8e efaeef8e c0c2a6a5 9ecb4e86 efaeef8e efaeef8e 90d759bc 61eb10d3
m7/part25 80d9664b51473d2e2a237a1daed2bc98 b3929061 b3929061 b3929061 b3929061 58be7aa3 89815b82 89815b82 b3929061 59a251ba 617128a2 617128a2 89815b82 59a251ba 56dba68c b3929061 89815b82
m7/part26 801a55cb31af78f0104c34e73edc12c7 8b955981 75e7049e 6282599b a6650c9e a6650c9e 75e7049e 6282599b 55f7f745 70c7aa62 5951829a 6282599b a6650c9e 55f7f745 6282599b 5951829a 55f7f745
m7/part27 80db355f106d61c781e4af2a3f6df5a4 8d5bdedb 30d3c3fb b2a61472 ffb60c55 8d5bdedb 148624ae 61961c91 8d5bdedb 8d5bdedb b2a61472 148624ae 30d3c3fb ffb60c55 b2a61472 5d98d0eb 5d98d0eb
m7/part28 809cc8dbcc48e3fffaf5ada8dbfc8207 109afbeb cf8effdf 9092fee3 a79eb970 9092fee3 348e7da6 348e7da6 a79eb970 a79eb970 dfa6d755 dfa6d755 9092fee3 348e7da6 4f96fce7 109afbeb 109afbeb
m7/part29 80ddc4fb10252de41286909b5b599806 9a208208 c755e70c b844c60b b844c60b df9696cf 3cb6866d 71ac8b8d df9696cf df9696cf 71ac8b8d aaa191af 71ac8b8d b844c60b a931a309 9a208208 9a208208
m7/part30 805e687ca761bb46ae32811d0888c144 0849d361 e0c584a8 e3b271c3 e3b271c3 0849d361 4928712b 0849d361 ded8978c e0c584a8 0849d361 0849d361 69184110 e3b271c3 e0c584a8 e3b271c3 2839a346
m7/part31 809f16029163a4ced422768003a6e90a d320d341 d320d341 1434a63c 1434a63c 3576b116 9429d24d 5333d059 3576b116 2454ab2a 5333d059 5333d059 4596b604 3576b116 3576b116 d320d341 d320d341
m7/part32 80208c001c0b238f7a83be90846f58de 8661c74e 0082d359 8238e300 008adb41 8eb68eef 0085d651 8eb68eef 0082d359 8238e300 008adb41 8a8daaa1 0082d359 8eb68eef 008adb41 8a8daaa1 0085d651
m7/part33 80e129ead42b82f69ae50caa59d3d028 38aad3cb 2cbef7cf 30b7ebce 30b7ebce 4b10b03a 420c8874 420c8874 4b10b03a 38aad3cb 30b7ebce 30b7ebce 34b1dfcc 5514d704 4b10b03a 4b10b03a 5514d704
m7/part34 80e261f0598ecbd895ba2f7572ce886e 3cb61c75 7f5ea7c0 61e3dbfb 82c3aa92 7d2ca6d7 48c55ba1 82c3aa92 61e3dbfb 3cb61c75 7f5ea7c0 3cb61c75 7f5ea7c0 7f5ea7c0 61e3dbfb 7f5ea7c0 48c55ba1
m7/part35 802315fa30ca65ab07542769ead602fb a6656dae 7579819a 3c9604a6 a1ca2799 10a2aa71 418e9685 6eaf159f a1ca2799 a1ca2799 d3e33892 a6656dae a6656dae 3c9604a6 6eaf159f 10a2aa71 10a2aa71
m7/part36 80a47ee5e27830586099663e28f593bb d3c30030 b5b01d43 58661d73 28380030 58661d73 58661d73 798a5969 798a5969 798a5969 d3c30030 58661d73 8a953cb8 bac359fb 8a953cb8 798a5969 979d3c56
m7/part37 80e532daae053e14ed0d3e47be362c64 4e5c5f5d b6ff7d1c 4e5c5f5d c9547071 305910e3 c0ab7645 4e5c5f5d d300699a d300699a 305910e3 c0ab7645 5d5d861c d300699a 4e5c5f5d c0ab7645 4e5c5f5d
m7/part38 8026a7a26aa7b6efd85a33890a63ccb7 e3d3f3b2 4480bf73 1051c39a ba94f05d 4480bf73 e3d3f3b2 a675ef34 1051c39a ba94f05d 4480bf73 7ab0ba4b a675ef34 aedfb624 ba94f05d cfb4f289 4480bf73
m7/part39 80a77eb4100a1fd299e2c298da730eb2 d32041c3 2c7da665 997aa65e 2c7da665 7b80bf62 997aa65e 2c7da665 d32041c3 2c7da665 b74c7291 a282cb61 d32041c3 b74c7291 537fb264 b74c7291 7b80bf62
m7/part40 80e89fc6e92f8c4ce5651dda87b7b8b1 dfe47ed2 34142c0c 34142c0c 602a624d 9eff4dd7 dfe47ed2 75347d6d 602a624d 34142c0c 602a624d 9eff4dd7 bef265d4 491f472c 34142c0c 75347d6d bef265d4
m7/part41 80a9dcc46d86e4d427cc86d903502605 96df9e9e 96df9e9e 96df9e9e 24453cc7 96df9e9e c78dc47d 5a7b1c85 24453cc7 3f602ca7 3f602ca7 c78dc47d 96df9e9e 3f602ca7 aeb7b18e 96df9e9e 96df9e9e
m7/part42 80aa0d8d09400844fcc68b9f030d0db6 b210828a b210828a 6d24e7c7 6d24e7c7 7c0c6e9b 0c0445be 6d24e7c7 b210828a 7c0c6e9b 6524be7d b210828a b210828a 6824cb95 6a24daaf 0c0445be 420859ad
m7/part43 806b0a534927d1071bf069222797da41 3487a9cb 4992fbe3 867b9752 9e96df34 5545048e 3487a9cb 867b9752 6d604c70 6d604c70 6d604c70 3487a9cb 5545048e 867b9752 9e96df34 4992fbe3 3487a9cb
m7/part44 80ecf3c6b7ccf8e23bbde1c9a896893f 7d6d5d7d 708cabae 708cabae cfafba3c b3b87965 a58d8a5d a58d8a5d b3b87965 708cabae cfafba3c 7d6d5d7d b3b87965 f7cfe71c f3e34920 f3e34920 7d6d5d7d
m7/part45 80edb714db6e216353bad69159ad6d16 fbb26171 b6ef656d b993967a b993967a b993967a b0a59ab6 e4c66270 b6ef656d b993967a b0a59ab6 b6ef656d fbb26171 b6ef656d cddb646e a6b69eef a6b69eef
m7/part46 80ae6867e3785eea96f7bc95d19cb3a0 10c349eb a765d480 a765d480 2fb27fe2 4e9fb9d8 db79e351 3c3cb6df 6d8eefcf 7050c5b0 4e9fb9d8 2fb27fe2 7050c5b0 3c3cb6df 10c349eb 2fb27fe2 7050c5b0
m7/part47 802fb07ade7101746905526e1fc5ac60 3d887f13 b2187120 04be860c 794e7819 794e7819 d7be4d2c d7be4d2c b2187120 04be860c 9e045dbe b141588e 794e7819 04be860c 04be860c 794e7819 3d887f13
m7/part48 80f0358ad45c3230f9a94a4eb07db85e beae0455 30969430 8fb81271 30cb30aa 30969430 20cb7938 415db028 8fb81271 beae0455 30969430 30cb30aa 5fc1228e 5fc1228e 30cb30aa 8fb81271 8fb81271
m7/part49 80b116797b84dfd8ef4ee103fcaed4b4 93b9586d 1041db10 d0ab8ea6 1041db10 507b9b3d db79ba08 d691a555 d691a555 d3f3189a 93b9586d d0ab8ea6 1041db10 d3f3189a 93b9586d 1041db10 507b9b3d
m7/part50 8072f75f10dafb55808c8d82b385f123 eb20ba18 f37a769e ef4c9959 f7a655df f37a769e eb20ba18 ffef0445 f37a769e ef4c9959 ffef0445 14ef240c 14ef240c f7a655df eb20ba18 61ef1a1f eb20ba18
m7/part51 803317220572989a6cb4a27380e462fe e70c556d e70c556d e70c556d a0136c56 5719833f 103861d3 10209a28 a0136c56 234549d0 103861d3 365430ce a0136c56 5719833f 496118cb 10209a28 10209a28
m7/part52 8074e2ed85c7f729cf42dd026642d89b 7c2d339d 69e37969 7ddfb60c 49083882 70e28d4a 69e37969 b0542db8 49083882 69e37969 e37928d3 b0542db8 7ddfb60c 7c2d339d e37928d3 69e37969 70e28d4a
m7/part53 80b53d9e2cb23525657a037d5baeb298 b65da6f7 38202030 69da79d2 f7df2c86 38202030 b2dc51ab b2dc51ab 8d497ab6 b2dc51ab 69da79d2 8d497ab6 8d497ab6 f7df2c86 38202030 b65da6f7 b2dc51ab
m7/part54 80f67f2bf980e791fb9b398e685a067a fbf33830 54b6e623 54b6e623 d2a75754 a658777a a658777a 54b6e623 54b6e623 4ea7f12e d2a75754 fbf33830 59c3db18 4ea7f12e 4ea7f12e 7d0c969e d2a75754
m7/part55 8077a2695f15b95bc1392485f5f3d16c 68996a63 87766453 7caa2d6a dbe37110 dbe37110 49ba7171 a6555d45 dbe37110 7caa2d6a 4d8e0c96 68996a63 a6555d45 49ba7171 dbe37110 acc7503c 68996a63
m7/part56 80f84c37d6e213840db85916161a9200 7f7f827e 9c83254c baf36928 9aaa8271 acbd4839 8e4d045d 9aaa8271 9aaa8271 acbd4839 9c83254c 9aaa8271 7f7f827e baf36928 9aaa8271 9aaa8271 baf36928
m7/part57 80790ab6f0883cbc9d2032f9c16fcf0c 4de78645 b645ef9e 57ba64cc 0c8ebe24 0c8ebe24 38ca983a 28f320e3 57ba64cc 0c8ebe24 38ca983a 57ba64cc 877eabb5 57ba64cc 38ca983a 4de78645 b645ef9e
m7/part58 803a61875228f99a1b989d6573e76af8 24a65d34 83cc4ca9 a6e70496 83cc4ca9 a6e70496 3c96dfcf a6e70496 389a716b 5fb197bc 389a716b 61829adb 24a65d34 24a65d34 61829adb 61829adb 5fb197bc
m7/part59 803b27c8c2a49a56c273c7f8251b3210 a773acc2 e786d7e7 a773acc2 8e62aaba 695c5d8e 244d5575 e786d7e7 e786d7e7 695c5d8e 8e62aaba 695c5d8e e786d7e7 e786d7e7 8e62aaba 45551465 45551465
m7/part60 803ce13b0b440c71a9910101946b68fa 60203b1d a331561b 20102020 e3417118 d6255457 d6255457 cb306900 db204982 20102020 60203b1d cb306900 db204982 60203b1d e3417118 cb306900 d6255457
m7/part61 80bdb0046c045cf12059b02f94cef4ad 45a86b78 7d74b03a 200000db 0b4c31c5 7d74b03a b241f300 200000db 007149ba 200000db 162518d0 007149ba 007149ba 45a86b78 b241f300 7d74b03a 7d74b03a
m7/part62 80fe5c3f277201afe295d4c2192802b9 9e4de72c 5d24ae4d ffbe146d 9e4de72c 9e4de72c 7231c142 dc3e5829 9e4de72c dc3e5829 ffbe146d ffbe146d 9e4de72c ee80354c dc3e5829 cb007908 7231c142
m7/part63 80bfc69234075cb230fa3451b208c3b0 d76d4df7 484f8a61 d06e6ebe d06e6ebe d76d4df7 6e26867e d76d4df7 ca709182 d06e6ebe 9200829a 484f8a61 6e26867e d76d4df7 484f8a61 6e26867e 6e26867e
invalid/zero 00000000000000000000000000000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
invalid/random0 00bcdf5615fb913a3ff1ff8f46e03e5a 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
invalid/random1 0020c88bbe1a64002baf4eb2a87165eb 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
invalid/random2 00db5c83a56ef8fcd1aa1c000ed5161d 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
+12 -7
View File
@@ -10,19 +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.
@@ -32,8 +37,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
## Testing, validation, and benchmarks
- [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: 21 of 21. Accepted Metal forms · Apple M5: 18 of 21. Accepted guest milestones · X1–X4: 4 of 4</desc>
<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>
<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">21 / 21</text>
<text x="510" y="58" font-size="13" text-anchor="end">42 / 42</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 / 21</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 42</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="420.00" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="210.00" 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

+35 -8
View File
@@ -1,12 +1,18 @@
# Agent task queue
Work items are GitHub issues. Contributors and coding agents claim them with a comment, work in
their own branch, and open a pull request that is checked against the claim. The queue is
their own branch, and open a pull request that is checked against the claim. The claim rules for
everyone are in `AGENTS.md` ("Claiming work before you start"): a plain reply is a valid claim, and
a claim goes stale after about one week without a pull request. The commands below are an optional
layer for contributors listed in `.github/agent-queue.json`; the bot only sees `/claim` comments, so
read the issue's comments before using it and never `/claim` over a plain-reply claim. The queue is
deterministic: the rules live in `scripts/agent_queue/` (standard-library Python, no network, no
model or external service), and GitHub Actions and the shell helpers only call it.
Status: implemented and unit-tested locally. **Not yet run on GitHub**: the workflows are untested
against the real API until the first live run.
against the real API until the first live run. Until a live smoke test has passed and existing issues
have been migrated into the queue, the pull request check is **advisory**: it reports problems but
never blocks a merge, and it must not be made a required check.
## Areas
@@ -47,18 +53,27 @@ done
prints "claimed".** Refusals name the reason: not `agent:ready`, area not allowed for you, open
or missing dependency, dependency cycle, or file overlap with a claimed task (the issue is named).
Claims are decided one at a time across the whole repository, so two overlapping claims cannot both win.
GitHub keeps at most one waiting run in a concurrency group and cancels it when a newer one
queues, so each run decides every command of the last `lease_hours` that has no bot reply yet,
oldest first; a comment listed twice is decided once. A command whose own run was cancelled is answered by the run that replaced it, or at
the latest by the hourly audit. Each reply carries a marker naming the comment it answers. A
command left unanswered for more than `lease_hours` (the workflow did not run) gets a "Not
decided" reply instead and must be posted again; one older than twice that is no longer read.
4. `scripts/agent-queue.sh start <n>` creates branch `task/<n>-<slug>` from `upstream/main` in a
separate worktree `../xenora-task-<n>` (`--here` uses the current clean checkout instead).
5. Keep the lease alive with `scripts/agent-queue.sh progress <n> "what changed"`. A claim lapses
`lease_hours` (24) after the latest of: the grant, your `/progress` comment, a push to your
`lease_hours` (168, one week) after the latest of: the grant, your `/progress` comment, a push to your
linked pull request. Other people's comments never renew it. A lapsed task returns to the queue.
6. Open the pull request with `Closes #<n>` and a DCO sign-off (`git commit -s`).
7. A different person (not the author, not the task holder) who is a maintainer or has `qa`
comments `/verified <head sha>` after running the acceptance command. A new push changes the
comments `/verified <full 40-character head sha>` after running the acceptance command. A new push changes the
head and invalidates the verification.
## Commands (issue comments)
A command must start the comment. Comments that do not start with `/` (on an issue) or with
`/verified` (on a pull request) start no job: GitHub records a skipped run and nothing else happens.
| Command | Who | Effect |
| --- | --- | --- |
| `/claim` | allowed for the area | Take a ready task |
@@ -67,7 +82,7 @@ done
| `/progress <text>` | holder | Renew the lease (text required) |
| `/blocked <reason>`, `/unblock` | holder or maintainer | Set or clear `agent:blocked` |
| `/approve-acceptance` | maintainer | Authorise the acceptance command as currently written |
| `/verified <sha>` (on a pull request) | maintainer or `qa`, not author, not holder | Independent verification of the current head |
| `/verified <40-character sha>` (on a pull request) | maintainer or `qa`, not author, not holder | Independent verification of the current head |
Labels: `area:<x>`, `priority:<critical|high|medium|low>`, `agent:ready|claimed|blocked|invalid|conflict`,
`claimed-by:<login>`. An hourly audit lapses stale claims, marks tasks with missing dependencies or
@@ -80,7 +95,16 @@ machine-readable summary (counts and lists per area, priority and state).
`agent-pr-checks` fails a pull request when: it has no `Closes #N` for a claimed task; the task is held
by someone else; it changes files outside the task's patterns; it changes a file that another open
pull request also changes; the claim has lapsed without a push; or no eligible `/verified <current
head sha>` exists. After a `/verified` comment the check is re-run automatically.
head sha>` exists. The SHA must be the full 40 characters and the only argument: a commit with the
same short prefix is cheap to make. After an accepted `/verified` (an eligible verifier, the current
head) the verify job evaluates the same check again and writes it to its run summary; the earlier
check run is not re-run, since `pull_request_target` runs are recorded against the base branch and
cannot be found by the pull request head. Refused, stale, malformed or unauthorized `/verified`
comments get a reply and nothing else, and other pull request comments start no job.
The check is advisory for now: a failure is shown as a warning and in the run summary, and the job
still succeeds. It becomes blocking (fail on problems, then a required check) only after a live smoke
test on GitHub and the migration of existing issues into the queue.
## Forks and upstream sync
@@ -104,7 +128,8 @@ sync report that shows upstream touching your files is the signal to re-read the
- Acceptance commands are never run automatically. `scripts/agent-queue.sh acceptance <n>` prints
one only when a maintainer's `/approve-acceptance` marker (posted by the bot) matches a hash of
the current text; editing the issue body invalidates the approval. Read the command before running it.
- Markers (grant, approval) count only when posted by the Actions bot, so they cannot be forged in a comment.
- Markers (grant, approval, answered command) count only when posted by the Actions bot, so they cannot be forged in a comment.
User text that a bot reply echoes (a `/blocked` reason, a login, a file pattern) has its angle brackets and backticks escaped, so a reply cannot carry a marker the user wrote.
- Workflows declare empty top-level permissions and grant each job only what it needs; actions are
pinned by commit SHA. Pull request checks run on the base branch (`pull_request_target`), never
check out or run pull request code and read changed files through the API.
@@ -118,4 +143,6 @@ sh -n scripts/agent-queue.sh scripts/agent-sync.sh
```
The tests cover command decisions, overlap, cycles, leases, acceptance hashing, pull request checks,
the summary, the CLI and a structural check of the workflow files. They do not exercise GitHub itself.
the summary, the CLI, claim concurrency (a model of a concurrency group in which newer runs cancel
pending ones, and in-order replay of unanswered commands) and a structural check of the workflow
files, including which comments start a run. They do not exercise GitHub itself.
+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).
+14 -3
View File
@@ -42,7 +42,7 @@ python3 crates/isa/generate_rdna2.py path/to/amdgpu_isa_rdna2.xml | diff -u crat
## Complete instruction metadata
`crates/isa/generate_rdna2_meta.py` reduces the same approved XML to every
gfx1030 base instruction form: 1,460 forms in 21 encoding families, with
gfx1030 base instruction form: 1,465 forms in 21 encoding families, with
identifying bits, field layouts, operands (field, data format, operand type,
width, direction), control-flow flags and allowed extension words. It runs in
two stages so regeneration and CI checks need no network and no XML:
@@ -66,8 +66,19 @@ VOP1, VOP2 and VOPC `SRC0` values 0xF9, 0xFA, 0xE9 and 0xEA add an SDWA, DPP16
or DPP8 control dword (from the RDNA 2 ISA guide's SDWA and DPP sections, not
the XML); MIMG `NSA` adds that many address dwords. An extension the form does
not list is rejected. Every LLVM-assembled fixture identifies with exact
boundaries and matching mnemonics. A broader LLVM comparison of the extension
rules is still open because it needs the LLVM oracle.
boundaries and matching mnemonics. `crates/isa/tests/llvm/identify.s` holds one
instruction per family and extension word (literal, SDWA, DPP16, DPP8 with and
without fetch-inactive, VOP3 and VOP3P literals, NSA images, MTBUF opcodes
above 7, MSAA loads); its LLVM oracle compares every name and length:
```sh
LLVM_BIN=path/to/llvm/bin cargo test --locked -p xenora-isa --test meta_llvm -- --include-ignored
```
The oracle found five instructions that the XML lists only under a literal
encoding (`S_SETREG_IMM32_B32`, `V_FMAMK_F32`, `V_FMAAK_F32`, `V_FMAMK_F16`,
`V_FMAAK_F16`); the generator now treats them as base forms that always carry a
literal.
Identification is not execution. `xenora shaders coverage` reports forms
discovered in metadata against forms the semantic decoder accepts
+31 -9
View File
@@ -15,13 +15,34 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `buffer_load_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL load | implemented | fixture verified | fixture verified |
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
| `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified |
| `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified |
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
| `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_add_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8110C109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_sub_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8191C110` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_addc_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; adds SCC; SCC = carry-out | `820980FF 7FFFFFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_subb_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; subtracts SCC; SCC = borrow | `828B0809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `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 |
| `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 |
| `v_cmp_gt_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 | `7D0802D0` | 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_ne_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 | `7D0A0301` | 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_ge_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 | `7D0C02FF 80000001` | 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_lt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 < S1), fully written | `7D820701` | 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_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 == S1), fully written | `7D8402FF 80000000` | 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_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 <= S1), fully written | `7D860208` | 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_gt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 > S1), fully written | `7D8802C0` | 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_ne_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 != S1), fully written | `7D8A026A` | 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_ge_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 >= S1), fully written | `7D8C0D01` | 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 |
| `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified |
| `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified |
| `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified |
@@ -33,26 +54,27 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `v_lshrrev_b32_e32` | Two VGPR sources and one VGPR destination | `2DFFFF01` | yes | yes | three-way passed | MSL logical right shift with a five-bit count | implemented | fixture verified | fixture verified on Apple M5 |
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
<!-- status:instructions:end -->
## Automated three-way comparison
LLVM 23.1.6, the production decoder and the independent reference decoder
matched 338 instructions across eight streams: the six synthetic fixtures,
a high-register sequence and a 272-instruction matrix assembled by LLVM.
matched 650 instructions across ten streams: the eight synthetic fixtures,
a high-register sequence and an operand matrix assembled by LLVM.
The harness checks byte offsets, widths, encoded bytes from LLVM, mnemonic
and operands, and the typed reference operation against the production
operation. It covers all 21 forms in this document.
operation. It covers all 42 compute forms in this document.
The matrix checks the 81 inline integer selectors in VOP1, SOP1 and SOPC,
forced literals that could otherwise be inline, literal selection in either
SOPC operand, high SGPR and VGPR indices, MUBUF descriptor and index
The matrix checks the 81 inline integer selectors in VOP1, SOP1, SOPC and
SOP2, forced literals that could otherwise be inline, literal selection in
either SOPC or SOP2 operand, every supported SOP2 form, every VOPC compare
with VGPR, SGPR, vcc_lo, inline and literal sources, VOP1 SGPR and vcc_lo sources, high SGPR and VGPR indices, MUBUF descriptor and index
operands, and zero and nonzero forward branch displacements. The decoder
trace exposes MUBUF operands independently of the synthetic execution ABI,
which still requires the original index and resource bindings.
Five malformed LLVM probes produced diagnostics, and 19 valid encodings
Five malformed LLVM probes produced diagnostics, and 25 valid encodings
or disassemblable branch sequences were deliberately rejected by both Xenora
decoders. Both Xenora decoders also reject all 37 interior truncation offsets
in the add fixture and every case in the unsupported-encoding list.
+3 -1
View File
@@ -1,6 +1,6 @@
# Independent gfx1030 CPU reference
`xenora_ref::execute` reads raw little-endian code bytes and input words without dependencies on the production ISA crate, the compiler or Metal. It accepts at most 1024 instruction bytes and 4096 input words. The synthetic ABI gives every invocation its own input and output word. The indexed load and store forms need no host address arithmetic, and V0 is reserved for that indexing. The reference accepts uniform forward branches driven by scalar register state. Cross-lane register access and wave-mask changes are outside the subset. Floating-point arithmetic is restricted to positive normal inputs and exact normal results.
`xenora_ref::execute` reads raw little-endian code bytes and input words without dependencies on the production ISA crate, the compiler or Metal. It accepts at most 1024 instruction bytes and 4096 input words. The synthetic ABI gives every invocation its own input and output word. The indexed load and store forms need no host address arithmetic, and V0 is reserved for that indexing. Dispatch indices form Wave32 waves of 32 consecutive invocations, executed in lockstep with shared scalar state. The reference accepts uniform forward branches driven by scalar register state or by a compare mask in VCC_LO. Cross-lane register access other than compare masks, and EXEC derived from lane data, are outside the subset. Floating-point arithmetic is restricted to positive normal inputs and exact normal results.
| AMD RDNA 2 ISA guide instruction | Reference operation |
|---|---|
@@ -9,6 +9,8 @@
| VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. |
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
| SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set SCC. Descriptor SGPRs are reserved. |
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
| VOP2 `V_ADD_F32`, `V_MUL_F32` | Require exact binary32 results by checking the inputs and the wider intermediate. Multiplication of the significands fits in binary64. Addition must also recover the smaller operand by subtracting the larger. |
+100
View File
@@ -0,0 +1,100 @@
# SOP2 scalar ALU subset
Xenora decodes and executes nine gfx1030 SOP2 forms. Each takes 32-bit
operands, writes a normal SGPR (s0-s105) and sets SCC.
| Form | D | SCC |
| --- | --- | --- |
| `s_add_u32` | S0 + S1 | carry-out of bit 31 |
| `s_sub_u32` | S0 - S1 | borrow (S1 > S0) |
| `s_add_i32` | S0 + S1 | signed overflow: S0 and S1 have the same sign and D's sign differs |
| `s_sub_i32` | S0 - S1 | signed overflow: S0 and S1 have opposite signs and D's sign differs from S0's |
| `s_addc_u32` | S0 + S1 + SCC | carry-out of bit 31 |
| `s_subb_u32` | S0 - S1 - SCC | borrow (S1 + SCC > S0) |
| `s_and_b32` | S0 & S1 | D != 0 |
| `s_or_b32` | S0 \| S1 | D != 0 |
| `s_xor_b32` | S0 ^ S1 | D != 0 |
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
These nine 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
- The AMD "RDNA 2" Instruction Set Architecture reference guide (GPUOpen,
`rdna2-shader-instruction-set-architecture.pdf`, 291 pages) gives the
pseudocode for every form in section 12.1, "SOP2 Instructions" (pages
101-102). Section 5.3, "Scalar Condition Code" (page 33), defines SCC as
signed overflow for signed add and subtract and as carry-out for the
unsigned forms. The unsigned rules below were derived before the guide was
available and agree with it.
- Opcodes, operand fields and which forms read and write SCC come from the
pinned AMD RDNA 2 XML (`crates/isa/generate_rdna2.py`). Its descriptions say
that additions "store the carry-out bit into SCC", ADDC adds "a carry-in bit
from SCC", SUBB subtracts "the carry-in bit", and the bitwise forms "set SCC
iff the result is nonzero".
- For subtraction, the XML's "carry-out" does not say whether SCC is the borrow
or its complement. LLVM's AMDGPU backend settles it. It lowers unsigned
subtract-with-overflow (`S_USUBO_PSEUDO`) to `s_sub_u32` and reads SCC as the
overflow. It also lowers 64-bit subtraction to `s_sub_u32` followed by
`s_subb_u32` (`SIISelLowering.cpp`), which is only correct if SCC is the
borrow and SUBB subtracts it. LLVM 23.1.6 also checks every encoding here
against the decoder and the reference (`compares_fixture_instructions_against_llvm`).
## Not supported
- Every other SOP2 form, including the 64-bit bitwise forms.
- Destinations other than s0-s105 (VCC, EXEC, TTMP and M0).
- Sources other than normal SGPRs, inline integers and one literal.
- Both sources selecting a literal.
- ADDC or SUBB before SCC is set.
- Writes to the fixture's resource descriptors s0-s7.
## How it runs
Scalar state in a compute fixture is wave-uniform and known while the code is
translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates
SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values
read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the
IR and MSL contain the results, not scalar instructions.
## Verification
`signed_add_and_subtract_set_scc_on_overflow_not_carry` checks eight signed
cases worked by hand, including -1 + 1 and 0 - 1, which carry or borrow but do
not overflow. The reference checks that the exact signed result fits in i32.
The independent interpreter applies the guide's sign-bit rule.
`fixtures/rdna2/scalar-alu.s` is an original program, assembled by LLVM. It
chains a carry through `s_add_u32`/`s_addc_u32` and a borrow through
`s_sub_u32`/`s_subb_u32`. It also covers aliased destinations, inline and
literal operands, bitwise results that set and clear SCC, and an
`s_cbranch_scc0` that depends on them. It also includes two signed overflows.
Its expected output, input ^ 0x0000000e,
was derived by hand.
`tests/validation/known_answers.rs` runs every supported form 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
must agree with them:
- the translator (resolved branch and emitted constant);
- the reference interpreter (exact integers, reduced modulo 2^32);
- the independent interpreter (a bit-serial ripple-carry adder).
`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
Apple M5 Pro; independent acceptance is pending.
+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 | 9 | 9 | 9 | 9 | 9 | 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 | 42 | 9 | 46 | 42 | 42 | 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` |
+214
View File
@@ -0,0 +1,214 @@
# 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` |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (`bitwise` exactly for `and`, `or`, `xor`) |
| `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` |
| `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` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32` | 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).
+234
View File
@@ -0,0 +1,234 @@
# Execution contract: bounded Wave32 VOPC integer compares (issue #186)
Status: v2, after independent review (codex-contract.log); findings 1-7 addressed. Scope is the Xenora compute-fixture ABI
(one input word and one output word per dispatched thread; dispatch index `i`
is wave `i / 32`, lane `i % 32`; every wave starts with EXEC_LO = 0xffffffff;
scalar state is wave-uniform).
## 1. Sources (public only)
- AMD "RDNA 2" Instruction Set Architecture Reference Guide, 30 Nov 2020
([public PDF](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf)):
- S1 §2.1 "Wave32 and Wave64", printed p. 7-8 (PDF p. 15-16): "The upper half
of EXEC and VCC are ignored for wave32 waves."
- S2 §3.9 "Vector Compares: VCC and VCCZ", printed p. 19-20 (PDF p. 27-28):
compares set VCC (1 = pass, 0 = fail); "VCCZ is updated every time VCC is
updated: vector compares and scalar writes to VCC"; "V_CMP_* =>
VCC[n] = EXEC[n] & (test passed for thread[n])"; "VCC is fully written;
there are no partial mask updates"; in wave32 "only the lower 32 bits of
VCC contribute to the value of VCCZ".
- S3 §4.5 "Manually Inserted Wait States", printed p. 30 (PDF p. 38):
"Inserting S_NOP is not required to achieve correct operation."
- S3b §3.3 "EXECute Mask", printed p. 13 (PDF p. 21-22): EXEC "does not
affect scalar (ALU or memory) execution or branches"; in wave32 EXECZ
reflects only the lower 32 bits.
- S4 §6.2.2 "Instruction Outputs", printed p. 43 (PDF p. 51): a thread
writes a VGPR result only if its EXEC bit is set; V_CMPX writes EXEC.
- S4b §6.2 Table 20 (operand selectors), PDF p. 49-50: 106 = VCC_LO.
- S5 §12.9 "VOPC Instructions", printed p. 150-152 (PDF p. 158-160): field map
SRC0 / VSRC1 / OP; "producing a 1 bit result per lane into VCC or EXEC";
Table 59: integer compare offsets LT 1, EQ 2, LE 3, GT 4, LG/NE 5, GE 6.
Table 61 "VOPC Compare Opcodes", printed p. 155 and 159 (PDF p. 163, 167):
128-135 V_CMP_{F,LT,EQ,LE,GT,NE,GE,T}_I32 and 192-199 the _U32 forms,
"D = VCC in VOPC encoding". The XML is authoritative for encodings.
- AMD RDNA 2 machine-readable ISA XML (pinned SHA-256 `d671ecbc...`, used by
`crates/isa/generate_rdna2.py`; see `docs/research/rdna2.md`): ENC_VOPC opcodes V_CMP_{LT,EQ,LE,GT,NE,GE}_I32
= 129-134 and V_CMP_{LT,EQ,LE,GT,NE,GE}_U32 = 193-198; descriptions "Set the
per-lane condition code to 1 iff the first input is <rel> the second input";
SRC0 and VSRC1 data format FMT_NUM_I32 for the _I32 forms and FMT_NUM_U32
for the _U32 forms; destination OPR_VCC.
- LLVM 23.1.6 AMDGPU (`llvm-mc`, gfx1030, `+wavefrontsize32`) as an encoding
oracle only: `compares_fixture_instructions_against_llvm` checks every form
with every source class against the decoder and the reference.
## 2. Supported forms
The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP:
| Form | per-lane test, S0 = SRC0, S1 = VSRC1 |
| --- | --- |
| v_cmp_lt_i32 / v_cmp_lt_u32 | S0 < S1 |
| v_cmp_eq_i32 / v_cmp_eq_u32 | S0 == S1 |
| v_cmp_le_i32 / v_cmp_le_u32 | S0 <= S1 |
| v_cmp_gt_i32 / v_cmp_gt_u32 | S0 > S1 |
| v_cmp_ne_i32 / v_cmp_ne_u32 | S0 != S1 |
| v_cmp_ge_i32 / v_cmp_ge_u32 | S0 >= S1 |
`_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values.
Operand order matters (S0 is SRC0): lt with swapped operands is gt.
SRC0 selectors, exhaustively: 0-105 (normal SGPR), 106 (VCC_LO, see 5),
128-208 (inline integers 0..64 and -1..-16), 255 (one 32-bit literal, which
must be present in full after the word), 256-511 (VGPR). Every other selector
is rejected at decode, independent of EXEC: TTMPs, M0, NULL, EXEC_LO/HI,
VCC_HI, apertures, wave-ID, reserved values, inline floats 240-248, SDWA 249,
DPP8 233/234, DPP16 250, VCCZ/EXECZ/SCC 251-253, LDS direct 254. VSRC1 is a
VGPR.
Wave size: the compute fixture ABI is defined as Wave32. A raw instruction
stream carries no wave-size declaration (the VOPC word has no wave-size field),
so every caller of the translator and the reference establishes Wave32 by
using this ABI; there is no Wave64 entry point to reject.
## 3. Semantics of one supported compare, Wave32
Let E = EXEC_LO before the instruction and A = the set of lanes that exist in
this wave (all 32 except in a final partial wave, see 7). As an unsigned
32-bit value,
VCC_LO := OR over 0 <= n < 32 of ( [n in A] & E[n] & test(S0[n], S1[n]) ) << n
- VCC_LO is fully written, every time, including bits of inactive or absent
lanes, which become 0 (S2). With E = 0 the result is VCC_LO = 0 even if VCC
held a nonzero value before.
- Inactive lanes (E[n] = 0) read no VGPR source; their bit is 0 regardless of
their data.
- VCC_HI: S1 says it is ignored in wave32; whether hardware writes it is not
settled by the sources. After any supported compare, VCC_HI has no known
value. (No supported instruction can read vcc_hi today; this keeps any
future reader honest.)
- EXEC, SCC, every VGPR and every other SGPR are unchanged.
- VCCZ, as read by `s_cbranch_vccz`, is (VCC_LO == 0) (S2, wave32 sentence).
- No wait states are needed between the compare and a reader of VCC (S3).
## 4. Rejected (controlled translation/reference error, never a silent no-op)
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
- SDWA and DPP forms; F/T, 16-bit, 64-bit and float compares; v_cmp_class.
- SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs,
M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct.
- A normal-SGPR SRC0 without a known value, when EXEC_LO != 0.
- Wave64 in any form.
## 5. VCC_LO state and where a compare result may flow
Both the translator and the reference track VCC_LO in one of three static
states, decided by the instruction path alone, never by lane data:
- *uninitialized* (program start);
- *known*: written by `s_mov_b32 vcc_lo, <known value>`, or by a compare
executed while EXEC_LO is statically 0 (result: known 0);
- *lane-derived*: written by a compare executed while EXEC_LO != 0. It stays
lane-derived even when a particular wave's result happens to be 0 or equal
to a constant; acceptance never depends on that value.
Acceptance rules for one compare:
- EXEC_LO = 0 (EXEC is always a known value in this ABI): the encoding is
validated, no source is read or checked (not VGPR readiness, SGPR knowledge
or VCC state), and VCC_LO becomes known 0.
- EXEC_LO != 0: VSRC1 and a VGPR SRC0 must be initialized and not pending a
load; a normal-SGPR SRC0 must be known; a `vcc_lo` SRC0 must be known or
lane-derived (uninitialized is rejected). VCC_LO becomes lane-derived.
While VCC_LO is lane-derived it may be read only by:
1. `s_cbranch_vccz` (6);
2. `v_mov_b32_e32 vD, vcc_lo`, which writes the 32-bit mask into vD of active
lanes (inactive lanes keep vD, as for any partial-EXEC move);
3. SRC0 of a supported compare (`v_cmp_* vcc_lo, vcc_lo, vN`), which reads the
old VCC_LO in every active lane before the new value is written.
`v_mov_b32_e32 vD, vcc_lo` follows the usual EXEC rules: with EXEC_LO = 0 it
is skipped without reading VCC; otherwise VCC_LO must be known or
lane-derived. Every other read of vcc_lo is rejected in any state: the
supported scalar instructions (`s_mov_b32`, SOP2, `s_cmp_eq_u32`) do not
accept vcc_lo as a source at decode, so `s_mov_b32 exec_lo, vcc_lo` cannot
create divergent EXEC. `s_mov_b32 vcc_lo, <known>` makes VCC_LO known again.
## 6. Branches
- `s_cbranch_scc0`: unaffected (compares do not touch SCC).
- `s_cbranch_execz`: unaffected (compares do not touch EXEC).
- `s_cbranch_vccz` with a known VCC_LO: resolved during translation, as today.
- `s_cbranch_vccz` with a lane-derived VCC_LO (a *runtime branch*): the whole
wave takes it iff VCC_LO == 0. Control flow stays wave-uniform; no lane
diverges. Accepted only if the skipped region R (from the end of the branch
to the target, exclusive) satisfies all of:
- the target is a forward instruction boundary (existing rule);
- no vector load is outstanding at the branch;
- R contains only these integer vector forms: `v_mov_b32_e32` (from a
VGPR, an immediate (inline integer, the inline +1.0f bit pattern or a
literal; the move copies bits), a known normal SGPR, or vcc_lo known or
lane-derived), `v_add_nc_u32_e64`, `v_lshlrev_b32_e32`,
`v_lshrrev_b32_e32`, `v_ashrrev_i32_e32`, `v_and_b32_e32`, `v_or_b32_e32`,
`v_xor_b32_e32`. Nothing else: no FP32 form, scalar instruction, compare,
branch, wait, memory access or `s_endpgm`;
- every VGPR written in R was initialized before the branch;
- every source read in R is ready where it is read (the normal rules, as on
the fall-through path).
These rules are checked on R's instructions whether the branch is taken or
not, and whatever EXEC_LO is, so acceptance does not depend on lane data.
After R, each VGPR written in R holds its value from R if the branch was not
taken, else its value from before the branch; scalar state (SGPRs, SCC,
EXEC, VCC state) is the same on both paths. The translator's known-bit
facts for a joined VGPR keep only bits known and equal on both inputs, and
the union of the candidate values when it has at most two (so an exact
FP32 operation after the join is still accepted when both edges allow it).
An outstanding store at the branch is allowed: the store already read its
data.
## 7. Wave formation and absent lanes
Waves are formed from consecutive dispatch indices: wave w is indices
32w..32w+31. A final partial wave (input length not a multiple of 32) has
absent lanes; they never execute and contribute 0 to every compare result.
(The fixture's EXEC_LO still reads 0xffffffff in such a wave; that existing
ABI simplification is unchanged and documented as a limitation.)
## 8. Mapping to Metal (no SIMD-group assumption)
Metal SIMD groups, threadgroups and RDNA 2 waves are not assumed to coincide.
The Metal kernel makes no cross-thread call: no simd_ballot, no threadgroup
memory, no barrier. For each compare, every thread recomputes the compare's
per-lane operand values for each of the 32 lanes of its own RDNA wave
(dispatch indices (index & ~31) + n, bounded by the grid size from
`[[threads_per_grid]]`), from those lanes' input words, and assembles VCC_LO
itself. All values are pure functions of input words and translation-time
constants, so every thread of a wave computes the same VCC_LO. A runtime
branch becomes a per-register select on (VCC_LO != 0) at the join; region
instructions are pure 32-bit ALU and are evaluated unconditionally.
## 9. Verification
`fixtures/rdna2/vector-compare.s` is an original program, assembled by LLVM.
It uses all twelve forms with VGPR, SGPR, inline, literal and `vcc_lo`
sources, a compare and a mask move under partial EXEC, a compare under empty
EXEC that must clear a stale VCC, SCC kept across compares, and a runtime
`s_cbranch_vccz`. Its expected output is written in
`tests/validation/known_answers.rs` from the listing, with an explicit
relation for each row. The test input has a wave whose branch is taken, one
whose branch is not, and a final partial wave of 9 lanes.
The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe,
0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff,
0x0f0f0f0f), in both operand orders. That is 240 programs, checked against
exact i128 differences. It also covers partial and empty EXEC with seeded
destinations, both runtime branch edges in one dispatch, and 32 rejections
pinned to their byte offset. The translator, the reference (lockstep waves,
compares on widened i64 values) and the second interpreter (sign-bit flip,
then an unsigned compare) must all agree. The 9 ordered compare slots in the
fixture each change the result when their signedness is flipped. The same
programs, plus 2 mask-chain programs (252 in all), match on native Metal with API and shader validation
(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`).
A deliberately broken copy of each implementation fails these tests: the
reference with unsigned-only compares or with the EXEC test removed; the
second interpreter with unsigned-only compares or with no empty-EXEC rule;
the translator with a stale VCC under empty EXEC (CPU), and, on Metal, with
swapped signedness, without the EXEC mask, without the absent-lane bound
(shader validation aborts on the out-of-range read) or with an inverted join.
Evidence class: agreement with a specification-derived reference, run
locally on Apple M5 Pro. It is not agreement with RDNA 2 or Xbox hardware.
## 10. Limitations
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP, 16-bit, 64-bit or float compares.
- A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there
is no divergent execution. That needs its own contract.
- The skipped region of a runtime `s_cbranch_vccz` holds only integer vector
ALU instructions. Loops, nested runtime branches and scalar state that
differs between the two edges are not supported.
- Each thread recomputes up to 32 lanes per compare. The cost grows with the
compare's dependency chain. That is fine for fixtures, and no performance is
claimed.
+253 -2
View File
@@ -65,7 +65,7 @@ llvm = "three-way passed"
[[instruction]]
form = "v_mov_b32_e32"
encoding = "VOP1, VGPR destination, VGPR or inline integer or literal source, plus the inline bit pattern for +1.0f"
encoding = "VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f"
representation = "4 or 8 B"
lowering = "constant or register value"
reference = "implemented"
@@ -147,6 +147,257 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out"
representation = "`80088308`"
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_sub_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow"
representation = "`808A8180`"
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_add_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow"
representation = "`8110C109`"
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_sub_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow"
representation = "`8191C110`"
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_addc_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; adds SCC; SCC = carry-out"
representation = "`820980FF 7FFFFFFF`"
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_subb_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; subtracts SCC; SCC = borrow"
representation = "`828B0809`"
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_and_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0"
representation = "`870D090C`"
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_or_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0"
representation = "`880ED00D`"
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_xor_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0"
representation = "`890C0A0B`"
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"
representation = "`7D020701`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_eq_i32_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"
representation = "`7D040280`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_le_i32_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"
representation = "`7D060208`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_gt_i32_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"
representation = "`7D0802D0`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ne_i32_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"
representation = "`7D0A0301`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ge_i32_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"
representation = "`7D0C02FF 80000001`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_u32_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] & (unsigned S0 < S1), fully written"
representation = "`7D820701`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_eq_u32_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] & (unsigned S0 == S1), fully written"
representation = "`7D8402FF 80000000`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_le_u32_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] & (unsigned S0 <= S1), fully written"
representation = "`7D860208`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_gt_u32_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] & (unsigned S0 > S1), fully written"
representation = "`7D8802C0`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ne_u32_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] & (unsigned S0 != S1), fully written"
representation = "`7D8A026A`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ge_u32_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] & (unsigned S0 >= S1), fully written"
representation = "`7D8C0D01`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select"
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_cbranch_scc0"
encoding = "Nonnegative signed dword displacement"
@@ -283,7 +534,7 @@ llvm = "three-way passed"
form = "s_cbranch_vccz"
encoding = "Nonnegative signed dword displacement"
representation = "`BF860001`"
lowering = "resolved Wave32 VCC_LO zero check"
lowering = "resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
+44
View File
@@ -0,0 +1,44 @@
# Compare test inventories across commits
Run this check from a Xenora checkout with Python 3.11 or later and the
native ARM64 Rust toolchain. Choose the base commit whose tests the candidate
should preserve. Comparing against `main` can catch tests missing from a
branch that predates their merge.
```sh
python3 scripts/audit/test_inventory.py main HEAD
python3 scripts/audit/test_inventory.py main HEAD --allow intended-losses.tsv
python3 scripts/audit/test_inventory.py --self-test
```
The script resolves both refs to commits, then uses a temporary detached Git
worktree for each commit. It builds the workspace with the lockfile and
default features in offline mode, using Cargo's cached dependencies. It lists
tests and then lists ignored tests using the same build. It removes each
temporary worktree after listing, including when a build fails. Git needs
permission to update its worktree registry.
Each test is identified by `package/kind:target/test_name`. The report shows
removed, added, newly ignored and newly un-ignored tests. Renames appear as a
removal and an addition. Exit code 1 means at least one unexplained removal or
newly ignored test. Exit code 0 means every loss was explained or there were
no losses. Exit code 2 means the check could not complete, for example because
a ref did not resolve or Cargo could not build it.
To explain an intended removal or a newly ignored test, copy its exact key
from the report into a UTF-8 file, followed by a literal tab and a reason.
Use one entry per line. Blank lines and lines starting with `#` are allowed.
```text
xenora-texture/test:bc_formats/old_case Replaced by new_case, which covers both endpoint orders.
```
The report still shows explained losses. Keep the reasons specific enough for
a reviewer to verify.
The inventory covers Cargo's default workspace test targets for the host and
build configuration. Feature-gated targets such as those requiring
`gpu-tests` are outside that inventory. The check lists tests without
running their bodies or verifying CPU or GPU behavior. Benchmarks are
excluded. Rustdoc includes source positions in doctest names, so moving a
doctest can appear as a removal and an addition.
+9
View File
@@ -0,0 +1,9 @@
0000: t0 = load.u32 input[index]
003c: branch.uniform 0x0048 taken=true
0048: t2 = const.u32 0x7ffffffe
004c: t3 = const.u32 0xfffffff0
0050: t4 = xor.b32 t2, t3
0054: t5 = const.u32 0x80000000
0058: t6 = xor.b32 t4, t5
005c: t7 = xor.b32 t0, t6
0060: store.u32 output[index], t7
+15
View File
@@ -0,0 +1,15 @@
#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 = 0x7ffffffeu;
uint t3 = 0xfffffff0u;
uint t4 = t2 ^ t3;
uint t5 = 0x80000000u;
uint t6 = t4 ^ t5;
uint t7 = t0 ^ t6;
output[index] = t7;
}
+56
View File
@@ -0,0 +1,56 @@
0000: t0 = load.u32 input[index]
0018: t1 = const.u32 0x00000000
001c: t2 = const.u32 0x00000001
0020: t3 = const.u32 0x0f0f0f0f
0028: t4 = const.u32 0xa5a5a5a5
0030: t5 = const.u32 0xffffffff
0034: t6 = wave.mask v_cmp_lt_i32_e32 t0, t5 exec=0xffffffff
003c: t7 = lshl.b32 t1, t2
0040: t8 = xor.b32 t7, t6
0044: t9 = wave.mask v_cmp_lt_u32_e32 t0, t5 exec=0xffffffff
004c: t10 = lshl.b32 t8, t2
0050: t11 = xor.b32 t10, t9
0054: t12 = const.u32 0x00000000
0054: t13 = wave.mask v_cmp_eq_i32_e32 t12, t0 exec=0xffffffff
005c: t14 = lshl.b32 t11, t2
0060: t15 = xor.b32 t14, t13
0064: t16 = const.u32 0x80000000
0064: t17 = wave.mask v_cmp_eq_u32_e32 t16, t0 exec=0xffffffff
0070: t18 = lshl.b32 t15, t2
0074: t19 = xor.b32 t18, t17
0078: t20 = const.u32 0x7fffffff
0078: t21 = wave.mask v_cmp_le_i32_e32 t20, t0 exec=0xffffffff
0080: t22 = lshl.b32 t19, t2
0084: t23 = xor.b32 t22, t21
0088: t24 = const.u32 0x7fffffff
0088: t25 = wave.mask v_cmp_le_u32_e32 t24, t0 exec=0xffffffff
0090: t26 = lshl.b32 t23, t2
0094: t27 = xor.b32 t26, t25
0098: t28 = const.u32 0xfffffff0
0098: t29 = wave.mask v_cmp_gt_i32_e32 t28, t0 exec=0xffffffff
00a0: t30 = lshl.b32 t27, t2
00a4: t31 = xor.b32 t30, t29
00a8: t32 = const.u32 0x00000040
00a8: t33 = wave.mask v_cmp_gt_u32_e32 t32, t0 exec=0xffffffff
00b0: t34 = lshl.b32 t31, t2
00b4: t35 = xor.b32 t34, t33
00b8: t36 = wave.mask v_cmp_ne_i32_e32 t0, t0 exec=0xffffffff
00bc: t37 = wave.mask v_cmp_ne_u32_e32 t36, t0 exec=0xffffffff
00c4: t38 = lshl.b32 t35, t2
00c8: t39 = xor.b32 t38, t37
00cc: t40 = const.u32 0x80000001
00cc: t41 = wave.mask v_cmp_ge_i32_e32 t40, t0 exec=0xffffffff
00d8: t42 = lshl.b32 t39, t2
00dc: t43 = xor.b32 t42, t41
00e8: t44 = wave.mask v_cmp_ge_u32_e32 t0, t3 exec=0x55555555
00ec: t45 = merge.lanes mask=0x55555555, t44, t4
00f4: t46 = xor.b32 t43, t45
0104: branch.uniform 0x0110 taken=true
0114: t48 = const.u32 0x00000000
0118: t49 = xor.b32 t46, t48
011c: branch.uniform 0x012c taken=false
0120: t51 = wave.mask v_cmp_gt_u32_e32 t0, t3 exec=0xffffffff
0124: branch.vccz t51 -> 0x012c
0128: t53 = xor.b32 t49, t3
012c: t54 = join.vccz t51, t53, t49
012c: store.u32 output[index], t54
+152
View File
@@ -0,0 +1,152 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]],
uint grid [[threads_per_grid]]) {
uint t0 = input[index];
uint t1 = 0x00000000u;
uint t2 = 0x00000001u;
uint t3 = 0x0f0f0f0fu;
uint t4 = 0xa5a5a5a5u;
uint t5 = 0xffffffffu;
uint t6 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) < as_type<int>(t5)) ? 1u : 0u;
t6 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t7 = t1 << (t2 & 31u);
uint t8 = t7 ^ t6;
uint t9 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 < t5) ? 1u : 0u;
t9 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t10 = t8 << (t2 & 31u);
uint t11 = t10 ^ t9;
uint t12 = 0x00000000u;
uint t13 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(t12) == as_type<int>(l0)) ? 1u : 0u;
t13 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t14 = t11 << (t2 & 31u);
uint t15 = t14 ^ t13;
uint t16 = 0x80000000u;
uint t17 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (t16 == l0) ? 1u : 0u;
t17 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t18 = t15 << (t2 & 31u);
uint t19 = t18 ^ t17;
uint t20 = 0x7fffffffu;
uint t21 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(t20) <= as_type<int>(l0)) ? 1u : 0u;
t21 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t22 = t19 << (t2 & 31u);
uint t23 = t22 ^ t21;
uint t24 = 0x7fffffffu;
uint t25 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (t24 <= l0) ? 1u : 0u;
t25 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t26 = t23 << (t2 & 31u);
uint t27 = t26 ^ t25;
uint t28 = 0xfffffff0u;
uint t29 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(t28) > as_type<int>(l0)) ? 1u : 0u;
t29 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t30 = t27 << (t2 & 31u);
uint t31 = t30 ^ t29;
uint t32 = 0x00000040u;
uint t33 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (t32 > l0) ? 1u : 0u;
t33 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t34 = t31 << (t2 & 31u);
uint t35 = t34 ^ t33;
uint t36 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) != as_type<int>(l0)) ? 1u : 0u;
t36 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t37 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (t36 != l0) ? 1u : 0u;
t37 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t38 = t35 << (t2 & 31u);
uint t39 = t38 ^ t37;
uint t40 = 0x80000001u;
uint t41 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(t40) >= as_type<int>(l0)) ? 1u : 0u;
t41 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t42 = t39 << (t2 & 31u);
uint t43 = t42 ^ t41;
uint t44 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 >= t3) ? 1u : 0u;
t44 |= ((0x55555555u >> lane) & pass) << lane;
}
uint t45 = ((0x55555555u >> (index & 31u)) & 1u) != 0u ? t44 : t4;
uint t46 = t43 ^ t45;
uint t48 = 0x00000000u;
uint t49 = t46 ^ t48;
uint t51 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 > t3) ? 1u : 0u;
t51 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t53 = t49 ^ t3;
uint t54 = t51 != 0u ? t53 : t49;
output[index] = t54;
}
Binary file not shown.
+33
View File
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP2 vectors: a carry chain through s_add_u32/s_addc_u32, a borrow
// chain through s_sub_u32/s_subb_u32, bitwise results feeding SCC, an SCC
// branch, signed overflow, and SGPR results moved into VGPRs.
// Expected: input ^ 0x0000000e.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0xfffffffe
s_add_u32 s8, s8, 3 // s8 = 1, SCC = 1 (carry-out; dst aliases src0)
s_addc_u32 s9, 0x7fffffff, 0 // s9 = 0x80000000, SCC = 0
s_sub_u32 s10, 0, 1 // s10 = 0xffffffff, SCC = 1 (borrow)
s_subb_u32 s11, s9, s8 // s11 = 0x7ffffffe, SCC = 0
s_xor_b32 s12, s11, s10 // s12 = 0x80000001, SCC = 1
s_and_b32 s13, s12, s9 // s13 = 0x80000000, SCC = 1
s_or_b32 s14, s13, -16 // s14 = 0xfffffff0, SCC = 1
s_add_i32 s16, s9, -1 // s16 = 0x7fffffff, SCC = 1 (signed overflow)
s_sub_i32 s17, s16, -1 // s17 = 0x80000000, SCC = 1 (signed overflow)
s_and_b32 s15, s14, 15 // s15 = 0, SCC = 0
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s11
v_mov_b32_e32 v3, s14
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v4, s17
v_xor_b32_e32 v2, v2, v4
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
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more