Compare commits

..
Author SHA1 Message Date
Guillaume Demay 0214a7bab5 loader: avoid allocations when fetching instruction bytes
Signed-off-by: Guillaume Demay <guillaumedemay@hotmail.fr>
2026-11-24 21:20:28 +01:00
Zach Doxsee 7dd1329866 Merge pull request #367 from jelly013/probe-default-folder
cli: use a neutral default folder for probe reports (#364)
2026-11-24 21:07:02 +01:00
Zach Doxsee 4b579af70d Merge pull request #360 from 1Bartosz/perf/116-release-lto
build: use fat LTO and one codegen unit for release builds (#116)
2026-11-24 21:06:47 +01:00
Zach Doxsee 9dfdfd1134 Merge pull request #365 from Arths17/fix/363-native-audit-utf8
Read native audit JSON as UTF-8
2026-11-24 21:05:34 +01:00
atharvranjan 8df13ae976 ci: retrigger 2026-11-24 14:02:59 -06:00
Bartosz Szczepański 36c4fbd520 changelog: state the warm DBT cost of fat LTO (#116)
Review re-measurement on Apple M5 showed warm DBT about 2% slower
under fat LTO with one codegen unit in four of four alternating runs.
The entry said it was unchanged.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:02:54 +01:00
Zach Doxsee 3c8b6bad97 Merge pull request #366 from vedantdadhich21/fix/gpu-semantic-timeout
Scripts: allow longer Metal semantic-review runs
2026-11-24 21:01:35 +01:00
Zach Doxsee d4c29cd7dd Merge pull request #368 from izdat-sl4w/fix/unsigned-jcc-boundaries
cpu: pin the unsigned Jcc conditions at their boundaries
2026-11-24 20:59:17 +01:00
Zach Doxsee 02eb8046a1 Merge pull request #355 from sahib453/task/118-xchg-accumulator
loader: add the accumulator short form of XCHG (#118)
2026-11-24 20:46:47 +01:00
Zach Doxsee 4a0b5d4ded Merge pull request #344 from sahib453/task/128-exact-unmasked-overflow
loader: set only the overflow flag for an exact unmasked overflow (#128)
2026-11-24 20:46:33 +01:00
atharvranjan 00eb6971e9 Preserve UTF-8 native inspection output
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:45:16 -06:00
Bartosz Szczepański c3b0025977 Merge upstream main into perf/116-release-lto
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:44:30 +01:00
izdat-sl4w 7c88e5d655 cpu: pin the unsigned Jcc conditions at their boundaries
The native DBT had no test for the 0x70..=0x7F or the 0F 80..=8F block
at all. These four conditions are the ones an ARM64 condition code
cannot provide directly: SUBS sets C when a subtraction does not
borrow, so x86 CF is its inverse, and ARM64's HI and LS are defined on
that same inverted carry.

Three tests derive CF and ZF from the operands (Intel SDM Volume 1,
3.4.3.1), then check JB, JAE, JBE and JA in the short and the near
encoding at both ends of the 32-bit and 64-bit ranges, with SUB as well
as CMP, and with the compare and the branch in separate translated
blocks. Inverting the borrow polarity in the lowering makes all three
fail.

Closes #64

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:43:54 +01:00
zachdoxsee bb318ed2ba Merge upstream main into task/118-xchg-accumulator
Conflicts in CHANGELOG.md, where both new entries are kept, and in the
generated crates/loader/src/x86_table.rs, which is rebuilt with
generate_x86.py from the merged instructions.toml.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:41:29 +01:00
zachdoxsee b1b57cf16a Merge upstream main into task/128-exact-unmasked-overflow
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:40:31 +01:00
Zach Doxsee cdcc55c33e Merge pull request #351 from sahib453/task/121-rcl-rcr
loader: add RCL and RCR, the rotates through carry (#121)
2026-11-24 20:39:46 +01:00
Zach Doxsee 0730f4dbbf Merge pull request #353 from sahib453/task/69-rex-before-prefix
loader: ignore a REX prefix that is followed by a legacy prefix (#69)
2026-11-24 20:39:22 +01:00
Zach Doxsee 6f27da3ccc Merge pull request #354 from 1Bartosz/perf/92-imm-materialization
loader: load ARM64 constants with the fewest wide moves (#92)
2026-11-24 20:39:00 +01:00
zachdoxsee 6236996f41 Merge upstream main into perf/92-imm-materialization
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:32:35 +01:00
Zach Doxsee 05f2526d27 Merge pull request #345 from katherinebytes/codex/dbt-benchmark-percentiles
Report p95, p99 and IQR in the DBT benchmark
2026-11-24 20:31:23 +01:00
jelly013 e5aca73c55 cli: use a neutral default folder for probe reports
`xenora probe` and `xenora imports sync` defaulted to a folder named after
one commercial game. Give both one shared default, `diagnostics/probe`, and
ignore it in Git. Keep the old ignore rules so existing local reports stay
out of commits.

Closes #364

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 20:31:13 +01:00
atharvranjan 281d92bfb5 Read native audit JSON as UTF-8
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:28:35 -06:00
Zach Doxsee 5131de9cd6 Merge pull request #350 from katherinebytes/codex/bc1-tile-row-linearization
Copy tiled BC1 data by tile row
2026-11-24 20:27:49 +01:00
Vedant Dadhich fec13fa27a Scripts: allow longer Metal semantic-review runs
The full semantic-review batch can exceed the hard-coded 120-second timeout on a cold Apple Silicon host. A local M1 acceptance run exited 124 while tests were still progressing; the same batch passed with a longer limit. Add XENORA_SEMANTIC_TIMEOUT, default it to 300 seconds, and document the override.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-25 00:57:15 +05:30
katherinebytes 68503a674c Explain DBT benchmark medians and test invocation
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:23:26 +00:00
katherinebytes 82cb66e80f Document the BC1 tile row bounds
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:23:26 +00:00
katherinebytes 06dbe2946d Merge upstream main for the DBT benchmark
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:22:23 +00:00
zachdoxsee 14d5083f0f Merge upstream main into codex/bc1-tile-row-linearization
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:20:44 +01:00
Zach Doxsee 0115af5c04 Merge pull request #332 from vedantdadhich21/docs/gfx1030-form-acceptance
Docs: define gfx1030 form acceptance
2026-11-24 20:19:26 +01:00
Zach Doxsee 5b7ffec90a Merge pull request #347 from Arths17/task/109-relocation-overhead
loader: avoid per-entry relocation histogram lookups
2026-11-24 20:15:11 +01:00
Zach Doxsee 48c5d20aa9 Merge pull request #335 from izdat-sl4w/fix/audit-utf8-locale
audit: read and write tracked files as UTF-8
2026-11-24 20:14:57 +01:00
izdat-sl4w 8049c36f51 audit: pin LF newlines in the generated status writes
Path.write_text opens with newline=None, so on Windows a regeneration
would translate the tracked LF files to CRLF and show a spurious diff.
Both write sites now pass newline="\n", which leaves the bytes
identical on macOS and Linux.

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:14:45 +01:00
izdat-sl4w c91036f879 Merge main into fix/audit-utf8-locale
Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:14:30 +01:00
sahib453 c1cea65e17 docs: take RCL and RCR off the rejected-on-purpose list (#121)
The instruction registry document listed RCL and RCR among the forms
rejected on purpose. This branch implements them, so the list no longer
names them. SHLD and SHRD stay on it.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:44:28 +05:30
Bartosz Szczepański 3d19c756e2 build: use fat LTO and one codegen unit for release builds (#116)
Release and bench builds used Cargo's defaults: no cross-crate LTO and
16 codegen units. Fat LTO with a single codegen unit lets the
interpreter and DBT hot paths inline across crates.

On Apple M5, dbt_bench medians over five alternating rounds of 101
samples drop from 903 to 845 us for the interpreter (-6%) and from
1.155 to 1.046 ms for cold DBT (-9%, faster in all five rounds); warm
DBT is unchanged. The xenora binary shrinks from 2.73 to 2.11 MB. A
clean release build of the workspace takes 14.0 s instead of 5.9 s.
Debug and test builds keep the dev profile and are unaffected.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:08:43 +01:00
sahib453 823a5812a0 loader: add the accumulator short form of XCHG (#118)
Both engines refused XCHG with the register in the opcode (91 to 97,
and 90 with REX.B) as an illegal instruction. Assemblers choose this
form whenever one operand is the accumulator.

- instructions.toml, x86_table.rs (generated): one form per opcode 91
  to 97. A row of eight would have to start at 90, which is NOP.
- x86_decode.rs: 90 stays NOP without REX.B and decodes as the 91 form
  with register r8 when REX.B is set. F3 before it is rejected.
- x86_exec.rs: exchange the accumulator with the named register at 16,
  32 and 64 bits.
- cpu_known_answers.rs: three SDM-derived cases move from refused to
  verified.
- tests/x86: 20 assembled instructions, checked by the existing
  text-only reference. `xchg r8, rax` leaves the rejected list.

Nothing is lowered to ARM64.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:09:31 +05:30
Bartosz Szczepański 710a2e1e73 loader: load ARM64 constants with the fewest wide moves (#92)
load_imm_64 emitted MOVZ for halfword 0 and then MOVK for zero
halfwords it could skip, and never used MOVN, so a small negative
constant took four instructions. It now starts from MOVZ or MOVN,
whichever leaves more halfwords already correct, at the first halfword
that differs, and adds MOVK only for the remaining differing halfwords.

On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native
bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture
instructions 128,724 instead of 145,732 (-11.7%). Benchmark run times
did not change measurably.

Tests check the sequences against llvm-mc encodings and execute the
edge values plus 512 seeded values, in X0 and X9, on the host through
the JIT, checking both the loaded value and the instruction count.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 19:31:02 +01:00
sahib453 de92766b29 loader: ignore a REX prefix that is followed by a legacy prefix (#69)
A REX prefix takes effect only immediately before the opcode (Intel SDM
Vol. 2A, 2.2.1). The decoder took the byte after the first REX as the
opcode, so `48 66 01 D8` was refused as an illegal instruction where it
should run as `add ax, bx`.

- x86_decode.rs: a REX byte followed by an operand-size, address-size,
  segment, LOCK or repeat prefix is dropped and prefix reading goes on.
  The dropped byte still counts toward the instruction length.
- cpu_known_answers.rs: the SDM-derived case moves from refused to
  verified, with three more for an ignored REX.B, an ignored REX.W
  before a segment prefix, and a later REX that does apply.

Two REX bytes in a row and the address-size prefix stay rejected.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:00:15 +05:30
sahib453 4d44765363 loader: add RCL and RCR, the rotates through carry (#121)
Both engines refused RCL and RCR (group 2, digits 2 and 3) as illegal
instructions. They are now declared in the x86 registry and run on the
shared semantics for 8-, 16-, 32- and 64-bit register and memory
operands, with a count of one, CL or an immediate.

- instructions.toml, x86_table.rs (generated): the two operations, with
  CF as an input.
- x86_exec.rs: rotation over the operand plus CF. The masked count is
  reduced modulo the operand width plus one, CF takes the last bit
  rotated out, and OF is set only for a count of one.
- cpu_known_answers.rs: fourteen SDM-derived cases move from refused to
  verified, and the shift sweep runs both instructions at every width.
- tests/x86: 80 assembled RCL and RCR instructions, with a single-step
  reference in x86_integer.rs. `rcl al, 1` leaves the rejected list.

Nothing is lowered to ARM64. SHLD and SHRD stay rejected.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:54:26 +05:30
katherinebytes 6de750b152 Copy tiled BC1 data by tile row
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 18:22:19 +00:00
atharvranjan adf10db015 loader: build relocation type counts once per image
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 12:04:05 -06:00
katherinebytes 4e4a6b36be Report DBT benchmark percentiles and warmup
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 17:55:12 +00:00
sahib453 403a67747f loader: set only the overflow flag for an exact unmasked overflow (#128)
With the overflow exception unmasked, an overflow whose result is exact
before the exponent is bounded set the MXCSR precision flag as well as
the overflow flag. The Intel SDM (Vol. 1, D.4.2.3, Table D-16) reports
precision there only if rounding with an unbounded exponent is inexact.

- softfloat.rs: Control reads the overflow mask, and round() reports
  precision on an unmasked overflow only when the result was rounded.
  The masked response is unchanged.
- cpu_known_answers.rs: the five exact-overflow cases are no longer an
  ignored defect, three more cover the other rounding modes, and the
  scalar and conversion sweeps now compare the precision flag here.
- docs/cpu/instruction-registry.md: the behaviour is no longer listed
  as unasserted.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:25:07 +05:30
Vedant Dadhich dc3b02b62f Merge latest main into docs/gfx1030-form-acceptance
# Conflicts:
#	CHANGELOG.md
2026-11-24 23:14:13 +05:30
Vedant Dadhich d847d7ea6e Docs: clarify gfx1030 acceptance terminology
Address review feedback: introduce AMD RDNA2 desktop GPU (gfx1030) before the internal codename, define the LLVM three-way decoder check, document the Apple M5 status spelling, use GitHub logins in acceptance records, and mark the independence rule as proposed pending maintainer confirmation.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-24 23:11:55 +05:30
elforeign 0fdb995892 isa, decoder, shader, ref: VOP3A encodings of eleven VOP2 integer forms and the sixteen integer compares (#215) (#311)
* isa, decoder: VOP3 encodings of the eleven registry VOP2 integer forms (#215)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 11:38:44 -06:00
Vedant Dadhich b55a4c24ef Merge main into docs/gfx1030-form-acceptance
# Conflicts:
#	CHANGELOG.md
2026-11-24 23:08:10 +05:30
elforeign d7f7d586d3 gpu: bind a texture and sampler to guest draws through descriptor tables (#303) (#336)
* gpu: bind a texture and sampler to guest draws through descriptor tables (#303)

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

Closes #334

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 18:09:21 +01:00
Vedant Dadhich 291c9807ee Docs: define gfx1030 form acceptance
Add the promotion rule for moving desktop gfx1030 forms from local CPU and Metal results to fixture verified. The rule records clean-commit evidence, independent-runner requirements, exact commands, raw-log location, review-log summaries, failure handling and status regeneration. This is documentation only: no status rows, tests or fixtures change. Part of #302.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-24 22:24:18 +05:30
84 changed files with 7557 additions and 2736 deletions

No files matched your search

+5 -1
View File
@@ -41,6 +41,8 @@ jobs:
python3 crates/isa/generate_semantics.py --check
python3 scripts/audit/semantic_coverage.py --check
python3 scripts/audit/status.py --check
# The generated status check must not depend on the host locale encoding.
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
@@ -50,6 +52,8 @@ jobs:
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
@@ -65,7 +69,7 @@ jobs:
cargo test --locked --workspace
cargo test --locked --manifest-path experiments/x1/Cargo.toml
scripts/audit/dependencies.sh
scripts/audit/claims.sh
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
- name: Inspect native CLI
run: |
cargo build --locked -p xenora
+1
View File
@@ -35,6 +35,7 @@
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
+18 -1
View File
@@ -10,14 +10,27 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
### Added
- Added an isolated experiment under `experiments/audio-dsp` with a bounded PCM mixer and opt-in native CoreAudio output. It runs outside the Xenora runtime, with measurements limited to one local machine.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
@@ -186,7 +199,10 @@ remains unsupported.
native DBT.
### Fixed
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
@@ -195,6 +211,7 @@ remains unsupported.
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
Generated
+1
View File
@@ -204,6 +204,7 @@ dependencies = [
"sha2",
"xenora-metal",
"xenora-shader",
"xenora-texture",
]
[[package]]
+7
View File
@@ -10,3 +10,10 @@ rust-version = "1.100"
[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
# Whole-program optimization for release and bench builds (#116). On an Apple M5 the
# interpreter ran about 6 % and cold DBT about 9 % faster in `dbt_bench`, at the cost of
# slower release builds. Debug and test builds are unaffected.
[profile.release]
lto = "fat"
codegen-units = 1
+1 -1
View File
@@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
scripts/test-gpu.sh
```
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
### Verify guest execution
+5 -2
View File
@@ -6,6 +6,9 @@ mod shaders;
use std::process::ExitCode;
/// Where `probe` writes and `imports sync` reads without `--report`.
const DEFAULT_REPORT_DIR: &str = "diagnostics/probe";
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("info") => {
@@ -46,7 +49,7 @@ fn main() -> ExitCode {
let args: Vec<String> = std::env::args().collect();
let mut pe_path: Option<String> = None;
let mut mode = "static".to_string();
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut i = 2;
while i < args.len() {
@@ -373,7 +376,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
}
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut check_mode = false;
let mut i = 0;
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Default report folder of `xenora probe` and `xenora imports sync`.
use std::process::Command;
#[test]
fn probe_and_sync_use_the_same_default_folder() {
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/delay-imports.exe"
);
let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id()));
std::fs::create_dir(&folder).unwrap();
for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
.args(arguments)
.current_dir(&folder)
.status()
.unwrap();
assert!(status.success(), "{arguments:?}");
}
let written = ["imports.csv", "import_backlog.md"]
.map(|name| folder.join("diagnostics/probe").join(name).is_file());
std::fs::remove_dir_all(folder).unwrap();
assert_eq!(written, [true, true]);
}
+41 -13
View File
@@ -5,8 +5,8 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp,
VectorUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
VectorSource, VectorSwapOp, VectorUnaryOp,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
@@ -330,6 +330,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if let Some(op) = VectorCompareOp::from_word(first) {
return vector_compare(op, first, bytes);
}
if let Some(op) = VectorCompareVop3Op::from_word(first) {
let second = word(bytes, 8)?;
let sdst = first as u8;
if sdst > VCC_LO {
return Err(unsupported(
op.assembly_name(),
"expected a destination of s0-s105 or vcc_lo",
));
}
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
return Ok((
Instruction::VectorCompareVop3 {
op,
sdst,
src0,
src1,
},
8,
));
}
if let Some(op) = VectorAluVop3Op::from_word(first) {
let second = word(bytes, 8)?;
return Ok((vop3_vgpr2(op, first, second)?, 8));
@@ -723,29 +743,37 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
Ok((Instruction::MoveB32 { dst, src }, len))
}
/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1
/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources
/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is
/// the gfx1030 assembler's inline-zero operand encoding.
fn vop3_vgpr2(
op: VectorAluVop3Op,
first: u32,
second: u32,
) -> Result<Instruction, DecodeErrorKind> {
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
Ok(Instruction::VectorAluVop3 {
op,
dst: first as u8,
src0,
src1,
})
}
/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4).
/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL,
/// CLAMP, OMOD and NEG are clear.
fn vop3_vgpr2_sources(
mnemonic: &'static str,
first: u32,
second: u32,
) -> Result<(u8, u8), DecodeErrorKind> {
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(unsupported(
op.assembly_name(),
mnemonic,
"expected two VGPR sources and no modifiers",
));
}
Ok(Instruction::VectorAluVop3 {
op,
dst: first as u8,
src0: src0 as u8,
src1: src1 as u8,
})
Ok((src0 as u8, src1 as u8))
}
fn scalar_form(
+304 -36
View File
@@ -5,7 +5,7 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
VectorSource, VectorUnaryOp, decode, decode_at,
VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
@@ -71,6 +71,127 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
assert_eq!(instructions, wanted);
}
#[test]
fn decodes_wave32_vop3_compares_from_llvm_words() {
use VectorCompareVop3Op::*;
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -mattr=+wavefrontsize32 -show-encoding
let cases: [(u32, VectorCompareVop3Op, u8); 19] = [
// v_cmp_lt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x81,0xd4,0x01,0x05,0x02,0x02]
(0xd481_0004, CmpLtI32, 4),
// v_cmp_eq_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x82,0xd4,0x01,0x05,0x02,0x02]
(0xd482_0004, CmpEqI32, 4),
// v_cmp_le_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x83,0xd4,0x01,0x05,0x02,0x02]
(0xd483_0004, CmpLeI32, 4),
// v_cmp_gt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x84,0xd4,0x01,0x05,0x02,0x02]
(0xd484_0004, CmpGtI32, 4),
// v_cmp_ne_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x85,0xd4,0x01,0x05,0x02,0x02]
(0xd485_0004, CmpNeI32, 4),
// v_cmp_ge_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x86,0xd4,0x01,0x05,0x02,0x02]
(0xd486_0004, CmpGeI32, 4),
// v_cmp_lt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc1,0xd4,0x01,0x05,0x02,0x02]
(0xd4c1_0004, CmpLtU32, 4),
// v_cmp_eq_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_0004, CmpEqU32, 4),
// v_cmp_le_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc3,0xd4,0x01,0x05,0x02,0x02]
(0xd4c3_0004, CmpLeU32, 4),
// v_cmp_gt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc4,0xd4,0x01,0x05,0x02,0x02]
(0xd4c4_0004, CmpGtU32, 4),
// v_cmp_ne_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc5,0xd4,0x01,0x05,0x02,0x02]
(0xd4c5_0004, CmpNeU32, 4),
// v_cmp_ge_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc6,0xd4,0x01,0x05,0x02,0x02]
(0xd4c6_0004, CmpGeU32, 4),
// v_cmp_f_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x80,0xd4,0x01,0x05,0x02,0x02]
(0xd480_0004, CmpFI32, 4),
// v_cmp_t_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x87,0xd4,0x01,0x05,0x02,0x02]
(0xd487_0004, CmpTI32, 4),
// v_cmp_f_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc0,0xd4,0x01,0x05,0x02,0x02]
(0xd4c0_0004, CmpFU32, 4),
// v_cmp_t_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc7,0xd4,0x01,0x05,0x02,0x02]
(0xd4c7_0004, CmpTU32, 4),
// v_cmp_eq_u32_e64 s0, v1, v2 ; encoding: [0x00,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_0000, CmpEqU32, 0),
// v_cmp_eq_u32_e64 s105, v1, v2 ; encoding: [0x69,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_0069, CmpEqU32, 105),
// v_cmp_eq_u32_e64 vcc_lo, v1, v2 ; encoding: [0x6a,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
(0xd4c2_006a, CmpEqU32, 106),
];
for (first, op, sdst) in cases {
let code: Vec<_> = [first, 0x0202_0501]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
let decoded = decode(Architecture::Gfx1030, &code).unwrap();
let dst = if sdst == 106 {
"vcc_lo".to_owned()
} else {
format!("s{sdst}")
};
assert_eq!(
decoded,
[DecodedInstruction {
offset: 0,
byte_len: 8,
instruction: Instruction::VectorCompareVop3 {
op,
sdst,
src0: 1,
src1: 2
},
}],
);
assert_eq!(
decoded[0].instruction.to_string(),
format!("{} {dst}, v1, v2", op.assembly_name())
);
}
}
#[test]
fn rejects_noncanonical_wave32_vop3_compare_operands() {
// v_cmp_eq_u32_e64 s4, v1, v2
let first = 0xd4c2_0004;
let second = 0x0202_0501;
let rejects = |first, second| {
let code: Vec<_> = [first, second]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
let error = decode(Architecture::Gfx1030, &code).unwrap_err();
assert_eq!(error.offset, 0);
assert!(
matches!(
error.kind,
DecodeErrorKind::UnsupportedForm {
mnemonic: "v_cmp_eq_u32_e64",
..
}
),
"{first:#010x} {second:#010x}: {error}"
);
};
// Includes vcc_hi (107), TTMPs (108-123), null (124), m0 (125) and EXEC (126-127).
for sdst in 107..=255 {
rejects((first & !0xff) | sdst, second);
}
for bit in 8..=15 {
// ABS, OP_SEL and CLAMP.
rejects(first | (1 << bit), second);
}
for bit in 27..=31 {
// OMOD and NEG.
rejects(first, second | (1 << bit));
}
rejects(first, second ^ (1 << 18)); // SRC2 = 129 instead of 128.
for shift in [0, 9] {
for selector in [4, 106, 128, 240, 255] {
// SGPR, VCC_LO, inline integer/float, literal.
rejects(first, (second & !(0x1ff << shift)) | (selector << shift));
}
}
}
#[test]
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
let lengths = [8, 4, 8, 8, 8, 4, 4];
@@ -303,6 +424,44 @@ fn reference_scalar(scalar: ScalarSource) -> Source {
}
}
fn reference_comparison(op: VectorCompareOp) -> Comparison {
Comparison {
offset: match op.relation() {
CompareRelation::Less => 1,
CompareRelation::Equal => 2,
CompareRelation::LessOrEqual => 3,
CompareRelation::Greater => 4,
CompareRelation::NotEqual => 5,
CompareRelation::GreaterOrEqual => 6,
CompareRelation::False => 0,
CompareRelation::True => 7,
},
signed: op.signed(),
}
}
fn reference_vector_integer(op: VectorAluOp) -> VectorInteger {
match op {
VectorAluOp::CndmaskB32 => VectorInteger::Select,
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
VectorAluOp::XnorB32 => VectorInteger::Xnor,
VectorAluOp::AddNcU32 => VectorInteger::Add,
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
}
}
fn reference_op(instruction: Instruction) -> Op {
match instruction {
Instruction::BufferLoadDword {
@@ -391,13 +550,23 @@ fn reference_op(instruction: Instruction) -> Op {
reference_scalar(src0),
reference_scalar(src1),
),
// The reference's VOP3 add; it is the only VOP3 variant so far.
Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
dst,
src0,
src1,
} => Op::Add(dst, src0, src1),
Instruction::VectorAluVop3 {
op,
dst,
src0,
src1,
} => Op::VectorInteger(
reference_vector_integer(op.base()),
dst,
CompareSource::Vector(src0),
src1,
),
Instruction::ScalarUnary { op, dst, src } => {
let src = reference_scalar(src);
let unary = match op {
@@ -506,19 +675,7 @@ fn reference_op(instruction: Instruction) -> Op {
}
Instruction::VectorCompare { op, src0, src1 } => {
let comparison = Comparison {
offset: match op.relation() {
CompareRelation::Less => 1,
CompareRelation::Equal => 2,
CompareRelation::LessOrEqual => 3,
CompareRelation::Greater => 4,
CompareRelation::NotEqual => 5,
CompareRelation::GreaterOrEqual => 6,
CompareRelation::False => 0,
CompareRelation::True => 7,
},
signed: op.signed(),
};
let comparison = reference_comparison(op);
let src0 = match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
@@ -531,31 +688,24 @@ fn reference_op(instruction: Instruction) -> Op {
width => panic!("unexpected VOPC operand width {width}"),
}
}
Instruction::VectorCompareVop3 {
op,
sdst,
src0,
src1,
} => Op::CompareVop3(
sdst,
reference_comparison(op.base()),
CompareSource::Vector(src0),
src1,
),
Instruction::VectorAlu {
op,
dst,
src0,
src1,
} => Op::VectorInteger(
match op {
VectorAluOp::CndmaskB32 => VectorInteger::Select,
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
VectorAluOp::XnorB32 => VectorInteger::Xnor,
VectorAluOp::AddNcU32 => VectorInteger::Add,
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
},
reference_vector_integer(op),
dst,
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
@@ -596,12 +746,14 @@ fn compares_fixture_instructions_against_llvm() {
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"),
include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 142, "forms compared: {forms:?}");
assert_eq!(forms.len(), 169, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -829,7 +981,7 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
let outside_subset: &[&[u32]] = &[
&[0x7e04_026b], // VOP1 VCC_HI source
&[0x7da2_0501], // v_cmpx_eq_u32_e32
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
&[0xd482_006a, 0x0002_0501], // v_cmp_eq_i32_e64 with SRC2 = 0
&[0x8788_0908], // s_and_b64
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
&[0x806c_0908], // SOP2 TTMP destination
@@ -1119,6 +1271,122 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() {
);
}
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding
const VOP3_INTEGER_ENCODINGS: [(VectorAluVop3Op, u32); 11] = [
// v_mul_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x09,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulI32I24, 0xd50900ff),
// v_mul_hi_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0a,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulHiI32I24, 0xd50a00ff),
// v_mul_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0b,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulU32U24, 0xd50b00ff),
// v_mul_hi_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0c,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MulHiU32U24, 0xd50c00ff),
// v_min_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x11,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MinI32, 0xd51100ff),
// v_max_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x12,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MaxI32, 0xd51200ff),
// v_min_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x13,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MinU32, 0xd51300ff),
// v_max_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x14,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::MaxU32, 0xd51400ff),
// v_xnor_b32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x1e,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::XnorB32, 0xd51e00ff),
// v_sub_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x26,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::SubNcU32, 0xd52600ff),
// v_subrev_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x27,0xd5,0x00,0xff,0x02,0x02]
(VectorAluVop3Op::SubrevNcU32, 0xd52700ff),
];
const VOP3_INTEGER_SOURCE_WORD: u32 = 0x0202_ff00;
#[test]
fn decodes_registry_vop3_integer_encodings() {
for (op, first) in VOP3_INTEGER_ENCODINGS {
let bytes = [first.to_le_bytes(), VOP3_INTEGER_SOURCE_WORD.to_le_bytes()].concat();
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
assert_eq!(decoded.len(), 1);
assert_eq!(decoded[0].byte_len, 8);
assert_eq!(
decoded[0].instruction,
Instruction::VectorAluVop3 {
op,
dst: 255,
src0: 0,
src1: 127,
}
);
}
}
#[test]
fn decodes_vop3_integer_fixture() {
use VectorAluVop3Op::*;
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
let decoded = decode(Architecture::Gfx1030, code).unwrap();
let expected = [
(MulI32I24, 2, 1, 1),
(MulHiI32I24, 3, 2, 1),
(MulU32U24, 4, 2, 1),
(MulHiU32U24, 255, 4, 1),
(MinI32, 6, 1, 2),
(MaxI32, 7, 1, 4),
(MinU32, 8, 3, 1),
(MaxU32, 9, 255, 2),
(XnorB32, 10, 1, 255),
(SubNcU32, 11, 6, 10),
(SubrevNcU32, 1, 1, 9),
];
let actual: Vec<_> = decoded
.iter()
.filter_map(|decoded| match decoded.instruction {
Instruction::VectorAluVop3 {
op,
dst,
src0,
src1,
} => Some((decoded.offset, decoded.byte_len, op, dst, src0, src1)),
_ => None,
})
.collect();
let expected: Vec<_> = expected
.into_iter()
.enumerate()
.map(|(index, (op, dst, src0, src1))| (12 + 8 * index, 8, op, dst, src0, src1))
.collect();
assert_eq!(actual, expected);
}
#[test]
fn rejects_registry_vop3_integer_modifiers_and_other_sources() {
for (op, first) in VOP3_INTEGER_ENCODINGS {
let second = VOP3_INTEGER_SOURCE_WORD;
let reject = |first: u32, second: u32| {
let bytes = [first.to_le_bytes(), second.to_le_bytes()].concat();
let error = decode(Architecture::Gfx1030, &bytes)
.expect_err(&format!("{op:?} accepted {first:#010x} {second:#010x}"));
assert_eq!(error.offset, 0);
assert!(matches!(
error.kind,
DecodeErrorKind::UnsupportedForm { mnemonic, .. }
if mnemonic == op.assembly_name()
));
};
// First word: ABS[10:8], OP_SEL[14:11], CLAMP[15].
for bit in 8..=15 {
reject(first | (1 << bit), second);
}
// Second word: OMOD[28:27], NEG[31:29].
for bit in 27..=31 {
reject(first, second | (1 << bit));
}
reject(first, second & !0x1ff); // SRC0 = s0
reject(first, (second & !(0x1ff << 9)) | (128 << 9)); // SRC1 = inline zero
reject(first, second | (1 << 18)); // SRC2 = inline one
}
}
#[test]
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
use xenora_decoder::ScalarImmediateCompareOp;
+61 -22
View File
@@ -44,7 +44,7 @@ TOP_KEYS = {
# An encoding variant is another encoding of a form already in the registry (for
# example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base
# form, the encoding family, its opcode there and the operand rule of that
# encoding. It inherits the base form's operation, signedness and effects.
# encoding. The rule may redirect the base form's mask to an explicit destination.
VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"}
# The assembler suffix LLVM prints for a variant's encoding family.
ASSEMBLY_SUFFIX = {"VOP3": "_e64"}
@@ -151,8 +151,9 @@ SCC = {
"selected_src0": "SelectedSrc0",
}
# lane_mask: the Wave32 compare or carry result written to VCC_LO.
# sdst_lane_mask: the Wave32 compare result written to explicit VOP3A SDST.
# EXEC writes such as v_cmpx have no contract, so exec must stay unchanged.
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask", "sdst_lane_mask": "SdstLaneMask"}
WAVE = {"any": "Any", "wave32": "Wave32"}
# The synthetic compute fixture ABI fixes the wave size for these operand-rule
# kinds and for the VCC-reading VOP2 rule. Other forms declare "any".
@@ -275,7 +276,12 @@ UNSUPPORTED_COMBOS = {
# which SOP2 groups under src_vcc and src_special).
# VOP3 rules also name source classes and encoding fields they refuse.
VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"}
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null", "dst_vcc_hi"} | VOP3_COMBOS
VOP3_VGPR2_UNSUPPORTED = {
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
}
VECTOR_UNARY_PRIMITIVES = {
("not", "bitwise"): "Not",
("brev", "bitwise"): "ReverseBits",
@@ -495,16 +501,34 @@ OPERAND_RULES = {
},
# Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and
# SRC2 the assembler's unused inline zero; the decoder rejects the rest.
"unsupported": {
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
},
"unsupported": VOP3_VGPR2_UNSUPPORTED,
"kind": "vector_vop3",
# Only encoding variants of forms whose rule has this kind may use it.
"variant_of": "vector",
# The generated enum of this rule's variants; base() maps to "enum".
"variant_enum": "VectorAluVop3Op",
},
"vop3_cmp_vgpr2": {
"rust": "Vop3CmpVgpr2",
"enum": "VectorCompareOp",
"shape": {
"family": "VOP3",
"dst": {"field": "VDST", "class": "sgpr", "min": 0, "max": 106},
"src": [
{"field": "SRC0", "class": "vgpr"},
{"field": "SRC1", "class": "vgpr"},
],
"max_literals": 0,
"variant_only": True,
},
"unsupported": VOP3_VGPR2_UNSUPPORTED | {
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
},
"kind": "vector_compare_vop3",
"variant_of": "vector_compare",
"variant_enum": "VectorCompareVop3Op",
"vcc_transition": ("lane_mask", "sdst_lane_mask"),
},
"vop2_vgpr": {
"rust": "Vop2Vgpr",
"enum": "VectorAluOp",
@@ -744,18 +768,18 @@ def _check_xml(form, rule, snapshot, errors):
):
mask_inputs += 1
elif field:
operands[field] = (data_format, size, is_input, is_output)
operands[field] = (data_format, kind, size, is_input, is_output)
elif kind == "OPR_VCC":
vcc_operands.append((is_input, is_output))
vcc_operands.append((data_format, size, is_input, is_output))
else:
implicit.add(kind)
if form["carry_in"] == "vcc":
if vcc_operands.count((True, False)) != 1:
if vcc_operands.count(("FMT_NUM_M64", 64, True, False)) != 1:
errors.append(f"{label}: carry_in vcc requires one implicit XML VCC input")
if (True, False) in vcc_operands:
vcc_operands.remove((True, False))
if ("FMT_NUM_M64", 64, True, False) in vcc_operands:
vcc_operands.remove(("FMT_NUM_M64", 64, True, False))
if form["vcc"] == "lane_mask":
if vcc_operands != [(False, True)]:
if vcc_operands != [("FMT_NUM_M64", 64, False, True)]:
errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output")
elif vcc_operands:
implicit.add("OPR_VCC")
@@ -780,7 +804,7 @@ def _check_xml(form, rule, snapshot, errors):
if field not in operands:
errors.append(f"{label}: XML has no operand {field}")
continue
data_format, size, is_input, is_output = operands[field]
data_format, kind, size, is_input, is_output = operands[field]
if field == "SIMM16" and _rule_kind(form) == "control":
expected_kind, expected_format = (
("OPR_LABEL", "FMT_NUM_I16") if form["operands"] == "sopp_branch"
@@ -800,6 +824,11 @@ def _check_xml(form, rule, snapshot, errors):
continue
bits = form.get(SOURCE_BITS_KEY) if is_source else None
expected = bits if type(bits) is int else form["width"]
if not is_source and form["vcc"] == "sdst_lane_mask":
# The XML describes the Wave64 pair. The Wave32 ABI writes one SGPR.
expected = 64
if (kind, data_format) != ("OPR_SREG", "FMT_NUM_M64"):
errors.append(f"{label}: {field} is not a scalar mask destination in the XML")
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
# The XML marks both swap operands as outputs. Guide 12.8 also
@@ -896,10 +925,11 @@ def validate(registry, snapshot):
if form["wave"] in WAVE and form["wave"] != wave:
errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})")
lane_mask = _rule_kind(form) == "vector_compare" or (reads_vcc and form["operation"] != "cselect")
if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask:
vcc = "lane_mask" if lane_mask else "unchanged"
if form["vcc"] in MASK and form["vcc"] != vcc:
errors.append(
f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} "
f"(requires {'lane_mask' if lane_mask else 'unchanged'})"
f"(requires {vcc})"
)
if form["exec"] != "unchanged":
errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)")
@@ -1070,9 +1100,10 @@ def variant_row(registry, variant, base=None):
"""The base form re-encoded: its declaration with the variant's identity."""
if base is None:
base = next(form for form in registry["form"] if form.get("name") == variant["of"])
_, vcc = OPERAND_RULES[variant["operands"]].get("vcc_transition", ("unchanged", "unchanged"))
return dict(
base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"],
spec=variant["spec"], verify=variant["verify"],
vcc=vcc, spec=variant["spec"], verify=variant["verify"],
)
@@ -1142,24 +1173,32 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
if FORM_KEYS - set(base):
errors.append(f"{label}: not checked, its form {variant['of']} is incomplete")
continue
base_vcc, _ = implemented.get("vcc_transition", ("unchanged", "unchanged"))
if base["vcc"] != base_vcc:
errors.append(
f"{label}: operand rule {variant['operands']} requires a base "
f"destination contract of {base_vcc}, got {base['vcc']}"
)
# The same base row as the completeness check above (with duplicate
# declarations, the dict keeps the last one).
_check_xml(variant_row(registry, variant, base), rule, snapshot, errors)
# Every explicit operand, destination included, has the base encoding's
# data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3).
# Explicit destinations and sources keep the base encoding's data format
# in the same role. The implicit-to-explicit mask transition is checked
# above and in _check_xml for each encoding.
base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"])))
own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"])))
base_rule = rules.get(base.get("operands"))
if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule):
# Operands correspond by role, in rule order: the destination, then
# each source (VSRC1 of VOP2 is SRC1 of VOP3).
def roles(rule, record):
def roles(rule, record, explicit_dst):
by_field = {row[0]: row[1] for row in record["operands"] if row[0]}
fields = ([rule["dst"]["field"]] if "dst" in rule else [])
fields = [rule["dst"]["field"]] if explicit_dst else []
fields += [src["field"] for src in rule.get("src", [])]
return [(field, by_field.get(field)) for field in fields]
pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml)))
explicit_dst = "dst" in base_rule and "dst" in rule
pairs = zip(roles(base_rule, base_xml, explicit_dst), roles(rule, own_xml, explicit_dst))
for (base_field, base_format), (field, data_format) in pairs:
if base_format != data_format:
errors.append(
+1
View File
@@ -49,6 +49,7 @@ file = "amdgpu_isa_rdna2.xml"
# width operand and result width in bits
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output)
# VOP3A compare variant rows derive sdst_lane_mask from their operand rule.
# wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms)
# operands a key of [operand_rules]
# spec references; at least one guide section with a page
+323
View File
@@ -1,6 +1,202 @@
# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- Wave32 VOPC compares in VOP3A (#215) ----
# VDST encodes the scalar lane-mask destination, including vcc_lo (selector 106).
# The two sources are VGPRs. Modifiers are clear and SRC2 is inline zero.
[operand_rules.vop3_cmp_vgpr2]
family = "VOP3"
dst = { field = "VDST", class = "sgpr", min = 0, max = 106 }
src = [
{ field = "SRC0", class = "vgpr" },
{ field = "SRC1", class = "vgpr" },
]
max_literals = 0
variant_only = true
unsupported = [
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
]
# Opcodes come from the pinned XML's default ENC_VOP3 records.
[[encoding_variant]]
of = "V_CMP_LT_I32"
family = "VOP3"
opcode = 129
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_EQ_I32"
family = "VOP3"
opcode = 130
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_LE_I32"
family = "VOP3"
opcode = 131
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GT_I32"
family = "VOP3"
opcode = 132
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_NE_I32"
family = "VOP3"
opcode = 133
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GE_I32"
family = "VOP3"
opcode = 134
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_LT_U32"
family = "VOP3"
opcode = 193
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_EQ_U32"
family = "VOP3"
opcode = 194
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_LE_U32"
family = "VOP3"
opcode = 195
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GT_U32"
family = "VOP3"
opcode = 196
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_NE_U32"
family = "VOP3"
opcode = 197
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_GE_U32"
family = "VOP3"
opcode = 198
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_F_I32"
family = "VOP3"
opcode = 128
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_T_I32"
family = "VOP3"
opcode = 135
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_F_U32"
family = "VOP3"
opcode = 192
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_CMP_T_U32"
family = "VOP3"
opcode = 199
operands = "vop3_cmp_vgpr2"
spec = [
{ document = "guide", section = "3.9", page = 19 },
{ document = "guide", section = "13.3.4", page = 257 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- VOP3 encoding variants of registry forms (#215) ----
# An [[encoding_variant]] re-encodes a form declared in another family file: it
# names the form (`of`), this family, the XML opcode here and the operand rule
@@ -37,3 +233,130 @@ spec = [
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ABS and NEG apply to floating-point inputs (guide 6.2.1) and OMOD
# applies to floating-point results (6.2.2). These integer forms use neither.
# OP_SEL selects 16-bit halves (13.3.4). CLAMP saturates integer results
# (6.5), which these registry forms do not declare. SGPR, inline and literal
# sources remain outside this operand rule.
[[encoding_variant]]
of = "V_MUL_I32_I24"
family = "VOP3"
opcode = 265
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 131 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MUL_HI_I32_I24"
family = "VOP3"
opcode = 266
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 132 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MUL_U32_U24"
family = "VOP3"
opcode = 267
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 132 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MUL_HI_U32_U24"
family = "VOP3"
opcode = 268
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 132 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MIN_I32"
family = "VOP3"
opcode = 273
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MAX_I32"
family = "VOP3"
opcode = 274
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MIN_U32"
family = "VOP3"
opcode = 275
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_MAX_U32"
family = "VOP3"
opcode = 276
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 133 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_XNOR_B32"
family = "VOP3"
opcode = 286
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_SUB_NC_U32"
family = "VOP3"
opcode = 294
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[encoding_variant]]
of = "V_SUBREV_NC_U32"
family = "VOP3"
opcode = 295
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+14 -1
View File
@@ -20,7 +20,8 @@ pub use rdna2::{
};
pub use semantics_gen::{
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
VectorSwapOp, VectorUnaryOp,
};
impl VectorAluOp {
@@ -227,6 +228,14 @@ pub enum Instruction {
src0: VectorSource,
src1: u8,
},
/// VOP3A 32-bit integer compare writing a Wave32 mask to s0-s105 or `vcc_lo`.
/// Both sources are VGPR indices.
VectorCompareVop3 {
op: VectorCompareVop3Op,
sdst: u8,
src0: u8,
src1: u8,
},
/// VOP2 32-bit per-lane integer operation from the semantic registry.
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
/// `src1` is a VGPR. Inactive lanes keep `dst`.
@@ -309,6 +318,7 @@ impl Instruction {
Self::ScalarImmediate { op, .. } => op.mnemonic(),
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
Self::VectorCompare { op, .. } => op.assembly_name(),
Self::VectorCompareVop3 { op, .. } => op.assembly_name(),
Self::VectorAlu { op, .. } => op.assembly_name(),
Self::BranchSccZero { .. } => "s_cbranch_scc0",
Self::BranchExecZero { .. } => "s_cbranch_execz",
@@ -393,6 +403,9 @@ impl fmt::Display for Instruction {
Self::VectorCompare { src0, src1, .. } => {
write!(formatter, " vcc_lo, {src0}, v{src1}")
}
Self::VectorCompareVop3 {
sdst, src0, src1, ..
} => write!(formatter, " {}, v{src0}, v{src1}", ScalarDestination(sdst)),
Self::VectorAlu {
op,
dst,
+8 -3
View File
@@ -47,7 +47,7 @@ pub enum Operation {
LogicalShiftRight,
/// Shift S0 right by the masked count in S1, filling with its sign bit.
ArithmeticShiftRight,
/// Compare S0 with S1 under the form's relation; writes only SCC.
/// Compare S0 with S1 under the form's relation, producing SCC or a lane mask.
Compare,
/// Bitwise complement of S0.
Not,
@@ -227,7 +227,7 @@ pub enum SccEffect {
SelectedSrc0,
}
/// What a form writes to VCC or EXEC.
/// Where a form writes its lane mask, if any.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MaskEffect {
/// Not written.
@@ -236,6 +236,8 @@ pub enum MaskEffect {
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
/// it (docs/shaders/vector-compare.md section 3).
LaneMask,
/// Wave32 VOP3A compare mask written to SDST, which may be `vcc_lo`.
SdstLaneMask,
}
/// Wave-size restriction.
@@ -288,6 +290,9 @@ pub enum OperandRule {
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
/// rejected as unsupported.
Vop3Vgpr2,
/// VOP3A compare: VDST encodes s0-s105 or `vcc_lo`; SRC0 and SRC1 are
/// VGPRs, SRC2 is unused and all modifiers are clear.
Vop3CmpVgpr2,
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
/// rejected as unsupported.
@@ -365,7 +370,7 @@ pub struct FormSemantics {
pub relation: Option<CompareRelation>,
/// SCC write.
pub scc: SccEffect,
/// VCC write.
/// Implicit VCC write or explicit scalar destination for a compare mask.
pub vcc: MaskEffect,
/// EXEC write.
pub exec: MaskEffect,
+834 -10
View File
@@ -3421,17 +3421,62 @@ impl VectorCompareOp {
}
}
/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`).
/// VOP3 encodings of registry forms (operand rule `vop3_cmp_vgpr2`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorAluVop3Op {
/// `v_add_nc_u32_e64` (VOP3 opcode 293).
AddNcU32,
pub enum VectorCompareVop3Op {
/// `v_cmp_lt_i32_e64` (VOP3 opcode 129).
CmpLtI32,
/// `v_cmp_eq_i32_e64` (VOP3 opcode 130).
CmpEqI32,
/// `v_cmp_le_i32_e64` (VOP3 opcode 131).
CmpLeI32,
/// `v_cmp_gt_i32_e64` (VOP3 opcode 132).
CmpGtI32,
/// `v_cmp_ne_i32_e64` (VOP3 opcode 133).
CmpNeI32,
/// `v_cmp_ge_i32_e64` (VOP3 opcode 134).
CmpGeI32,
/// `v_cmp_lt_u32_e64` (VOP3 opcode 193).
CmpLtU32,
/// `v_cmp_eq_u32_e64` (VOP3 opcode 194).
CmpEqU32,
/// `v_cmp_le_u32_e64` (VOP3 opcode 195).
CmpLeU32,
/// `v_cmp_gt_u32_e64` (VOP3 opcode 196).
CmpGtU32,
/// `v_cmp_ne_u32_e64` (VOP3 opcode 197).
CmpNeU32,
/// `v_cmp_ge_u32_e64` (VOP3 opcode 198).
CmpGeU32,
/// `v_cmp_f_i32_e64` (VOP3 opcode 128).
CmpFI32,
/// `v_cmp_t_i32_e64` (VOP3 opcode 135).
CmpTI32,
/// `v_cmp_f_u32_e64` (VOP3 opcode 192).
CmpFU32,
/// `v_cmp_t_u32_e64` (VOP3 opcode 199).
CmpTU32,
}
impl VectorAluVop3Op {
impl VectorCompareVop3Op {
/// Every variant, in registry order.
pub const ALL: [Self; 1] = [
Self::AddNcU32,
pub const ALL: [Self; 16] = [
Self::CmpLtI32,
Self::CmpEqI32,
Self::CmpLeI32,
Self::CmpGtI32,
Self::CmpNeI32,
Self::CmpGeI32,
Self::CmpLtU32,
Self::CmpEqU32,
Self::CmpLeU32,
Self::CmpGtU32,
Self::CmpNeU32,
Self::CmpGeU32,
Self::CmpFI32,
Self::CmpTI32,
Self::CmpFU32,
Self::CmpTU32,
];
/// Selects the variant from the first word of its VOP3 encoding: the
@@ -3442,7 +3487,159 @@ impl VectorAluVop3Op {
return None;
}
match (word >> 16) & 0x3ff {
128 => Some(Self::CmpFI32),
129 => Some(Self::CmpLtI32),
130 => Some(Self::CmpEqI32),
131 => Some(Self::CmpLeI32),
132 => Some(Self::CmpGtI32),
133 => Some(Self::CmpNeI32),
134 => Some(Self::CmpGeI32),
135 => Some(Self::CmpTI32),
192 => Some(Self::CmpFU32),
193 => Some(Self::CmpLtU32),
194 => Some(Self::CmpEqU32),
195 => Some(Self::CmpLeU32),
196 => Some(Self::CmpGtU32),
197 => Some(Self::CmpNeU32),
198 => Some(Self::CmpGeU32),
199 => Some(Self::CmpTU32),
_ => None,
}
}
/// The form this encodes, whose declaration it inherits.
pub const fn base(self) -> VectorCompareOp {
match self {
Self::CmpLtI32 => VectorCompareOp::CmpLtI32,
Self::CmpEqI32 => VectorCompareOp::CmpEqI32,
Self::CmpLeI32 => VectorCompareOp::CmpLeI32,
Self::CmpGtI32 => VectorCompareOp::CmpGtI32,
Self::CmpNeI32 => VectorCompareOp::CmpNeI32,
Self::CmpGeI32 => VectorCompareOp::CmpGeI32,
Self::CmpLtU32 => VectorCompareOp::CmpLtU32,
Self::CmpEqU32 => VectorCompareOp::CmpEqU32,
Self::CmpLeU32 => VectorCompareOp::CmpLeU32,
Self::CmpGtU32 => VectorCompareOp::CmpGtU32,
Self::CmpNeU32 => VectorCompareOp::CmpNeU32,
Self::CmpGeU32 => VectorCompareOp::CmpGeU32,
Self::CmpFI32 => VectorCompareOp::CmpFI32,
Self::CmpTI32 => VectorCompareOp::CmpTI32,
Self::CmpFU32 => VectorCompareOp::CmpFU32,
Self::CmpTU32 => VectorCompareOp::CmpTU32,
}
}
/// Assembler name of the VOP3 encoding, as LLVM prints it.
pub const fn assembly_name(self) -> &'static str {
match self {
Self::CmpLtI32 => "v_cmp_lt_i32_e64",
Self::CmpEqI32 => "v_cmp_eq_i32_e64",
Self::CmpLeI32 => "v_cmp_le_i32_e64",
Self::CmpGtI32 => "v_cmp_gt_i32_e64",
Self::CmpNeI32 => "v_cmp_ne_i32_e64",
Self::CmpGeI32 => "v_cmp_ge_i32_e64",
Self::CmpLtU32 => "v_cmp_lt_u32_e64",
Self::CmpEqU32 => "v_cmp_eq_u32_e64",
Self::CmpLeU32 => "v_cmp_le_u32_e64",
Self::CmpGtU32 => "v_cmp_gt_u32_e64",
Self::CmpNeU32 => "v_cmp_ne_u32_e64",
Self::CmpGeU32 => "v_cmp_ge_u32_e64",
Self::CmpFI32 => "v_cmp_f_i32_e64",
Self::CmpTI32 => "v_cmp_t_i32_e64",
Self::CmpFU32 => "v_cmp_f_u32_e64",
Self::CmpTU32 => "v_cmp_t_u32_e64",
}
}
/// The validated registry row of this encoding.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::CmpLtI32 => 151,
Self::CmpEqI32 => 152,
Self::CmpLeI32 => 153,
Self::CmpGtI32 => 154,
Self::CmpNeI32 => 155,
Self::CmpGeI32 => 156,
Self::CmpLtU32 => 157,
Self::CmpEqU32 => 158,
Self::CmpLeU32 => 159,
Self::CmpGtU32 => 160,
Self::CmpNeU32 => 161,
Self::CmpGeU32 => 162,
Self::CmpFI32 => 163,
Self::CmpTI32 => 164,
Self::CmpFU32 => 165,
Self::CmpTU32 => 166,
}]
}
}
/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorAluVop3Op {
/// `v_add_nc_u32_e64` (VOP3 opcode 293).
AddNcU32,
/// `v_mul_i32_i24_e64` (VOP3 opcode 265).
MulI32I24,
/// `v_mul_hi_i32_i24_e64` (VOP3 opcode 266).
MulHiI32I24,
/// `v_mul_u32_u24_e64` (VOP3 opcode 267).
MulU32U24,
/// `v_mul_hi_u32_u24_e64` (VOP3 opcode 268).
MulHiU32U24,
/// `v_min_i32_e64` (VOP3 opcode 273).
MinI32,
/// `v_max_i32_e64` (VOP3 opcode 274).
MaxI32,
/// `v_min_u32_e64` (VOP3 opcode 275).
MinU32,
/// `v_max_u32_e64` (VOP3 opcode 276).
MaxU32,
/// `v_xnor_b32_e64` (VOP3 opcode 286).
XnorB32,
/// `v_sub_nc_u32_e64` (VOP3 opcode 294).
SubNcU32,
/// `v_subrev_nc_u32_e64` (VOP3 opcode 295).
SubrevNcU32,
}
impl VectorAluVop3Op {
/// Every variant, in registry order.
pub const ALL: [Self; 12] = [
Self::AddNcU32,
Self::MulI32I24,
Self::MulHiI32I24,
Self::MulU32U24,
Self::MulHiU32U24,
Self::MinI32,
Self::MaxI32,
Self::MinU32,
Self::MaxU32,
Self::XnorB32,
Self::SubNcU32,
Self::SubrevNcU32,
];
/// Selects the variant from the first word of its VOP3 encoding: the
/// encoding bits (mask 0xfc00_0000) and then the OP field (bits
/// 16-25). `None` for undeclared opcodes.
pub const fn from_word(word: u32) -> Option<Self> {
if word & 0xfc00_0000 != 0xd400_0000 {
return None;
}
match (word >> 16) & 0x3ff {
265 => Some(Self::MulI32I24),
266 => Some(Self::MulHiI32I24),
267 => Some(Self::MulU32U24),
268 => Some(Self::MulHiU32U24),
273 => Some(Self::MinI32),
274 => Some(Self::MaxI32),
275 => Some(Self::MinU32),
276 => Some(Self::MaxU32),
286 => Some(Self::XnorB32),
293 => Some(Self::AddNcU32),
294 => Some(Self::SubNcU32),
295 => Some(Self::SubrevNcU32),
_ => None,
}
}
@@ -3451,6 +3648,17 @@ impl VectorAluVop3Op {
pub const fn base(self) -> VectorAluOp {
match self {
Self::AddNcU32 => VectorAluOp::AddNcU32,
Self::MulI32I24 => VectorAluOp::MulI32I24,
Self::MulHiI32I24 => VectorAluOp::MulHiI32I24,
Self::MulU32U24 => VectorAluOp::MulU32U24,
Self::MulHiU32U24 => VectorAluOp::MulHiU32U24,
Self::MinI32 => VectorAluOp::MinI32,
Self::MaxI32 => VectorAluOp::MaxI32,
Self::MinU32 => VectorAluOp::MinU32,
Self::MaxU32 => VectorAluOp::MaxU32,
Self::XnorB32 => VectorAluOp::XnorB32,
Self::SubNcU32 => VectorAluOp::SubNcU32,
Self::SubrevNcU32 => VectorAluOp::SubrevNcU32,
}
}
@@ -3458,19 +3666,41 @@ impl VectorAluVop3Op {
pub const fn assembly_name(self) -> &'static str {
match self {
Self::AddNcU32 => "v_add_nc_u32_e64",
Self::MulI32I24 => "v_mul_i32_i24_e64",
Self::MulHiI32I24 => "v_mul_hi_i32_i24_e64",
Self::MulU32U24 => "v_mul_u32_u24_e64",
Self::MulHiU32U24 => "v_mul_hi_u32_u24_e64",
Self::MinI32 => "v_min_i32_e64",
Self::MaxI32 => "v_max_i32_e64",
Self::MinU32 => "v_min_u32_e64",
Self::MaxU32 => "v_max_u32_e64",
Self::XnorB32 => "v_xnor_b32_e64",
Self::SubNcU32 => "v_sub_nc_u32_e64",
Self::SubrevNcU32 => "v_subrev_nc_u32_e64",
}
}
/// The validated registry row of this encoding.
pub fn semantics(self) -> &'static FormSemantics {
&FORMS[match self {
Self::AddNcU32 => 151,
Self::AddNcU32 => 167,
Self::MulI32I24 => 168,
Self::MulHiI32I24 => 169,
Self::MulU32U24 => 170,
Self::MulHiU32U24 => 171,
Self::MinI32 => 172,
Self::MaxI32 => 173,
Self::MinU32 => 174,
Self::MaxU32 => 175,
Self::XnorB32 => 176,
Self::SubNcU32 => 177,
Self::SubrevNcU32 => 178,
}]
}
}
/// Identity of every registry form and encoding variant, in registry order.
pub const FORM_IDS: [(&str, EncodingFamily); 152] = [
pub const FORM_IDS: [(&str, EncodingFamily); 179] = [
("S_ADD_U32", EncodingFamily::Sop2),
("S_SUB_U32", EncodingFamily::Sop2),
("S_ADD_I32", EncodingFamily::Sop2),
@@ -3622,11 +3852,38 @@ pub const FORM_IDS: [(&str, EncodingFamily); 152] = [
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
("S_WAITCNT", EncodingFamily::Sopp),
("V_CMP_LT_I32", EncodingFamily::Vop3),
("V_CMP_EQ_I32", EncodingFamily::Vop3),
("V_CMP_LE_I32", EncodingFamily::Vop3),
("V_CMP_GT_I32", EncodingFamily::Vop3),
("V_CMP_NE_I32", EncodingFamily::Vop3),
("V_CMP_GE_I32", EncodingFamily::Vop3),
("V_CMP_LT_U32", EncodingFamily::Vop3),
("V_CMP_EQ_U32", EncodingFamily::Vop3),
("V_CMP_LE_U32", EncodingFamily::Vop3),
("V_CMP_GT_U32", EncodingFamily::Vop3),
("V_CMP_NE_U32", EncodingFamily::Vop3),
("V_CMP_GE_U32", EncodingFamily::Vop3),
("V_CMP_F_I32", EncodingFamily::Vop3),
("V_CMP_T_I32", EncodingFamily::Vop3),
("V_CMP_F_U32", EncodingFamily::Vop3),
("V_CMP_T_U32", EncodingFamily::Vop3),
("V_ADD_NC_U32", EncodingFamily::Vop3),
("V_MUL_I32_I24", EncodingFamily::Vop3),
("V_MUL_HI_I32_I24", EncodingFamily::Vop3),
("V_MUL_U32_U24", EncodingFamily::Vop3),
("V_MUL_HI_U32_U24", EncodingFamily::Vop3),
("V_MIN_I32", EncodingFamily::Vop3),
("V_MAX_I32", EncodingFamily::Vop3),
("V_MIN_U32", EncodingFamily::Vop3),
("V_MAX_U32", EncodingFamily::Vop3),
("V_XNOR_B32", EncodingFamily::Vop3),
("V_SUB_NC_U32", EncodingFamily::Vop3),
("V_SUBREV_NC_U32", EncodingFamily::Vop3),
];
/// One validated row per registry form, in registry order.
pub static FORMS: [FormSemantics; 152] = [
pub static FORMS: [FormSemantics; 179] = [
FormSemantics {
name: "S_ADD_U32",
family: EncodingFamily::Sop2,
@@ -6798,6 +7055,342 @@ pub static FORMS: [FormSemantics; 152] = [
spec: &[SpecRef { document: Document::Guide, section: "12.5", page: 125 }, SpecRef { document: Document::Guide, section: "13.1.5", page: 245 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_LT_I32",
family: EncodingFamily::Vop3,
opcode: 129,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::Less),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_EQ_I32",
family: EncodingFamily::Vop3,
opcode: 130,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::Equal),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_LE_I32",
family: EncodingFamily::Vop3,
opcode: 131,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::LessOrEqual),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_GT_I32",
family: EncodingFamily::Vop3,
opcode: 132,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::Greater),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_NE_I32",
family: EncodingFamily::Vop3,
opcode: 133,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::NotEqual),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_GE_I32",
family: EncodingFamily::Vop3,
opcode: 134,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::GreaterOrEqual),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_LT_U32",
family: EncodingFamily::Vop3,
opcode: 193,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::Less),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_EQ_U32",
family: EncodingFamily::Vop3,
opcode: 194,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::Equal),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_LE_U32",
family: EncodingFamily::Vop3,
opcode: 195,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::LessOrEqual),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_GT_U32",
family: EncodingFamily::Vop3,
opcode: 196,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::Greater),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_NE_U32",
family: EncodingFamily::Vop3,
opcode: 197,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::NotEqual),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_GE_U32",
family: EncodingFamily::Vop3,
opcode: 198,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::GreaterOrEqual),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_F_I32",
family: EncodingFamily::Vop3,
opcode: 128,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::False),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_T_I32",
family: EncodingFamily::Vop3,
opcode: 135,
operation: Operation::Compare,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::True),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_F_U32",
family: EncodingFamily::Vop3,
opcode: 192,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::False),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_CMP_T_U32",
family: EncodingFamily::Vop3,
opcode: 199,
operation: Operation::Compare,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: Some(CompareRelation::True),
scc: SccEffect::Unchanged,
vcc: MaskEffect::SdstLaneMask,
exec: MaskEffect::Unchanged,
wave: Wave::Wave32,
operands: OperandRule::Vop3CmpVgpr2,
spec: &[SpecRef { document: Document::Guide, section: "3.9", page: 19 }, SpecRef { document: Document::Guide, section: "13.3.4", page: 257 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_ADD_NC_U32",
family: EncodingFamily::Vop3,
@@ -6819,4 +7412,235 @@ pub static FORMS: [FormSemantics; 152] = [
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MUL_I32_I24",
family: EncodingFamily::Vop3,
opcode: 265,
operation: Operation::Multiply24,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 131 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MUL_HI_I32_I24",
family: EncodingFamily::Vop3,
opcode: 266,
operation: Operation::MultiplyHigh24,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MUL_U32_U24",
family: EncodingFamily::Vop3,
opcode: 267,
operation: Operation::Multiply24,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MUL_HI_U32_U24",
family: EncodingFamily::Vop3,
opcode: 268,
operation: Operation::MultiplyHigh24,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 132 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MIN_I32",
family: EncodingFamily::Vop3,
opcode: 273,
operation: Operation::Minimum,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MAX_I32",
family: EncodingFamily::Vop3,
opcode: 274,
operation: Operation::Maximum,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MIN_U32",
family: EncodingFamily::Vop3,
opcode: 275,
operation: Operation::Minimum,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_MAX_U32",
family: EncodingFamily::Vop3,
opcode: 276,
operation: Operation::Maximum,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 133 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_XNOR_B32",
family: EncodingFamily::Vop3,
opcode: 286,
operation: Operation::Xnor,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_SUB_NC_U32",
family: EncodingFamily::Vop3,
opcode: 294,
operation: Operation::Sub,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: false,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "V_SUBREV_NC_U32",
family: EncodingFamily::Vop3,
opcode: 295,
operation: Operation::Sub,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
shift_amount: 0,
swap_sources: true,
source_bits: 32,
relation: None,
scc: SccEffect::Unchanged,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Vop3Vgpr2,
spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
];
+40 -3
View File
@@ -2,11 +2,12 @@
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
use xenora_isa::semantics::{
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect,
Signedness, Wave,
};
use xenora_isa::{
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
};
#[test]
@@ -261,8 +262,38 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
assert_eq!(row.swap_sources, base.swap_sources);
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
}
for base_op in VectorCompareOp::ALL {
let base = base_op.semantics();
let mut variants = VectorCompareVop3Op::ALL
.into_iter()
.filter(|op| op.base() == base_op);
if base.width != 32 {
assert_eq!(variants.next(), None, "{}", base.name);
continue;
}
let op = variants
.next()
.expect("32-bit VOPC form must have a VOP3A encoding");
assert_eq!(variants.next(), None);
let row = op.semantics();
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
assert_eq!(row.operation, base.operation);
assert_eq!(row.signedness, base.signedness);
assert_eq!(row.relation, base.relation);
assert_eq!(row.scc, SccEffect::Unchanged);
assert_eq!(row.exec, MaskEffect::Unchanged);
assert_eq!(row.wave, Wave::Wave32);
assert_eq!(row.width, 32);
assert_eq!(row.vcc, MaskEffect::SdstLaneMask);
assert_eq!(row.operands, OperandRule::Vop3CmpVgpr2);
assert_eq!(op.assembly_name(), format!("{}_e64", base_op.mnemonic()));
}
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
VectorAluVop3Op::from_word(word).map(|op| op.semantics().name)
let alu = VectorAluVop3Op::from_word(word);
let compare = VectorCompareVop3Op::from_word(word);
assert!(alu.is_none() || compare.is_none(), "{word:#x}");
alu.map(|op| op.semantics().name)
.or_else(|| compare.map(|op| op.semantics().name))
});
// No first word of the other 64-bit families (VOP3B shares VOP3's
// encoding bits) selects a variant.
@@ -276,5 +307,11 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
"{}",
meta.name
);
assert_eq!(
VectorCompareVop3Op::from_word(meta.bits as u32),
None,
"{}",
meta.name
);
}
}
+1
View File
@@ -16,6 +16,7 @@ gpu-tests = []
[dependencies]
libc = "0.2"
sha2 = "0.10"
xenora-texture = { path = "../texture" }
[dev-dependencies]
xenora-metal = { path = "../metal" }
+80 -11
View File
@@ -1,5 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Synthetic interpreter and DBT timings.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
//! and run the executable named by the benchmark's compiler-artifact message.
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
@@ -88,14 +95,25 @@ fn check(result: ExecutionResult) {
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
}
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
// Interpolate between adjacent values at rank (n - 1) * fraction.
let rank = (sorted.len() - 1) as f64 * fraction;
let lower = sorted[rank.floor() as usize];
let upper = sorted[rank.ceil() as usize];
lower + (upper - lower).mul_f64(rank.fract())
}
fn report(label: &str, samples: &mut [Duration]) {
samples.sort_unstable();
let median = samples[samples.len() / 2];
let median = percentile(samples, 0.50);
let p95 = percentile(samples, 0.95);
let p99 = percentile(samples, 0.99);
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
let min = samples[0];
let max = samples[samples.len() - 1];
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
println!(
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
samples.len()
);
}
@@ -104,6 +122,8 @@ fn main() {
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
let warmup_count = std::env::var("XENORA_DBT_BENCH_WARMUP")
.map_or(10, |value| value.parse::<usize>().expect("warmup count"));
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
for _ in 0..ADDS {
@@ -124,38 +144,52 @@ fn main() {
let mut warm = Vec::with_capacity(sample_count);
let mut cold_metrics = None;
for _ in 0..sample_count {
for record in
std::iter::repeat_n(false, warmup_count).chain(std::iter::repeat_n(true, sample_count))
{
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
let start = Instant::now();
let result = black_box(interp.run());
interpreter.push(start.elapsed());
let interpreter_time = start.elapsed();
check(result);
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
cold.push(start.elapsed());
let cold_time = start.elapsed();
check(result);
assert!(dbt.metrics.blocks_compiled > 0);
assert_eq!(dbt.metrics.cache_hits, 0);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
cold_metrics = Some(dbt.metrics);
let metrics = dbt.metrics;
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
warm.push(start.elapsed());
let warm_time = start.elapsed();
check(result);
assert_eq!(
Some(dbt.metrics.blocks_compiled),
cold_metrics.map(|m| m.blocks_compiled)
);
assert_eq!(dbt.metrics.blocks_compiled, metrics.blocks_compiled);
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
if record {
interpreter.push(interpreter_time);
cold.push(cold_time);
warm.push(warm_time);
cold_metrics = Some(metrics);
}
}
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
println!("{warmup_count} warmup rounds excluded (XENORA_DBT_BENCH_WARMUP, default 10)");
println!(
"Cold DBT includes translation with a fresh engine; warm DBT reuses that engine's cache."
);
println!(
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
);
println!("Even sample counts use the midpoint of the two middle values for the median.");
report("Interpreter", &mut interpreter);
report("Cold DBT", &mut cold);
report("Warm DBT", &mut warm);
@@ -165,3 +199,38 @@ fn main() {
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
);
}
#[cfg(test)]
mod tests {
#[test]
fn single_sample_has_no_spread() {
use super::{Duration, percentile};
let samples = [Duration::from_micros(50)];
for fraction in [0.25, 0.50, 0.75, 0.95, 0.99] {
assert_eq!(percentile(&samples, fraction), samples[0]);
}
}
#[test]
fn percentiles_interpolate_across_even_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 30, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(25));
assert_eq!(percentile(&samples, 0.95), Duration::from_nanos(89_500));
assert_eq!(percentile(&samples, 0.99), Duration::from_nanos(97_900));
assert_eq!(
percentile(&samples, 0.75) - percentile(&samples, 0.25),
Duration::from_nanos(30_000)
);
}
#[test]
fn median_uses_the_middle_of_odd_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
}
}
+128 -14
View File
@@ -582,22 +582,35 @@ impl Arm64Assembler {
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
}
/// Load a full 64-bit constant into register Xd.
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
let w0 = (val & 0xffff) as u16;
let w1 = ((val >> 16) & 0xffff) as u16;
let w2 = ((val >> 32) & 0xffff) as u16;
let w3 = ((val >> 48) & 0xffff) as u16;
/// MOVN (64-bit with shift): MOVN Xd, #imm16, LSL #shift writes
/// NOT (imm16 << shift), so every other halfword becomes 0xFFFF.
pub fn movn_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
let hw = (shift_idx & 3) as u32;
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
}
self.movz_64(xd, w0, 0);
if w1 != 0 || (w2 == 0 && w3 == 0) {
self.movk_64(xd, w1, 1);
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
/// MOVN plus MOVK instructions: one for each halfword that differs from
/// the background the first instruction leaves, and always at least one.
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
/// when more halfwords are 0xFFFF than zero.
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
let zeros = halves.iter().filter(|&&h| h == 0).count();
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
let background = if ones > zeros { 0xffff } else { 0 };
// The first halfword that differs from the background, or halfword 0
// when none does (val is 0 or all ones).
let first = halves.iter().position(|&h| h != background).unwrap_or(0);
if background == 0 {
self.movz_64(xd, halves[first], first as u8);
} else {
self.movn_64(xd, !halves[first], first as u8);
}
if w2 != 0 || w3 != 0 {
self.movk_64(xd, w2, 2);
}
if w3 != 0 {
self.movk_64(xd, w3, 3);
for (index, &half) in halves.iter().enumerate().skip(first + 1) {
if half != background {
self.movk_64(xd, half, index as u8);
}
}
}
@@ -786,4 +799,105 @@ mod tests {
asm.str_uoff_32(X0, X19, 136);
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
}
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
const IMMEDIATE_EDGES: [u64; 16] = [
0,
1,
0xffff,
0x1_0000,
0x8000_0000,
0xffff_ffff,
0x1_0000_0000,
0x1234_0000_0000_0000,
0x0000_0001_0000_0005,
0x1234_5678_9abc_def0,
0x7fff_ffff_ffff_ffff,
0x8000_0000_0000_0000,
0xffff_0000_ffff_ffff,
0xffff_ffff_edcc_5678,
0xffff_ffff_ffff_1234,
u64::MAX,
];
#[test]
fn immediate_sequences_match_llvm_encodings() {
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
let cases: &[(u64, &[u32])] = &[
(0, &[0xd2800000]), // movz x0, #0
(u64::MAX, &[0x92800000]), // movn x0, #0
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
(0x0000_0001_0000_0005, &[0xd28000a0, 0xf2c00020]), // movz #5; movk #1, lsl #32
// movn x0, #0xa987; movk x0, #0xedcc, lsl #16
(0xffff_ffff_edcc_5678, &[0x929530e0, 0xf2bdb980]),
];
for &(value, expected) in cases {
let mut asm = Arm64Assembler::new();
asm.load_imm_64(X0, value);
assert_eq!(asm.instructions(), expected, "{value:#x}");
}
// movz x9, #0xdef0; movk x9, #0x9abc, lsl #16; #0x5678, lsl #32;
// #0x1234, lsl #48
let mut asm = Arm64Assembler::new();
asm.load_imm_64(X9, 0x1234_5678_9abc_def0);
assert_eq!(
asm.instructions(),
&[0xd29bde09, 0xf2b35789, 0xf2cacf09, 0xf2e24689]
);
}
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
fn shortest_wide_move(value: u64) -> usize {
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
let not_zero = halves.clone().filter(|&h| h != 0).count();
let not_ones = halves.filter(|&h| h != 0xffff).count();
not_zero.min(not_ones).max(1)
}
#[test]
fn immediates_run_on_the_host_and_use_the_fewest_wide_moves() {
let mut values = IMMEDIATE_EDGES.to_vec();
let mut state = 0x9e37_79b9_7f4a_7c15u64;
for _ in 0..512 {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
let raw = state.wrapping_mul(0x2545_f491_4f6c_dd1d);
// Force some halfwords to zero or all ones so both MOVZ and MOVN
// sequences of every length occur.
let mut value = raw;
for half in 0..4 {
match (raw >> (60 - 2 * half)) & 3 {
0 => value &= !(0xffff << (16 * half)),
1 => value |= 0xffff << (16 * half),
_ => {}
}
}
values.push(value);
}
let mut jit = crate::jit::JitMemory::new(64 * 1024).unwrap();
for value in values {
for register in [X0, X9] {
let mut asm = Arm64Assembler::new();
asm.load_imm_64(register, value);
assert_eq!(
asm.instructions().len(),
shortest_wide_move(value),
"{value:#x}"
);
if register != X0 {
asm.mov_reg_64(X0, register);
}
asm.ret();
let entry = jit.emit_block(asm.instructions()).unwrap();
// SAFETY: the block is a complete AAPCS64 leaf function that
// writes only X0 (and X9, a caller-saved register) and returns.
let function: extern "C" fn() -> u64 = unsafe { std::mem::transmute(entry) };
assert_eq!(function(), value, "{value:#x} in x{register}");
}
}
}
}
+203
View File
@@ -2267,4 +2267,207 @@ mod tests {
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
);
}
/// Intel SDM Volume 1, section 3.4.3.1: for `SUB` and `CMP`, `CF` is the
/// borrow out of the most significant bit. `JB` is `CF = 1`, `JAE` is
/// `CF = 0`, `JBE` is `CF = 1 or ZF = 1` and `JA` is `CF = 0 and ZF = 0`.
///
/// ARM64 reports the inverse: `SUBS` sets `C` when the subtraction does
/// *not* borrow, and its `HI`/`LS` conditions are defined on that same
/// inverted carry. These four x86 conditions therefore cannot be taken
/// from an ARM64 condition code without translating the borrow first,
/// which makes them the ones to pin at the boundaries.
/// One unsigned condition: the low nibble pair as encoded in the `0x70`
/// block, and the rule that decides it from CF and ZF.
type UnsignedCondition = (u8, fn(bool, bool) -> bool);
const UNSIGNED_CONDITIONS: [UnsignedCondition; 4] = [
(0x72, |cf, _zf| cf), // JB, JC, JNAE
(0x73, |cf, _zf| !cf), // JAE, JNB, JNC
(0x76, |cf, zf| cf || zf), // JBE, JNA
(0x77, |cf, zf| !cf && !zf), // JA, JNBE
];
/// Build `<op> eax, ebx` (or `rax, rbx`) followed by the short or near form
/// of `condition`. The not-taken path writes 1 to `ECX` and halts, the
/// taken path writes 2. A near branch targets offset 140, which a `disp8`
/// cannot reach, so the two encodings are exercised separately.
fn unsigned_branch_program(op: [u8; 2], condition: u8, wide: bool, near: bool) -> Vec<u8> {
let mut code = Vec::new();
if wide {
code.push(0x48); // REX.W
}
code.extend_from_slice(&op); // cmp/sub eax, ebx
let jcc = code.len();
if near {
// The near form is `0F 8x`, where x is the low nibble of the
// short form's opcode.
code.extend_from_slice(&[0x0F, 0x80 | (condition & 0x0F), 0, 0, 0, 0]);
} else {
code.extend_from_slice(&[condition, 0]);
}
code.extend_from_slice(&[0xB9, 1, 0, 0, 0]); // mov ecx, 1
code.push(0xF4); // hlt
let target = if near { 140 } else { code.len() };
while code.len() < target {
code.push(0x90); // nop
}
code.extend_from_slice(&[0xB9, 2, 0, 0, 0]); // mov ecx, 2
code.push(0xF4); // hlt
let next = jcc + if near { 6 } else { 2 };
let displacement = target as i64 - next as i64;
if near {
code[jcc + 2..jcc + 6].copy_from_slice(&(displacement as i32).to_le_bytes());
} else {
code[jcc + 1] = displacement as i8 as u8;
}
code
}
/// Run one branch program and return `(ecx, cf, zf)`.
fn run_unsigned_branch(code: &[u8], left: u64, right: u64) -> (u64, bool, bool) {
let (mut engine, mut cpu, mut memory) = fixture(code);
cpu.set(Register::Rax, left);
cpu.set(Register::Rbx, right);
let result = engine.run(&mut cpu, &mut memory, 32);
assert_eq!(result.exit_reason, ExitReason::Halt);
// Either the two-instruction taken path or the two-instruction
// not-taken path runs after the compare and the branch.
assert_eq!(result.instructions_executed, 4);
// The compare, the branch and the halting move all run as translated
// ARM64, not through the shared interpreter.
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
(cpu.get(Register::Rcx), cpu.flags.cf, cpu.flags.zf)
}
/// The four unsigned conditions, at both ends of the 32-bit and 64-bit
/// ranges, in the short and the near encoding. Expected flags and
/// outcomes come from the SDM rules above, not from the lowering.
#[test]
fn unsigned_branch_conditions_follow_the_borrow_at_every_boundary() {
const CMP: [u8; 2] = [0x39, 0xD8];
let cases: &[(bool, u64, u64)] = &[
// 32-bit: zero, one, equal operands, both ends of the range, and
// the pair where the sign bit flips but the unsigned order holds.
(false, 0, 0),
(false, 0, 1),
(false, 1, 0),
(false, 0xFFFF_FFFF, 0xFFFF_FFFF),
(false, 0xFFFF_FFFF, 0),
(false, 0, 0xFFFF_FFFF),
(false, 0x7FFF_FFFF, 0x8000_0000),
(false, 0x8000_0000, 0x7FFF_FFFF),
// The same boundaries at 64 bits, plus a subtraction that clears
// the sign bit without borrowing.
(true, 0, 0),
(true, 0, 1),
(true, 1, 0),
(true, u64::MAX, u64::MAX),
(true, u64::MAX, 0),
(true, 0, u64::MAX),
(true, 0x7FFF_FFFF_FFFF_FFFF, 0x8000_0000_0000_0000),
(true, 0x8000_0000_0000_0000, 0x7FFF_FFFF_FFFF_FFFF),
(true, 0x8000_0000_0000_0000, 1),
];
for &(wide, left, right) in cases {
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
let (left, right) = (left & mask, right & mask);
// SDM: CF is the borrow out of the most significant bit, ZF is a
// zero result. Both follow from the operands alone.
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
for &near in &[false, true] {
let code = unsigned_branch_program(CMP, condition, wide, near);
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
let case = format!(
"{condition:#04x} {:#x} {:#x} {}",
left,
right,
if near { "near" } else { "short" }
);
assert_eq!(got_cf, cf, "{case}: CF");
assert_eq!(got_zf, zf, "{case}: ZF");
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
}
}
}
}
/// `SUB` is the other producer of the carry these conditions read, and the
/// one where the ARM64 carry is inverted: `0 - 1` borrows, while
/// `0x8000_0000_0000_0000 - 1` does not borrow even though it clears the
/// sign bit.
#[test]
fn subtract_borrow_into_and_out_of_the_high_bit_feeds_the_unsigned_branches() {
const SUB: [u8; 2] = [0x29, 0xD8];
let cases: &[(bool, u64, u64)] = &[
(false, 0, 1),
(false, 0x8000_0000, 1),
(true, 0, 1),
(true, 0x8000_0000_0000_0000, 1),
];
for &(wide, left, right) in cases {
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
let (left, right) = (left & mask, right & mask);
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
for &near in &[false, true] {
let code = unsigned_branch_program(SUB, condition, wide, near);
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
let case = format!(
"{condition:#04x} {:#x} {:#x} {}",
left,
right,
if near { "near" } else { "short" }
);
assert_eq!(got_cf, cf, "{case}: CF");
assert_eq!(got_zf, zf, "{case}: ZF");
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
}
}
}
}
/// The carry these conditions read is produced in one translated block and
/// consumed in the next. A lowering that left it in the host's condition
/// flags would pass the single-block cases above and fail here.
#[test]
fn unsigned_branch_reads_flags_stored_by_a_previous_block() {
const CMP: [u8; 2] = [0x39, 0xD8];
let cases: &[(bool, u64, u64)] = &[
(false, 0, 0), // CF = 0, ZF = 1
(false, 0, 1), // CF = 1, ZF = 0
(false, 0xFFFF_FFFF, 0), // CF = 0, ZF = 0
(true, 0x8000_0000_0000_0000, 1), // CF = 0 although the sign bit clears
];
for &(wide, left, right) in cases {
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
let code = unsigned_branch_program(CMP, condition, wide, false);
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rax, left);
cpu.set(Register::Rbx, right);
// One instruction per run: the compare is translated as a
// one-instruction block, so the branch is compiled separately
// and can only read the flags the first block stored.
let first = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(first.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(cpu.rip, ENTRY + if wide { 3 } else { 2 });
assert_eq!((cpu.flags.cf, cpu.flags.zf), (cf, zf));
let second = engine.run(&mut cpu, &mut memory, 8);
assert_eq!(second.exit_reason, ExitReason::Halt);
assert_eq!(second.instructions_executed, 3);
assert_eq!(cpu.get(Register::Rcx), if taken { 2 } else { 1 });
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
}
}
}
}
File diff suppressed because it is too large. Load diff
+221 -3
View File
@@ -506,9 +506,20 @@ impl GuestMemory {
/// Read an instruction byte from guest memory, verifying execute permission.
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
let mut buf = [0u8; 1];
self.read_checked(address, &mut buf, Some("execute"))?;
Ok(buf[0])
address.checked_add(1).ok_or(MemoryError::Overflow)?;
let region = self
.regions
.iter()
.find(|region| region.base + region.data.len() as u64 > address)
.filter(|region| region.base <= address)
.ok_or(MemoryError::UnmappedAddress(address))?;
if !region.permissions.execute {
return Err(MemoryError::PermissionViolation {
address,
required: "execute",
});
}
Ok(region.data[(address - region.base) as usize])
}
/// Read a 64-bit integer (little endian) from guest memory.
@@ -627,3 +638,210 @@ mod tests {
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, moved), Some(1));
}
}
#[cfg(test)]
mod instruction_fetch_tests {
use super::{MemoryPermissions as P, *};
fn denied(address: u64) -> Result<u8, MemoryError> {
Err(MemoryError::PermissionViolation {
address,
required: "execute",
})
}
fn missing(address: u64) -> Result<u8, MemoryError> {
Err(MemoryError::UnmappedAddress(address))
}
#[test]
fn fetch_reports_overflow_before_lookup() {
let m = GuestMemory::new();
for at in [0, 1, 0x1000, u64::MAX - 1] {
assert_eq!(m.fetch_instruction_byte(at), missing(at));
}
assert_eq!(
m.fetch_instruction_byte(u64::MAX),
Err(MemoryError::Overflow)
);
let mut m = GuestMemory::new();
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
assert_eq!(
m.fetch_instruction_byte(u64::MAX),
Err(MemoryError::Overflow)
);
}
#[test]
fn fetch_checks_execute_permission_for_every_byte_value() {
let bytes: Vec<u8> = (0..=255).collect();
for flags in 0..8 {
let permission = P {
read: flags & 1 != 0,
write: flags & 2 != 0,
execute: flags & 4 != 0,
};
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, bytes.len(), permission, &bytes)
.unwrap();
for (offset, byte) in bytes.iter().enumerate() {
let at = 0x1000 + offset as u64;
assert_eq!(
m.fetch_instruction_byte(at),
if flags & 4 != 0 {
Ok(*byte)
} else {
denied(at)
},
"flags={flags}, at={at:x}"
);
}
}
}
#[test]
fn fetch_handles_sparse_and_out_of_order_mappings() {
let mut m = GuestMemory::new();
m.map_region_with_data(0x3000, 2, P::READ_EXECUTE, &[0xc1, 0xc2])
.unwrap();
m.map_region_with_data(0, 2, P::READ_EXECUTE, &[0x01, 0x02])
.unwrap();
m.map_region_with_data(0x2000, 1, P::READ_ONLY, &[0xb1])
.unwrap();
m.map_region_with_data(0x1000, 2, P::READ_EXECUTE, &[0xa1, 0xa2])
.unwrap();
for (at, byte) in [
(0, 1),
(1, 2),
(0x1000, 0xa1),
(0x1001, 0xa2),
(0x3000, 0xc1),
(0x3001, 0xc2),
] {
assert_eq!(m.fetch_instruction_byte(at), Ok(byte));
}
assert_eq!(m.fetch_instruction_byte(0x2000), denied(0x2000));
for at in [2, 0xfff, 0x1002, 0x2001, 0x2fff, 0x3002] {
assert_eq!(m.fetch_instruction_byte(at), missing(at));
}
}
#[test]
fn fetch_ignores_empty_mappings_at_shared_boundaries() {
for zero_first in [false, true] {
for execute in [false, true] {
let mut m = GuestMemory::new();
let permission = P {
read: false,
write: false,
execute,
};
if zero_first {
for _ in 0..7 {
m.map_region(0x1000, 0, P::READ_WRITE_EXECUTE).unwrap();
}
}
m.map_region_with_data(0x1000, 2, permission, &[0x34, 0x56])
.unwrap();
for _ in 0..7 {
m.map_region(0x1000, 0, P::NO_ACCESS).unwrap();
}
for _ in 0..7 {
m.map_region(0x1002, 0, P::READ_WRITE_EXECUTE).unwrap();
}
for (at, byte) in [(0x1000, 0x34), (0x1001, 0x56)] {
assert_eq!(
m.fetch_instruction_byte(at),
if execute { Ok(byte) } else { denied(at) }
);
}
assert_eq!(m.fetch_instruction_byte(0x1002), missing(0x1002));
}
}
let mut m = GuestMemory::new();
for at in [1, 1, 2, 0x1000] {
m.map_region(at, 0, P::READ_WRITE_EXECUTE).unwrap();
}
for at in [0, 1, 2, 3, 0x1000] {
assert_eq!(m.fetch_instruction_byte(at), missing(at));
}
}
#[test]
fn fetch_checks_adjacent_mapping_permissions() {
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0xa5])
.unwrap();
m.map_region_with_data(0x1001, 1, P::READ_WRITE, &[0x5a])
.unwrap();
m.map_region(0x1001, 0, P::READ_EXECUTE).unwrap();
m.map_region_with_data(0x1002, 1, P::READ_EXECUTE, &[0xc3])
.unwrap();
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0xa5));
assert_eq!(m.fetch_instruction_byte(0x1001), denied(0x1001));
assert_eq!(m.fetch_instruction_byte(0x1002), Ok(0xc3));
assert_eq!(m.fetch_instruction_byte(0x1003), missing(0x1003));
}
#[test]
fn fetch_handles_the_highest_region_end() {
let mut m = GuestMemory::new();
m.map_region_with_data(u64::MAX - 2, 2, P::READ_EXECUTE, &[0x12, 0x34])
.unwrap();
m.map_region(u64::MAX, 0, P::READ_EXECUTE).unwrap();
assert_eq!(
m.fetch_instruction_byte(u64::MAX - 3),
missing(u64::MAX - 3)
);
assert_eq!(m.fetch_instruction_byte(u64::MAX - 2), Ok(0x12));
assert_eq!(m.fetch_instruction_byte(u64::MAX - 1), Ok(0x34));
assert_eq!(
m.fetch_instruction_byte(u64::MAX),
Err(MemoryError::Overflow)
);
}
#[test]
fn fetch_observes_writes_clones_and_mapping_changes() {
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, 1, P::READ_WRITE_EXECUTE, &[0x11])
.unwrap();
let mut clone = m.clone();
m.write_u8(0x1000, 0x22).unwrap();
clone.write_u8(0x1000, 0x33).unwrap();
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0x22));
assert_eq!(clone.fetch_instruction_byte(0x1000), Ok(0x33));
let base = m
.map_virtual_allocation(0x4000, 1, P::READ_WRITE_EXECUTE)
.unwrap();
m.write_u8(base, 0x44).unwrap();
assert_eq!(m.fetch_instruction_byte(base), Ok(0x44));
assert!(m.release_virtual_allocation(base));
assert_eq!(m.fetch_instruction_byte(base), missing(base));
m.map_region_with_data(base, 1, P::READ_ONLY, &[0x55])
.unwrap();
assert_eq!(m.fetch_instruction_byte(base), denied(base));
assert_eq!(clone.fetch_instruction_byte(base), missing(base));
}
#[test]
fn fetch_keeps_first_mapping_priority_after_empty_heap_growth() {
// Existing private allocation methods can grow a zero allocation onto an
// earlier mapping at its base. The fetch-only patch must preserve the
// original mapping's priority even for this already-representable state.
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0x90])
.unwrap();
const BASE: u64 = 0x0000_0003_0000_0000;
m.map_region_with_data(BASE, 4, P::READ_EXECUTE, &[0x11, 0x22, 0x33, 0x44])
.unwrap();
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
assert_eq!(empty, BASE);
assert_eq!(
m.resize_heap_allocation(PROCESS_HEAP, empty, 2, true),
Ok(BASE)
);
assert_eq!(m.fetch_instruction_byte(BASE), Ok(0x11));
assert_eq!(m.fetch_instruction_byte(BASE + 1), Ok(0x22));
assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44));
}
}
+234 -1
View File
@@ -163,7 +163,6 @@ pub fn apply_relocations(
let reloc_type = (entry_val >> 12) as u8;
let offset_in_page = (entry_val & 0x0FFF) as u32;
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
report.total_entries += 1;
match reloc_type {
@@ -221,6 +220,17 @@ pub fn apply_relocations(
read_bytes += block_size as usize;
}
// Only these two types can reach a successful return. Build the public
// histogram once instead of searching its tree for every relocation.
for (kind, count) in [
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
] {
if count != 0 {
report.type_counts.insert(kind, count);
}
}
Ok(report)
}
@@ -274,3 +284,226 @@ fn find_reloc_directory(
Ok(Some((reloc_rva, reloc_size)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory::MemoryPermissions;
use crate::pe::PeSection;
use std::hint::black_box;
use std::time::Instant;
const PREFERRED: u64 = 0x140000000;
const LOADED: u64 = PREFERRED + 0x200000;
const DATA_RVA: u32 = 0x1000;
const DIRECTORY_RVA: u32 = 0x10000000;
const DIRECTORY_OFFSET: usize = 0x200;
// Original synthetic directory, laid out from Microsoft's PE Format,
// .reloc section: eight-byte block headers and two-byte type/offset words.
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
// Header fields and metadata are supplied directly: PE parsing is not timed.
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
for (page, entries) in blocks {
bytes.extend_from_slice(&page.to_le_bytes());
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
for entry in entries {
bytes.extend_from_slice(&entry.to_le_bytes());
}
}
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
let pe = ParsedPe {
machine: 0x8664,
number_of_sections: 1,
time_date_stamp: 0,
image_base: PREFERRED,
section_alignment: 4096,
file_alignment: 512,
size_of_image: DIRECTORY_RVA + size.max(4096),
size_of_headers: 512,
entry_point_rva: 0,
sections: vec![PeSection {
name: ".reloc".into(),
virtual_address: DIRECTORY_RVA,
virtual_size: size,
raw_data_ptr: DIRECTORY_OFFSET as u32,
raw_data_size: size,
characteristics: 0x40000040,
permissions: MemoryPermissions::READ_ONLY,
}],
};
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
LOADED + u64::from(DATA_RVA),
data.len(),
MemoryPermissions::READ_ONLY,
data,
)
.unwrap();
(pe, bytes, memory)
}
#[test]
fn counts_padding_and_rebases_read_only_targets() {
for (preferred, initial, expected) in [
(PREFERRED, 0x140001234, 0x140201234),
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
(LOADED - 8, u64::MAX - 3, 4),
(LOADED + 8, 3, u64::MAX - 4),
] {
let (mut pe, bytes, mut memory) =
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
pe.image_base = preferred;
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
assert_eq!(report.total_entries, 2);
assert_eq!(report.applied_dir64, 1);
assert_eq!(report.skipped_absolute, 1);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
}
}
#[test]
fn histogram_omits_types_that_did_not_occur() {
for (entries, counts) in [
(vec![], BTreeMap::new()),
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
] {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(report.type_counts, counts);
}
}
#[test]
fn preserves_duplicate_and_overlapping_entry_order() {
let (pe, bytes, mut memory) = fixture(
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
&[0; 16],
);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
// Two additions of 0x200000 at offset zero, then one at offset four.
let mut actual = [0; 16];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(
actual,
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
}
#[test]
fn overlapping_fields_observe_prior_carries_in_directory_order() {
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
for (entries, expected) in [
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
] {
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
pe.image_base = LOADED - 1;
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
let mut actual = [0; 12];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(actual, expected);
}
}
#[test]
fn preserves_prior_writes_and_rejects_unsupported_types() {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
assert_eq!(
apply_relocations(&pe, &bytes, LOADED, &mut memory),
Err(RelocationError::UnsupportedRelocationType(15))
);
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
}
#[test]
fn zero_delta_keeps_the_empty_report_without_parsing() {
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
pe.image_base = LOADED;
assert_eq!(
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
RelocationReport::default()
);
}
#[test]
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
fn relocation_profile() {
for pages in [1u32, 128] {
for padding_every in [0usize, 2, 1] {
let blocks: Vec<_> = (0..pages)
.map(|page| {
let entries = (0..512)
.map(|slot| {
let padding = padding_every != 0 && slot % padding_every == 0;
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
})
.collect();
(DATA_RVA + page * 4096, entries)
})
.collect();
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
let mut samples = Vec::new();
for run in 0..36 {
let mut memory = initial.clone();
let start = Instant::now();
let report = black_box(
apply_relocations(
black_box(&pe),
black_box(&bytes),
LOADED,
black_box(&mut memory),
)
.unwrap(),
);
let elapsed = start.elapsed().as_secs_f64() * 1e6;
assert_eq!(report.total_entries, pages as usize * 512);
let padding = match padding_every {
0 => 0,
2 => report.total_entries / 2,
_ => report.total_entries,
};
assert_eq!(report.skipped_absolute, padding);
assert_eq!(report.applied_dir64, report.total_entries - padding);
// Check every output against the fixture's independently specified pattern.
for slot in 0..pages as usize * 512 {
let expected = if padding_every != 0 && slot % padding_every == 0 {
0
} else {
0x200000
};
assert_eq!(
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
expected
);
}
if run >= 5 {
samples.push(elapsed);
}
}
samples.sort_by(f64::total_cmp);
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
let variance =
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
println!(
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
samples.len(),
samples[samples.len() / 2],
samples[0],
samples[samples.len() - 1]
);
}
}
}
}
+10
View File
@@ -35,6 +35,7 @@ pub struct Control {
pub rounding: Rounding,
pub denormals_are_zero: bool,
pub flush_to_zero: bool,
pub overflow_masked: bool,
pub underflow_masked: bool,
}
@@ -49,6 +50,7 @@ impl Control {
},
denormals_are_zero: mxcsr & 1 << 6 != 0,
flush_to_zero: mxcsr & 1 << 15 != 0,
overflow_masked: mxcsr & 1 << 10 != 0,
underflow_masked: mxcsr & 1 << 11 != 0,
}
}
@@ -263,6 +265,14 @@ fn round(
flags |= PRECISION;
}
if leading > format.bias() {
if !control.overflow_masked {
// No result is delivered. Precision is reported only if rounding
// with an unbounded exponent was inexact.
return Outcome {
bits: 0,
flags: OVERFLOW | if inexact { PRECISION } else { 0 },
};
}
let to_infinity = match control.rounding {
Rounding::Nearest => true,
Rounding::Down => sign,
+38 -9
View File
@@ -237,6 +237,15 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
}
}
/// Whether `byte` is a legacy prefix: an operand-size, address-size, segment,
/// LOCK or repeat prefix (Intel SDM Vol. 2A, 2.1.1).
fn is_legacy_prefix(byte: u8) -> bool {
matches!(
byte,
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3
)
}
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
/// is called only for bytes that belong to the instruction, in order.
///
@@ -258,9 +267,22 @@ pub fn decode<E>(
let mut repne = false;
let mut lock = false;
let mut segment = None;
let mut rex = 0;
let mut byte = cursor.u8()?;
loop {
let selected = match byte {
// REX applies only immediately before the opcode. One that is
// followed by a legacy prefix is ignored (Intel SDM Vol. 2A, 2.2.1).
0x40..=0x4F => {
let next = cursor.u8()?;
if !is_legacy_prefix(next) {
rex = byte;
byte = next;
break;
}
byte = next;
continue;
}
0x64 => Segment::Fs,
0x65 => Segment::Gs,
0x66 => {
@@ -299,10 +321,6 @@ pub fn decode<E>(
byte = cursor.u8()?;
}
let rex = if byte & 0xF0 == 0x40 { byte } else { 0 };
if rex != 0 {
byte = cursor.u8()?;
}
let (rex_w, rex_r, rex_x, rex_b) =
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
@@ -345,9 +363,24 @@ pub fn decode<E>(
GROUPS[usize::from(index)][usize::from((modrm >> 3) & 7)]
}
};
let form = FORMS
let mut form = FORMS
.get(usize::from(form_index))
.ok_or(DecodeError::Unsupported(opcode))?;
let mut form_index = form_index;
if form.no_rex_b && rex_b != 0 {
// 90 is NOP only without REX.B. With it the byte exchanges r8 with the
// accumulator, as the first register of the 91..97 row would (Intel
// SDM Vol. 2B, "NOP" and "XCHG").
match ONE_BYTE[slot + 1] {
Entry::Form(index)
if !two_byte && !rep && FORMS[usize::from(index)].encoding == Encoding::OpReg =>
{
form_index = index;
form = &FORMS[usize::from(index)];
}
_ => return Err(DecodeError::Unsupported(opcode)),
}
}
if form.has_modrm && matches!(entry, Entry::Form(_)) {
modrm = cursor.u8()?;
}
@@ -368,10 +401,6 @@ pub fn decode<E>(
if operand_size && !takes_operand_size && !overridden {
return Err(DecodeError::Unsupported(0x66));
}
if form.no_rex_b && rex_b != 0 {
return Err(DecodeError::Unsupported(opcode));
}
let rm_size = if form.source != 0 { form.source } else { size };
let register = |field: u8, extension: u8, width: u8| {
if width == 1 && rex == 0 && field >= 4 {
+29 -2
View File
@@ -241,6 +241,25 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
flags.cf = signed >> (count - 1) & 1 != 0;
(signed >> count) as u64
}
Op::Rcl | Op::Rcr => {
// The carry flag is one more bit above the operand, so the rotation
// is over `bits + 1` positions and the count is reduced modulo that.
let width = bits + 1;
let ring = wide | u128::from(old.cf) << bits;
let by = count % width;
let left = if op == Op::Rcl {
by
} else {
(width - by) % width
};
let rotated = if left == 0 {
ring
} else {
ring << left | ring >> (width - left)
};
flags.cf = rotated >> bits & 1 != 0;
rotated as u64
}
_ => {
let by = count % bits;
let left = if op == Op::Rol {
@@ -268,7 +287,7 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
// OF is defined only for a count of one.
if count == 1 {
flags.of = match op {
Op::Shl | Op::Rol => (result & top != 0) != flags.cf,
Op::Shl | Op::Rol | Op::Rcl => (result & top != 0) != flags.cf,
Op::Shr => value & top != 0,
Op::Sar => false,
_ => (result & top != 0) != (result & (top >> 1) != 0),
@@ -367,6 +386,14 @@ pub fn execute(
write_reg(cpu, insn.reg, size, offset(cpu, &operand));
}
}
Op::Xchg if insn.encoding == Encoding::OpReg => {
// The accumulator with the register in the opcode, never itself:
// 90 without REX.B is NOP.
let rax = accumulator(RAX);
let (a, b) = (read_reg(cpu, rax, size), read_reg(cpu, insn.reg, size));
write_reg(cpu, rax, size, b);
write_reg(cpu, insn.reg, size, a);
}
Op::Xchg => {
let (a, b) = operands(cpu, memory, insn)?;
write_rm(cpu, memory, insn, b)?;
@@ -419,7 +446,7 @@ pub fn execute(
if negative { mask(size) } else { 0 },
);
}
Op::Rol | Op::Ror | Op::Shl | Op::Shr | Op::Sar => {
Op::Rol | Op::Ror | Op::Rcl | Op::Rcr | Op::Shl | Op::Shr | Op::Sar => {
let (a, count) = operands(cpu, memory, insn)?;
match shift(insn.op, a, count, size, cpu.flags) {
Some((value, flags)) => {
+162 -125
View File
@@ -34,6 +34,8 @@ pub enum Op {
Cdq,
Rol,
Ror,
Rcl,
Rcr,
Shl,
Shr,
Sar,
@@ -209,7 +211,7 @@ pub enum Op {
}
impl Op {
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
/// Lower-case mnemonic stem.
pub const fn name(self) -> &'static str {
@@ -240,6 +242,8 @@ impl Op {
Op::Cdq => "cdq",
Op::Rol => "rol",
Op::Ror => "ror",
Op::Rcl => "rcl",
Op::Rcr => "rcr",
Op::Shl => "shl",
Op::Shr => "shr",
Op::Sar => "sar",
@@ -444,6 +448,8 @@ impl Op {
Op::Cdq => 0,
Op::Rol => 0,
Op::Ror => 0,
Op::Rcl => 1,
Op::Rcr => 1,
Op::Shl => 0,
Op::Shr => 0,
Op::Sar => 0,
@@ -648,6 +654,8 @@ impl Op {
Op::Cdq => 0,
Op::Rol => 0,
Op::Ror => 0,
Op::Rcl => 0,
Op::Rcr => 0,
Op::Shl => 0,
Op::Shr => 0,
Op::Sar => 0,
@@ -852,6 +860,8 @@ impl Op {
Op::Cdq => 0,
Op::Rol => 9,
Op::Ror => 9,
Op::Rcl => 9,
Op::Rcr => 9,
Op::Shl => 31,
Op::Shr => 31,
Op::Sar => 31,
@@ -1056,6 +1066,8 @@ impl Op {
Op::Cdq => 0,
Op::Rol => 0,
Op::Ror => 0,
Op::Rcl => 0,
Op::Rcr => 0,
Op::Shl => 32,
Op::Shr => 32,
Op::Sar => 32,
@@ -1260,6 +1272,8 @@ impl Op {
Op::Cdq => false,
Op::Rol => false,
Op::Ror => false,
Op::Rcl => false,
Op::Rcr => false,
Op::Shl => false,
Op::Shr => false,
Op::Sar => false,
@@ -1464,6 +1478,8 @@ impl Op {
Op::Cdq => false,
Op::Rol => false,
Op::Ror => false,
Op::Rcl => false,
Op::Rcr => false,
Op::Shl => false,
Op::Shr => false,
Op::Sar => false,
@@ -1668,6 +1684,8 @@ impl Op {
Op::Cdq => false,
Op::Rol => false,
Op::Ror => false,
Op::Rcl => false,
Op::Rcr => false,
Op::Shl => false,
Op::Shr => false,
Op::Sar => false,
@@ -1844,7 +1862,7 @@ impl Op {
}
}
pub static FORMS: [Form; 369] = [
pub static FORMS: [Form; 388] = [
Form { op: Op::Movsxd, encoding: Encoding::RegRm, size: OperandSize::Wide, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Push, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Pop, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
@@ -1867,6 +1885,13 @@ pub static FORMS: [Form; 369] = [
Form { op: Op::Test, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedFull, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::RmReg, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::RmReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Mov, encoding: Encoding::RmReg, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Mov, encoding: Encoding::RmReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Mov, encoding: Encoding::RegRm, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
@@ -2186,31 +2211,43 @@ pub static FORMS: [Form; 369] = [
Form { op: Op::Dec, encoding: Encoding::Rm, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rol, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Ror, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcl, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcr, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shl, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shr, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sar, encoding: Encoding::RmImm, size: OperandSize::Byte, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rol, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Ror, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcl, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcr, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shl, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shr, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sar, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedByte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rol, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Ror, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcl, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcr, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shl, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shr, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sar, encoding: Encoding::RmOne, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rol, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Ror, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcl, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcr, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shl, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shr, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sar, encoding: Encoding::RmOne, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rol, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Ror, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcl, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcr, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shl, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shr, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sar, encoding: Encoding::RmCl, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rol, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Ror, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcl, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Rcr, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shl, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Shr, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sar, encoding: Encoding::RmCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
@@ -2218,47 +2255,47 @@ pub static FORMS: [Form; 369] = [
/// Form per ModRM digit; 65535 marks an unsupported digit.
pub static GROUPS: [[u16; 8]; 22] = [
[253, 262, 271, 280, 289, 298, 307, 316],
[254, 263, 272, 281, 290, 299, 308, 317],
[255, 264, 273, 282, 291, 300, 309, 318],
[260, 269, 278, 287, 296, 305, 314, 323],
[261, 270, 279, 288, 297, 306, 315, 324],
[262, 271, 280, 289, 298, 307, 316, 325],
[6, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[339, 340, 65535, 65535, 341, 342, 65535, 343],
[344, 345, 65535, 65535, 346, 347, 65535, 348],
[33, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[34, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[349, 350, 65535, 65535, 351, 352, 65535, 353],
[354, 355, 65535, 65535, 356, 357, 65535, 358],
[359, 360, 65535, 65535, 361, 362, 65535, 363],
[364, 365, 65535, 65535, 366, 367, 65535, 368],
[18, 65535, 323, 324, 325, 326, 327, 328],
[19, 65535, 329, 330, 331, 332, 333, 334],
[335, 336, 65535, 65535, 65535, 65535, 65535, 65535],
[337, 338, 41, 65535, 42, 65535, 5, 65535],
[28, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[65535, 65535, 193, 194, 65535, 65535, 65535, 65535],
[65535, 65535, 65535, 65535, 319, 320, 321, 322],
[65535, 65535, 165, 65535, 167, 65535, 169, 65535],
[65535, 65535, 171, 65535, 173, 65535, 175, 65535],
[65535, 65535, 177, 180, 65535, 65535, 179, 181],
[346, 347, 348, 349, 350, 351, 65535, 352],
[353, 354, 355, 356, 357, 358, 65535, 359],
[40, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[41, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[360, 361, 362, 363, 364, 365, 65535, 366],
[367, 368, 369, 370, 371, 372, 65535, 373],
[374, 375, 376, 377, 378, 379, 65535, 380],
[381, 382, 383, 384, 385, 386, 65535, 387],
[18, 65535, 330, 331, 332, 333, 334, 335],
[19, 65535, 336, 337, 338, 339, 340, 341],
[342, 343, 65535, 65535, 65535, 65535, 65535, 65535],
[344, 345, 48, 65535, 49, 65535, 5, 65535],
[35, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[65535, 65535, 200, 201, 65535, 65535, 65535, 65535],
[65535, 65535, 65535, 65535, 326, 327, 328, 329],
[65535, 65535, 172, 65535, 174, 65535, 176, 65535],
[65535, 65535, 178, 65535, 180, 65535, 182, 65535],
[65535, 65535, 184, 187, 65535, 65535, 186, 188],
];
pub static ONE_BYTE: [Entry; 256] = [
Entry::Form(247), Entry::Form(248), Entry::Form(249), Entry::Form(250),
Entry::Form(251), Entry::Form(252), Entry::Unsupported, Entry::Unsupported,
Entry::Form(256), Entry::Form(257), Entry::Form(258), Entry::Form(259),
Entry::Form(260), Entry::Form(261), Entry::Unsupported, Entry::Unsupported,
Entry::Form(265), Entry::Form(266), Entry::Form(267), Entry::Form(268),
Entry::Form(269), Entry::Form(270), Entry::Unsupported, Entry::Unsupported,
Entry::Form(274), Entry::Form(275), Entry::Form(276), Entry::Form(277),
Entry::Form(278), Entry::Form(279), Entry::Unsupported, Entry::Unsupported,
Entry::Form(283), Entry::Form(284), Entry::Form(285), Entry::Form(286),
Entry::Form(287), Entry::Form(288), Entry::Unsupported, Entry::Unsupported,
Entry::Form(292), Entry::Form(293), Entry::Form(294), Entry::Form(295),
Entry::Form(296), Entry::Form(297), Entry::Unsupported, Entry::Unsupported,
Entry::Form(301), Entry::Form(302), Entry::Form(303), Entry::Form(304),
Entry::Form(305), Entry::Form(306), Entry::Unsupported, Entry::Unsupported,
Entry::Form(310), Entry::Form(311), Entry::Form(312), Entry::Form(313),
Entry::Form(314), Entry::Form(315), Entry::Unsupported, Entry::Unsupported,
Entry::Form(254), Entry::Form(255), Entry::Form(256), Entry::Form(257),
Entry::Form(258), Entry::Form(259), Entry::Unsupported, Entry::Unsupported,
Entry::Form(263), Entry::Form(264), Entry::Form(265), Entry::Form(266),
Entry::Form(267), Entry::Form(268), Entry::Unsupported, Entry::Unsupported,
Entry::Form(272), Entry::Form(273), Entry::Form(274), Entry::Form(275),
Entry::Form(276), Entry::Form(277), Entry::Unsupported, Entry::Unsupported,
Entry::Form(281), Entry::Form(282), Entry::Form(283), Entry::Form(284),
Entry::Form(285), Entry::Form(286), Entry::Unsupported, Entry::Unsupported,
Entry::Form(290), Entry::Form(291), Entry::Form(292), Entry::Form(293),
Entry::Form(294), Entry::Form(295), Entry::Unsupported, Entry::Unsupported,
Entry::Form(299), Entry::Form(300), Entry::Form(301), Entry::Form(302),
Entry::Form(303), Entry::Form(304), Entry::Unsupported, Entry::Unsupported,
Entry::Form(308), Entry::Form(309), Entry::Form(310), Entry::Form(311),
Entry::Form(312), Entry::Form(313), Entry::Unsupported, Entry::Unsupported,
Entry::Form(317), Entry::Form(318), Entry::Form(319), Entry::Form(320),
Entry::Form(321), Entry::Form(322), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2277,23 +2314,23 @@ pub static ONE_BYTE: [Entry; 256] = [
Entry::Form(10), Entry::Form(10), Entry::Form(10), Entry::Form(10),
Entry::Group(0), Entry::Group(1), Entry::Unsupported, Entry::Group(2),
Entry::Form(14), Entry::Form(15), Entry::Form(20), Entry::Form(21),
Entry::Form(22), Entry::Form(23), Entry::Form(24), Entry::Form(25),
Entry::Unsupported, Entry::Form(26), Entry::Unsupported, Entry::Group(3),
Entry::Form(27), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(29), Entry::Form(30), Entry::Unsupported, Entry::Unsupported,
Entry::Form(29), Entry::Form(30), Entry::Form(31), Entry::Form(32),
Entry::Unsupported, Entry::Form(33), Entry::Unsupported, Entry::Group(3),
Entry::Form(34), Entry::Form(22), Entry::Form(23), Entry::Form(24),
Entry::Form(25), Entry::Form(26), Entry::Form(27), Entry::Form(28),
Entry::Form(36), Entry::Form(37), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(49), Entry::Form(50), Entry::Unsupported, Entry::Unsupported,
Entry::Form(16), Entry::Form(17), Entry::Form(51), Entry::Form(52),
Entry::Form(56), Entry::Form(57), Entry::Unsupported, Entry::Unsupported,
Entry::Form(16), Entry::Form(17), Entry::Form(58), Entry::Form(59),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(31), Entry::Form(31), Entry::Form(31), Entry::Form(31),
Entry::Form(31), Entry::Form(31), Entry::Form(31), Entry::Form(31),
Entry::Form(32), Entry::Form(32), Entry::Form(32), Entry::Form(32),
Entry::Form(32), Entry::Form(32), Entry::Form(32), Entry::Form(32),
Entry::Group(4), Entry::Group(5), Entry::Form(35), Entry::Form(36),
Entry::Form(38), Entry::Form(38), Entry::Form(38), Entry::Form(38),
Entry::Form(38), Entry::Form(38), Entry::Form(38), Entry::Form(38),
Entry::Form(39), Entry::Form(39), Entry::Form(39), Entry::Form(39),
Entry::Form(39), Entry::Form(39), Entry::Form(39), Entry::Form(39),
Entry::Group(4), Entry::Group(5), Entry::Form(42), Entry::Form(43),
Entry::Unsupported, Entry::Unsupported, Entry::Group(6), Entry::Group(7),
Entry::Unsupported, Entry::Form(37), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(44), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Group(8), Entry::Group(9), Entry::Group(10), Entry::Group(11),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2301,27 +2338,27 @@ pub static ONE_BYTE: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(38), Entry::Form(39), Entry::Unsupported, Entry::Form(40),
Entry::Form(45), Entry::Form(46), Entry::Unsupported, Entry::Form(47),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(43), Entry::Form(44), Entry::Group(12), Entry::Group(13),
Entry::Form(45), Entry::Form(46), Entry::Unsupported, Entry::Unsupported,
Entry::Form(53), Entry::Form(54), Entry::Group(14), Entry::Group(15),
Entry::Form(50), Entry::Form(51), Entry::Group(12), Entry::Group(13),
Entry::Form(52), Entry::Form(53), Entry::Unsupported, Entry::Unsupported,
Entry::Form(60), Entry::Form(61), Entry::Group(14), Entry::Group(15),
];
pub static TWO_BYTE: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(47), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(54), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(77), Entry::Form(78), Entry::Form(96), Entry::Form(98),
Entry::Form(187), Entry::Form(189), Entry::Form(100), Entry::Form(102),
Entry::Form(84), Entry::Form(85), Entry::Form(103), Entry::Form(105),
Entry::Form(194), Entry::Form(196), Entry::Form(107), Entry::Form(109),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Group(16),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(73), Entry::Form(74), Entry::Unsupported, Entry::Form(86),
Entry::Unsupported, Entry::Unsupported, Entry::Form(227), Entry::Form(228),
Entry::Form(80), Entry::Form(81), Entry::Unsupported, Entry::Form(93),
Entry::Unsupported, Entry::Unsupported, Entry::Form(234), Entry::Form(235),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2330,10 +2367,10 @@ pub static TWO_BYTE: [Entry; 256] = [
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
Entry::Form(104), Entry::Form(195), Entry::Unsupported, Entry::Unsupported,
Entry::Form(108), Entry::Form(111), Entry::Form(114), Entry::Form(117),
Entry::Form(199), Entry::Form(203), Entry::Form(231), Entry::Form(235),
Entry::Form(207), Entry::Form(211), Entry::Form(215), Entry::Form(219),
Entry::Form(111), Entry::Form(202), Entry::Unsupported, Entry::Unsupported,
Entry::Form(115), Entry::Form(118), Entry::Form(121), Entry::Form(124),
Entry::Form(206), Entry::Form(210), Entry::Form(238), Entry::Form(242),
Entry::Form(214), Entry::Form(218), Entry::Form(222), Entry::Form(226),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2350,18 +2387,18 @@ pub static TWO_BYTE: [Entry; 256] = [
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
Entry::Unsupported, Entry::Unsupported, Entry::Form(48), Entry::Form(65),
Entry::Unsupported, Entry::Unsupported, Entry::Form(55), Entry::Form(72),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(66),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(73),
Entry::Unsupported, Entry::Unsupported, Entry::Group(17), Entry::Form(9),
Entry::Form(69), Entry::Form(70), Entry::Unsupported, Entry::Form(67),
Entry::Unsupported, Entry::Unsupported, Entry::Form(55), Entry::Form(56),
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(68),
Entry::Form(60), Entry::Form(61), Entry::Form(57), Entry::Form(58),
Entry::Form(71), Entry::Form(72), Entry::Form(223), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(185), Entry::Unsupported,
Entry::Form(59), Entry::Form(59), Entry::Form(59), Entry::Form(59),
Entry::Form(59), Entry::Form(59), Entry::Form(59), Entry::Form(59),
Entry::Form(76), Entry::Form(77), Entry::Unsupported, Entry::Form(74),
Entry::Unsupported, Entry::Unsupported, Entry::Form(62), Entry::Form(63),
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(75),
Entry::Form(67), Entry::Form(68), Entry::Form(64), Entry::Form(65),
Entry::Form(78), Entry::Form(79), Entry::Form(230), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(192), Entry::Unsupported,
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2381,14 +2418,14 @@ pub static TWO_BYTE_66: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(79), Entry::Form(80), Entry::Form(97), Entry::Form(99),
Entry::Form(188), Entry::Form(190), Entry::Form(101), Entry::Form(103),
Entry::Form(86), Entry::Form(87), Entry::Form(104), Entry::Form(106),
Entry::Form(195), Entry::Form(197), Entry::Form(108), Entry::Form(110),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(75), Entry::Form(76), Entry::Unsupported, Entry::Form(87),
Entry::Unsupported, Entry::Unsupported, Entry::Form(229), Entry::Form(230),
Entry::Form(82), Entry::Form(83), Entry::Unsupported, Entry::Form(94),
Entry::Unsupported, Entry::Unsupported, Entry::Form(236), Entry::Form(237),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2397,18 +2434,18 @@ pub static TWO_BYTE_66: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(105), Entry::Form(196), Entry::Unsupported, Entry::Unsupported,
Entry::Form(109), Entry::Form(112), Entry::Form(115), Entry::Form(118),
Entry::Form(200), Entry::Form(204), Entry::Form(232), Entry::Form(236),
Entry::Form(208), Entry::Form(212), Entry::Form(216), Entry::Form(220),
Entry::Form(119), Entry::Form(120), Entry::Form(121), Entry::Form(122),
Entry::Form(123), Entry::Form(124), Entry::Form(125), Entry::Form(126),
Entry::Form(127), Entry::Form(128), Entry::Form(129), Entry::Form(130),
Entry::Form(131), Entry::Form(132), Entry::Form(94), Entry::Form(81),
Entry::Form(182), Entry::Group(19), Entry::Group(20), Entry::Group(21),
Entry::Form(133), Entry::Form(134), Entry::Form(135), Entry::Unsupported,
Entry::Form(112), Entry::Form(203), Entry::Unsupported, Entry::Unsupported,
Entry::Form(116), Entry::Form(119), Entry::Form(122), Entry::Form(125),
Entry::Form(207), Entry::Form(211), Entry::Form(239), Entry::Form(243),
Entry::Form(215), Entry::Form(219), Entry::Form(223), Entry::Form(227),
Entry::Form(126), Entry::Form(127), Entry::Form(128), Entry::Form(129),
Entry::Form(130), Entry::Form(131), Entry::Form(132), Entry::Form(133),
Entry::Form(134), Entry::Form(135), Entry::Form(136), Entry::Form(137),
Entry::Form(138), Entry::Form(139), Entry::Form(101), Entry::Form(88),
Entry::Form(189), Entry::Group(19), Entry::Group(20), Entry::Group(21),
Entry::Form(140), Entry::Form(141), Entry::Form(142), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(95), Entry::Form(82),
Entry::Unsupported, Entry::Unsupported, Entry::Form(102), Entry::Form(89),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2425,22 +2462,22 @@ pub static TWO_BYTE_66: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(224), Entry::Unsupported,
Entry::Form(191), Entry::Form(192), Entry::Form(186), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(231), Entry::Unsupported,
Entry::Form(198), Entry::Form(199), Entry::Form(193), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(164), Entry::Form(170), Entry::Form(176),
Entry::Form(136), Entry::Form(137), Entry::Form(93), Entry::Form(106),
Entry::Form(138), Entry::Form(139), Entry::Form(140), Entry::Form(107),
Entry::Form(141), Entry::Form(142), Entry::Form(143), Entry::Form(110),
Entry::Form(144), Entry::Form(166), Entry::Form(172), Entry::Form(145),
Entry::Form(146), Entry::Form(147), Entry::Form(238), Entry::Form(85),
Entry::Form(148), Entry::Form(149), Entry::Form(150), Entry::Form(113),
Entry::Form(151), Entry::Form(152), Entry::Form(153), Entry::Form(116),
Entry::Unsupported, Entry::Form(168), Entry::Form(174), Entry::Form(178),
Entry::Form(154), Entry::Form(155), Entry::Form(156), Entry::Unsupported,
Entry::Form(157), Entry::Form(158), Entry::Form(159), Entry::Form(160),
Entry::Unsupported, Entry::Form(171), Entry::Form(177), Entry::Form(183),
Entry::Form(143), Entry::Form(144), Entry::Form(100), Entry::Form(113),
Entry::Form(145), Entry::Form(146), Entry::Form(147), Entry::Form(114),
Entry::Form(148), Entry::Form(149), Entry::Form(150), Entry::Form(117),
Entry::Form(151), Entry::Form(173), Entry::Form(179), Entry::Form(152),
Entry::Form(153), Entry::Form(154), Entry::Form(245), Entry::Form(92),
Entry::Form(155), Entry::Form(156), Entry::Form(157), Entry::Form(120),
Entry::Form(158), Entry::Form(159), Entry::Form(160), Entry::Form(123),
Entry::Unsupported, Entry::Form(175), Entry::Form(181), Entry::Form(185),
Entry::Form(161), Entry::Form(162), Entry::Form(163), Entry::Unsupported,
Entry::Form(164), Entry::Form(165), Entry::Form(166), Entry::Form(167),
Entry::Form(168), Entry::Form(169), Entry::Form(170), Entry::Unsupported,
];
pub static TWO_BYTE_F3: [Entry; 256] = [
@@ -2448,14 +2485,14 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(88), Entry::Form(89), Entry::Unsupported, Entry::Unsupported,
Entry::Form(95), Entry::Form(96), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(241), Entry::Unsupported,
Entry::Form(242), Entry::Form(243), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(248), Entry::Unsupported,
Entry::Form(249), Entry::Form(250), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2464,18 +2501,18 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(197), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(204), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(201), Entry::Form(205), Entry::Form(233), Entry::Form(237),
Entry::Form(209), Entry::Form(213), Entry::Form(217), Entry::Form(221),
Entry::Form(208), Entry::Form(212), Entry::Form(240), Entry::Form(244),
Entry::Form(216), Entry::Form(220), Entry::Form(224), Entry::Form(228),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(83),
Entry::Form(183), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(90),
Entry::Form(190), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(92), Entry::Form(84),
Entry::Unsupported, Entry::Unsupported, Entry::Form(99), Entry::Form(91),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2490,9 +2527,9 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(62), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(63), Entry::Form(64), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(225), Entry::Unsupported,
Entry::Form(69), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(70), Entry::Form(71), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(232), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2501,7 +2538,7 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(239), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(246), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2515,14 +2552,14 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(90), Entry::Form(91), Entry::Unsupported, Entry::Unsupported,
Entry::Form(97), Entry::Form(98), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(244), Entry::Unsupported,
Entry::Form(245), Entry::Form(246), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(251), Entry::Unsupported,
Entry::Form(252), Entry::Form(253), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2531,15 +2568,15 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(198), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(205), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(202), Entry::Form(206), Entry::Form(234), Entry::Unsupported,
Entry::Form(210), Entry::Form(214), Entry::Form(218), Entry::Form(222),
Entry::Form(209), Entry::Form(213), Entry::Form(241), Entry::Unsupported,
Entry::Form(217), Entry::Form(221), Entry::Form(225), Entry::Form(229),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(184), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(191), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2559,7 +2596,7 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(226), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(233), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2568,7 +2605,7 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(240), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(247), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
+21 -37
View File
@@ -1307,6 +1307,18 @@ addr32_sum_wraps_at_32_bits: rbx=ffff0000 rcx=10000+D rax=0 m0=44332211 => rax=1
486601d8
SDM 2A 2.2.1
rex_not_adjacent_to_opcode_is_ignored: rax=112233445566ffff rbx=1 => rax=1122334455660000 f=CPAZso
@ .byte 0x41,0x66,0x01,0xd8
416601d8
SDM 2A 2.2.1
ignored_rex_b_does_not_select_r8: rax=112233445566ffff rbx=1 r8=5 => rax=1122334455660000 f=CPAZso
@ .byte 0x48,0x64,0x8b,0x03
48648b03
SDM 2A 2.2.1; 1 3.4.1.1
ignored_rex_w_before_segment_prefix_loads_32_bits: rax=ffffffffffffffff rbx=8 fs8=1122334455667788 => rax=44332211 f=*
@ .byte 0x41,0x66,0x41,0x01,0xd8
41664101d8
SDM 2A 2.2.1
rex_after_ignored_rex_applies: rax=7 rbx=1 r8=112233445566ffff => r8=1122334455660000 f=CPAZso
@ .byte 0x66,0x48,0x01,0xd8
664801d8
SDM 2A 2.2.1.2
@@ -2596,12 +2608,15 @@ add_memory_crosses_contiguous_pages: rdi=D+1000 mffd=ffffffffffffffff => mffd=00
push_pop_cross_contiguous_pages: rsp=D+1004 rax=1122334455667788 => rbx=1122334455667788 mffc=8877665544332211 f=*
";
const DEFECT_EXACT_UNMASKED_OVERFLOW: &str = r"
const EXACT_UNMASKED_OVERFLOW: &str = r"
@ mulss xmm1, xmm2
!f30f59ca
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
unmasked_overflow_exact_sets_only_oe: x1=s:7f7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
unmasked_negative_overflow_exact_sets_only_oe: x1=s:ff7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
unmasked_overflow_exact_sets_only_oe_down: x1=s:7f7fffff x2=s:40000000 mx=3b80 => mx=3b88 f=* ! XM
unmasked_overflow_exact_sets_only_oe_up: x1=s:7f7fffff x2=s:40000000 mx=5b80 => mx=5b88 f=* ! XM
unmasked_overflow_exact_sets_only_oe_zero: x1=s:7f7fffff x2=s:40000000 mx=7b80 => mx=7b88 f=* ! XM
@ addsd xmm1, xmm2
!f20f58ca
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
@@ -2649,10 +2664,7 @@ const GROUPS: &[(&str, &str)] = &[
("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED),
("fp_beyond_sse2", FP_BEYOND_SSE2),
("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION),
(
"defect_exact_unmasked_overflow",
DEFECT_EXACT_UNMASKED_OVERFLOW,
),
("exact_unmasked_overflow", EXACT_UNMASKED_OVERFLOW),
("page_crossing", PAGE_CROSSING),
];
@@ -2720,22 +2732,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("ptest_flags", 0),
("push16_moves_rsp_by_two", 0),
("pushfq_popfq_status_round_trip", 0),
("rcl16_by16", 0),
("rcl16_by17_is_identity", 0),
("rcl32_by31", 0),
("rcl32_cl32_affects_nothing_but_extension", 0),
("rcl64_by63", 0),
("rcl8_by1_clear_carry_in", 0),
("rcl8_by1_set_carry_in_preserves_szap", 0),
("rcl8_by8", 0),
("rcl8_by9_is_identity", 0),
("rcpps_special_values", 0),
("rcpss_relative_error_bound", 0),
("rcpss_rsqrtss_signal_nothing", 0),
("rcr64_by1", 0),
("rcr8_by10_is_by_one_mod_9", 0),
("rcr8_by1_clear_carry_in", 0),
("rcr8_by1_set_carry_in", 0),
("rep_lodsb_source_fault", 1),
("rep_movsb_addr32_uses_32bit_registers", 1),
("repe_cmpsb_fault_restores_flags", 1),
@@ -2746,7 +2745,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("repne_scasb_finds_byte", 1),
("repne_scasb_finds_byte_df_clear", 0),
("repne_scasd_exhausts_count", 1),
("rex_not_adjacent_to_opcode_is_ignored", 0),
("roundps_uses_mxcsr_rc", 0),
("roundsd_suppress_precision", 0),
("roundss_imm_modes", 0),
@@ -2757,13 +2755,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("shld32_by4", 0),
("shld32_cl32_is_count_zero", 0),
("shld64_by63", 0),
("shr_rcr_128bit_right_shift", 1),
("shrd32_by8", 0),
("shrd64_by1_sign_change", 0),
("shrd64_cl64_is_count_zero", 0),
("xchg_ax_r9w_preserves_both_uppers", 0),
("xchg_eax_ebx_clears_both_uppers", 0),
("xchg_rax_r8_is_not_nop", 0),
];
// ---------------------------------------------------------------------------
@@ -3513,9 +3507,8 @@ fn defect_overlong_instruction() {
}
#[test]
#[ignore = "known defect (#155): an exact unmasked overflow sets PE as well as OE"]
fn defect_exact_unmasked_overflow() {
check_group(DEFECT_EXACT_UNMASKED_OVERFLOW);
fn exact_unmasked_overflow() {
check_group(EXACT_UNMASKED_OVERFLOW);
}
#[test]
@@ -4044,11 +4037,7 @@ fn shift_and_rotate_sweep_matches_operation_pseudocode() {
runs += bench.runs;
}
}
let wanted: Vec<String> = ["rcl", "rcr"]
.iter()
.flat_map(|op| WIDTHS.map(|bits| format!("{op}{bits}")))
.collect();
assert_eq!(refused, wanted, "unsupported shift forms changed");
assert_eq!(refused, Vec::<String>::new(), "a shift form is refused");
println!("{runs} engine runs");
}
@@ -4738,12 +4727,7 @@ fn deliver(
}
if lowest + precision - 1 > format.max_exponent() {
if mxcsr & OM == 0 {
// PE of an exact overflow is `defect_exact_unmasked_overflow`; this
// sweep compares every other bit.
return Outcome {
open: if unbounded_exact { PE } else { 0 },
..outcome(0, OE | unbounded_inexact)
};
return outcome(0, OE | unbounded_inexact);
}
let to_infinity = match mode {
0 => true,
File diff suppressed because it is too large. Load diff
+6 -1
View File
@@ -54,7 +54,7 @@ def cases():
for bits in (8, 16, 32, 64):
out += [f"{op} {reg(1, bits)}", f"{op} {reg(9, bits)}", f"{op} {mem(bits)}"]
out.append(f"{op} ch")
for op in "rol ror shl shr sar".split():
for op in "rol ror rcl rcr shl shr sar".split():
for bits in (8, 16, 32, 64):
for count in ("1", "3", "7", "cl"):
out += [f"{op} {reg(3, bits)}, {count}", f"{op} {mem(bits)}, {count}"]
@@ -98,6 +98,11 @@ def cases():
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
"nop dword ptr [rax + 8]", "pause", "push r9", "push rbx", "push -5", "push 0x12345678",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
# The accumulator short form of XCHG: 91..97, and 90 with REX.B.
for index in range(1, 16):
bits = (16, 32, 64)[index % 3]
out.append(f"xchg {reg(0, bits)}, {reg(index, bits)}")
out += ["xchg r8w, ax", "xchg r8, rax", "xchg r8d, eax", "xchg ecx, eax", "xchg r15w, ax"]
return list(dict.fromkeys(out))
+100
View File
@@ -547,6 +547,86 @@ d3 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], cl
48 d3 4c be 10 | ror qword ptr [rsi + 4*rdi + 16], cl
49 c1 cd 3f | ror r13, 63
49 c1 cd 00 | ror r13, 0
d0 d3 | rcl bl, 1
d0 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], 1
c0 d3 03 | rcl bl, 3
c0 54 be 10 03 | rcl byte ptr [rsi + 4*rdi + 16], 3
c0 d3 07 | rcl bl, 7
c0 54 be 10 07 | rcl byte ptr [rsi + 4*rdi + 16], 7
d2 d3 | rcl bl, cl
d2 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], cl
41 c0 d5 07 | rcl r13b, 7
41 c0 d5 00 | rcl r13b, 0
66 d1 d3 | rcl bx, 1
66 d1 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], 1
66 c1 d3 03 | rcl bx, 3
66 c1 54 be 10 03 | rcl word ptr [rsi + 4*rdi + 16], 3
66 c1 d3 07 | rcl bx, 7
66 c1 54 be 10 07 | rcl word ptr [rsi + 4*rdi + 16], 7
66 d3 d3 | rcl bx, cl
66 d3 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], cl
66 41 c1 d5 0f | rcl r13w, 15
66 41 c1 d5 00 | rcl r13w, 0
d1 d3 | rcl ebx, 1
d1 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], 1
c1 d3 03 | rcl ebx, 3
c1 54 be 10 03 | rcl dword ptr [rsi + 4*rdi + 16], 3
c1 d3 07 | rcl ebx, 7
c1 54 be 10 07 | rcl dword ptr [rsi + 4*rdi + 16], 7
d3 d3 | rcl ebx, cl
d3 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], cl
41 c1 d5 1f | rcl r13d, 31
41 c1 d5 00 | rcl r13d, 0
48 d1 d3 | rcl rbx, 1
48 d1 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], 1
48 c1 d3 03 | rcl rbx, 3
48 c1 54 be 10 03 | rcl qword ptr [rsi + 4*rdi + 16], 3
48 c1 d3 07 | rcl rbx, 7
48 c1 54 be 10 07 | rcl qword ptr [rsi + 4*rdi + 16], 7
48 d3 d3 | rcl rbx, cl
48 d3 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], cl
49 c1 d5 3f | rcl r13, 63
49 c1 d5 00 | rcl r13, 0
d0 db | rcr bl, 1
d0 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], 1
c0 db 03 | rcr bl, 3
c0 5c be 10 03 | rcr byte ptr [rsi + 4*rdi + 16], 3
c0 db 07 | rcr bl, 7
c0 5c be 10 07 | rcr byte ptr [rsi + 4*rdi + 16], 7
d2 db | rcr bl, cl
d2 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], cl
41 c0 dd 07 | rcr r13b, 7
41 c0 dd 00 | rcr r13b, 0
66 d1 db | rcr bx, 1
66 d1 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], 1
66 c1 db 03 | rcr bx, 3
66 c1 5c be 10 03 | rcr word ptr [rsi + 4*rdi + 16], 3
66 c1 db 07 | rcr bx, 7
66 c1 5c be 10 07 | rcr word ptr [rsi + 4*rdi + 16], 7
66 d3 db | rcr bx, cl
66 d3 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], cl
66 41 c1 dd 0f | rcr r13w, 15
66 41 c1 dd 00 | rcr r13w, 0
d1 db | rcr ebx, 1
d1 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], 1
c1 db 03 | rcr ebx, 3
c1 5c be 10 03 | rcr dword ptr [rsi + 4*rdi + 16], 3
c1 db 07 | rcr ebx, 7
c1 5c be 10 07 | rcr dword ptr [rsi + 4*rdi + 16], 7
d3 db | rcr ebx, cl
d3 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], cl
41 c1 dd 1f | rcr r13d, 31
41 c1 dd 00 | rcr r13d, 0
48 d1 db | rcr rbx, 1
48 d1 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], 1
48 c1 db 03 | rcr rbx, 3
48 c1 5c be 10 03 | rcr qword ptr [rsi + 4*rdi + 16], 3
48 c1 db 07 | rcr rbx, 7
48 c1 5c be 10 07 | rcr qword ptr [rsi + 4*rdi + 16], 7
48 d3 db | rcr rbx, cl
48 d3 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], cl
49 c1 dd 3f | rcr r13, 63
49 c1 dd 00 | rcr r13, 0
d0 e3 | shl bl, 1
d0 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], 1
c0 e3 03 | shl bl, 3
@@ -1046,3 +1126,23 @@ ff 74 be 10 | push qword ptr [rsi + 4*rdi + 16]
41 5c | pop r12
8f 44 be 10 | pop qword ptr [rsi + 4*rdi + 16]
c9 | leave
91 | xchg eax, ecx
48 92 | xchg rax, rdx
66 93 | xchg ax, bx
94 | xchg eax, esp
48 95 | xchg rax, rbp
66 96 | xchg ax, si
97 | xchg eax, edi
49 90 | xchg rax, r8
66 41 91 | xchg ax, r9w
41 92 | xchg eax, r10d
49 93 | xchg rax, r11
66 41 94 | xchg ax, r12w
41 95 | xchg eax, r13d
49 96 | xchg rax, r14
66 41 97 | xchg ax, r15w
66 41 90 | xchg r8w, ax
49 90 | xchg r8, rax
41 90 | xchg r8d, eax
91 | xchg ecx, eax
66 41 97 | xchg r15w, ax
+15 -6
View File
@@ -397,7 +397,7 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
write(m, places[0], (1u128 << bits) - 1 - a);
Outcome::Done(none)
}
"shl" | "shr" | "sar" | "rol" | "ror" => {
"shl" | "shr" | "sar" | "rol" | "ror" | "rcl" | "rcr" => {
let count = match rest.split(", ").nth(1) {
Some("cl") => u32::from(m.gpr[1] as u8),
_ => read(m, places[1], 8) as u32,
@@ -405,13 +405,22 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
let start = read(m, places[0], bits);
let mut value = start;
let top = 1u128 << (bits - 1);
let mut carry = m.flags.cf;
for _ in 0..count {
let carry_in = m.flags.cf;
let mut carry = carry_in;
// RCL and RCR rotate through CF, so `bits + 1` steps come round again.
let steps = if matches!(name, "rcl" | "rcr") {
count % (bits + 1)
} else {
count
};
for _ in 0..steps {
// One step at a time, as the SDM loop does.
let (high, low) = (bit(value, bits - 1), bit(value, 0));
(value, carry) = match name {
"shl" => (truncate(value * 2, bits), high),
"rol" => (truncate(value * 2, bits) + u128::from(high), high),
"rcl" => (truncate(value * 2, bits) + u128::from(carry), high),
"rcr" => (value / 2 + if carry { top } else { 0 }, low),
"shr" => (value / 2, low),
"sar" => (value / 2 + if high { top } else { 0 }, low),
_ => (value / 2 + if low { top } else { 0 }, low),
@@ -424,7 +433,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
let (msb, next) = (bit(value, bits - 1), bit(value, bits - 2));
if count == 1 {
m.flags.of = match name {
"shl" | "rol" => msb != carry,
"shl" | "rol" | "rcl" => msb != carry,
"rcr" => bit(start, bits - 1) != carry_in,
"shr" => bit(start, bits - 1),
"sar" => false,
_ => msb != next,
@@ -1222,10 +1232,9 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
&[0x66, 0xE8, 0, 0], // call rel16
&[0x66, 0x0F, 0xC9], // bswap cx (undefined)
&[0x66, 0x63, 0xC1], // 16-bit movsxd
&[0x41, 0x90], // xchg r8, rax
&[0xF3, 0x41, 0x90], // F3 on xchg r8, rax
&[0x8D, 0xC0], // lea with a register operand
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
&[0xC0, 0xD0, 0x01], // rcl al, 1
&[0xC6, 0xC8, 0x01], // C6 /1
&[0xFF, 0xF8], // FF /7
&[0xFE, 0xD0], // FE /2
+48 -1
View File
@@ -61,6 +61,8 @@ cwde = { ref = "sdm CBW/CWDE/CDQE" }
cdq = { ref = "sdm CWD/CDQ/CQO" }
rol = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
ror = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
rcl = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
rcr = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
shl = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
shr = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
sar = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
@@ -401,6 +403,51 @@ opcode = 0x87
enc = "rm_reg"
size = "v"
# The accumulator with the register in the opcode. Opcode 0x90 is NOP; with
# REX.B the decoder reads it as 0x91 with register 0, which is then r8. A row
# of eight would have to start at 0x90, so each opcode is its own form.
[[form]]
op = "xchg"
opcode = 0x91
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x92
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x93
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x94
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x95
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x96
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x97
enc = "op_reg"
size = "v"
[[form]]
op = "mov"
opcode = 0x88
@@ -779,7 +826,7 @@ digits = { 0 = "inc", 1 = "dec" }
[[group]]
opcodes = [[0xC0, "b", "ib", "rm_imm"], [0xC1, "v", "ib", "rm_imm"], [0xD0, "b", "", "rm_one"], [0xD1, "v", "", "rm_one"], [0xD2, "b", "", "rm_cl"], [0xD3, "v", "", "rm_cl"]]
digits = { 0 = "rol", 1 = "ror", 4 = "shl", 5 = "shr", 7 = "sar" }
digits = { 0 = "rol", 1 = "ror", 2 = "rcl", 3 = "rcr", 4 = "shl", 5 = "shr", 7 = "sar" }
# SSE and SSE2 moves and packed integer forms.
+39 -3
View File
@@ -101,7 +101,43 @@ impl NativeCompute {
colors,
[width, height],
clear,
sampled,
sampled.map(|(texture, sampler)| (texture.raw(), sampler)),
)
.map(|(pixels, _)| pixels)
}
/// As [`Self::render_rgba8_sampled`], with level 0 of a BC1 upload bound
/// natively as a `BC1_RGBA` texture to fragment texture slot 0 and the
/// sampler to fragment sampler slot 0.
///
/// # Errors
///
/// As [`Self::render_rgba8_sampled`], and for an invalid BC1 level.
#[allow(clippy::too_many_arguments)]
pub fn render_rgba8_sampled_bc1(
&self,
source: &str,
entries: [&str; 2],
vertices: &[[f32; 4]; 3],
colors: &[[f32; 4]; 3],
extent: [usize; 2],
clear: [u8; 4],
texture: &Bc1Upload<'_>,
sampler: &crate::sampler::MetalSampler,
) -> Result<Vec<u8>, MetalError> {
let level = texture
.subresource(0, 0)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.validate_bc_extent(level.width, level.height, "BC1")?;
let bc1 = self.new_bc1_texture(&level)?;
self.render_rgba8_internal(
source,
entries,
vertices,
colors,
extent,
clear,
Some((&bc1, sampler)),
)
.map(|(pixels, _)| pixels)
}
@@ -116,7 +152,7 @@ impl NativeCompute {
[width, height]: [usize; 2],
clear: [u8; 4],
sampled: Option<(
&crate::texture_pipeline::MetalRgba8Texture,
&ProtocolObject<dyn MTLTexture>,
&crate::sampler::MetalSampler,
)>,
) -> Result<(Vec<u8>, Option<f64>), MetalError> {
@@ -228,7 +264,7 @@ impl NativeCompute {
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1);
if let Some((tex, samp)) = sampled {
encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0);
encoder.setFragmentTexture_atIndex(Some(tex), 0);
encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0);
}
encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3);
@@ -0,0 +1,99 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
use xenora_texture::{Bc1Upload, Bc1UploadDesc, SamplerDesc, decode_bc1};
use super::{context, native};
/// The translated `image_sample_lz` pixel stage samples a native BC1
/// texture bound by `render_rgba8_sampled_bc1`. Each of the 8×8 texture's
/// four blocks selects only its two endpoints, which expand exactly to 0 or
/// 255, so the image is known without a decoder: selector 1 (the second
/// endpoint) where `x == 0 || y == 3` within a block, else selector 0.
#[test]
fn translated_image_sample_lz_reads_bound_bc1_texture() {
let blocks: [[u8; 8]; 4] = [
[0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], // red, blue
[0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], // green, black
[0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], // white, magenta
[0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], // yellow, cyan
];
let endpoints: [[[u8; 4]; 2]; 4] = [
[[255, 0, 0, 255], [0, 0, 255, 255]],
[[0, 255, 0, 255], [0, 0, 0, 255]],
[[255, 255, 255, 255], [255, 0, 255, 255]],
[[255, 255, 0, 255], [0, 255, 255, 255]],
];
let mut expected = Vec::new();
for y in 0..8 {
for x in 0..8 {
let selector = usize::from(x % 4 == 0 || y % 4 == 3);
expected.extend(endpoints[(y / 4) * 2 + x / 4][selector]);
}
}
for (index, block) in blocks.into_iter().enumerate() {
let (bx, by) = (index % 2 * 4, index / 2 * 4);
for (i, texel) in decode_bc1(block).iter().enumerate() {
let at = ((by + i / 4) * 8 + bx + i % 4) * 4;
assert_eq!(texel, &expected[at..at + 4], "decoder, block {index}");
}
}
let ps: Vec<u8> = [
&[0x00, 0x00, 0x08, 0xc8][..], // v_interp_p1_f32 v2, v0, attr0.x
&[0x01, 0x00, 0x09, 0xc8], // v_interp_p2_f32 v2, v1, attr0.x
&[0x00, 0x01, 0x0c, 0xc8], // v_interp_p1_f32 v3, v0, attr0.y
&[0x01, 0x01, 0x0d, 0xc8], // v_interp_p2_f32 v3, v1, attr0.y
&[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], // image_sample_lz
&[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], // exp mrt0
&[0x00, 0x00, 0x81, 0xbf], // s_endpgm
]
.concat();
let compiled = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"),
&ps,
)
.expect("compile translated image_sample_lz shader");
let gpu = context();
let upload = Bc1Upload::new(
blocks.as_flattened(),
Bc1UploadDesc {
width: 8,
height: 8,
mips: 1,
layers: 1,
format: 1,
usage: 1,
row_pitch: 16,
slice_pitch: 32,
},
)
.expect("valid BC1 upload");
let sampler = native(xenora_metal::sampler::MetalSampler::new(
gpu.device(),
SamplerDesc::nearest_clamp(),
));
// Pixel (x, y) of the 8×8 target samples uv ((x + 0.5) / 8, (y + 0.5) / 8).
let positions = [
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
];
let uvs = [
[0.0, 1.0, 0.0, 1.0],
[2.0, 1.0, 0.0, 1.0],
[0.0, -1.0, 0.0, 1.0],
];
let pixels = native(gpu.render_rgba8_sampled_bc1(
&compiled.msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&positions,
&uvs,
[8, 8],
[19, 43, 93, 251],
&upload,
&sampler,
));
assert_eq!(pixels, expected);
}
+2
View File
@@ -26,6 +26,8 @@ mod texture_bc_alpha;
mod texture_bc_channel;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_bc1.rs"]
mod translated_bc1;
#[path = "native/translated_render.rs"]
mod translated_render;
+74 -12
View File
@@ -57,6 +57,8 @@ pub enum Op {
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
Compare(Comparison, CompareSource, u8),
/// VOP3A integer compare writing a Wave32 mask to SDST.
CompareVop3(u8, Comparison, CompareSource, u8),
/// VOPC 16- or 64-bit integer compare writing the Wave32 mask to
/// `vcc_lo`. For 64-bit forms a `Vector` or `Scalar` source and VSRC1 name
/// the low register of a pair.
@@ -187,6 +189,8 @@ pub enum BranchCondition {
SccZero,
/// Take the branch when the low half of VCC is clear.
VccZero,
/// Take the branch when the low half of VCC is nonzero.
VccNonzero,
/// Take the branch when the low half of EXEC is clear.
ExecZero,
}
@@ -719,7 +723,13 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
left_length.max(right_length),
)
}
[lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => {
[
lo,
hi,
opcode @ (0x82 | 0x84 | 0x86 | 0x87 | 0x88),
0xbf,
..,
] => {
let words = i16::from_le_bytes([*lo, *hi]);
let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?;
(
@@ -728,6 +738,7 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
condition: match opcode {
0x84 => BranchCondition::SccZero,
0x86 => BranchCondition::VccZero,
0x87 => BranchCondition::VccNonzero,
0x88 => BranchCondition::ExecZero,
_ => BranchCondition::Always,
},
@@ -755,9 +766,50 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let src1 = (second >> 1) | ((third & 1) << 7);
(Op::Vector(kind, dst, *first, src1), 4)
}
[dst, 0, 0x25, 0xd5, lo, middle, hi @ 2..=3, 0x02, ..] if middle & 1 == 1 => {
// Guide §§12.7.1, 12.9.1, 12.12 and 13.3.4: VOP3A extends
// VOP2 by 0x100 and preserves the VOPC opcode. This subset
// fixes unused SRC2 to inline 0 and excludes FP ABS/NEG/OMOD,
// halfword OP_SEL, and CLAMP (integer saturation or FP compare
// exceptions, §6.5).
[
dst,
0,
op,
tag @ (0xd4 | 0xd5),
lo,
middle,
hi @ 2..=3,
0x02,
..,
] if middle & 1 != 0 => {
let src0 = CompareSource::Vector(*lo);
let src1 = (middle >> 1) | ((hi & 1) << 7);
(Op::Add(*dst, *lo, src1), 8)
match tag {
0xd4 if matches!(op, 128..=135 | 192..=199) && *dst <= 106 => (
Op::CompareVop3(
*dst,
Comparison {
offset: op & 7,
signed: *op < 192,
},
src0,
src1,
),
8,
),
0xd5 if *op == 37 => (Op::Add(*dst, *lo, src1), 8),
0xd5 => (
Op::VectorInteger(
VectorInteger::from_opcode(*op)
.ok_or_else(|| error(offset, "unsupported VOP3 opcode"))?,
*dst,
src0,
src1,
),
8,
),
_ => return Err(error(offset, "unsupported VOP3 opcode or destination")),
}
}
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
@@ -1434,13 +1486,16 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
}
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
Op::Compare(..) | Op::WideCompare(..) => {
let (comparison, width, src0, src1) = match op {
Op::Compare(..) | Op::WideCompare(..) | Op::CompareVop3(..) => {
let (dst, comparison, width, src0, src1) = match op {
Op::Compare(comparison, src0, src1) => {
(comparison, CompareWidth::Word, src0, src1)
(VCC_LO, comparison, CompareWidth::Word, src0, src1)
}
Op::CompareVop3(dst, comparison, src0, src1) => {
(usize::from(dst), comparison, CompareWidth::Word, src0, src1)
}
Op::WideCompare(comparison, width, src0, src1) => {
(comparison, width, src0, src1)
(VCC_LO, comparison, width, src0, src1)
}
_ => unreachable!(),
};
@@ -1501,18 +1556,24 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
}
}
scalars[VCC_LO] = Some(mask);
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
scalars[dst] = Some(mask);
if dst == VCC_LO {
scalars[VCC_HI] = None;
lane_derived_vcc = exec != 0;
}
}
Op::Branch {
target: destination,
condition,
} => {
if condition == BranchCondition::VccZero && scalars[VCC_LO].is_none() {
let tests_vcc = matches!(
condition,
BranchCondition::VccZero | BranchCondition::VccNonzero
);
if tests_vcc && scalars[VCC_LO].is_none() {
return Err(error(offset, "branch with uninitialized VCC_LO"));
}
if condition == BranchCondition::VccZero && lane_derived_vcc {
if tests_vcc && lane_derived_vcc {
check_runtime_region(
&program[position + 1..],
destination,
@@ -1529,6 +1590,7 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
!scc.ok_or_else(|| error(offset, "branch with uninitialized SCC"))?
}
BranchCondition::VccZero => scalars[VCC_LO] == Some(0),
BranchCondition::VccNonzero => scalars[VCC_LO] != Some(0),
BranchCondition::ExecZero => exec == 0,
};
if take_branch {
+115 -35
View File
@@ -120,6 +120,10 @@ enum Op {
/// The value is wave-uniform; every thread computes it for its own wave.
LaneMask {
op: VectorCompareOp,
/// Assembly name of the decoded encoding (`_e32` or `_e64`).
name: &'static str,
/// The explicit SGPR destination of the VOP3A encoding (IR text only).
sdst: Option<usize>,
src0: Value,
src1: Value,
high: Option<(Value, Value)>,
@@ -600,11 +604,18 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
}
Op::LaneMask {
op,
name,
sdst,
src0,
src1,
high,
exec,
} => {
let target = match sdst {
None => String::new(),
Some(VCC_LO) => " -> vcc_lo".to_string(),
Some(register) => format!(" -> s{register}"),
};
let (left, right) = if let Some((hi0, hi1)) = high {
(format!("{src0}:{hi0}"), format!("{src1}:{hi1}"))
} else {
@@ -612,8 +623,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
};
let _ = writeln!(
ir,
"{offset:04x}: {dest} = wave.mask {} {left}, {right} exec=0x{exec:08x}",
op.assembly_name()
"{offset:04x}: {dest} = wave.mask {name} {left}, {right}{target} exec=0x{exec:08x}"
);
let inputs = if matches!(
op.relation(),
@@ -721,6 +731,13 @@ fn decode_fixture(
xenora_decoder::decode(architecture, bytes).map_err(CompileError::Decode)
}
#[derive(Clone, Copy)]
enum ScalarValue {
Uninitialized,
Known(u32),
RuntimeMask,
}
fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, Op)>, CompileError> {
let mut operations = Vec::new();
let mut registers = [None::<Value>; 256];
@@ -728,12 +745,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let mut pending_load = None;
let mut stored = false;
let mut store_pending = false;
let mut scalars = [None; 128];
let mut scalars = [ScalarValue::Uninitialized; 128];
let mut exec = u32::MAX; // The fixture starts with full Wave32 EXEC.
scalars[126] = Some(exec);
scalars[126] = ScalarValue::Known(exec);
let mut scc = None;
let mut skip_before = 0;
// Set while VCC_LO holds a lane-derived compare mask (scalars[VCC_LO] is then None).
// VCC_LO can forward a lane-derived mask to its supported runtime consumers.
let mut lane_vcc: Option<Value> = None;
// An open runtime `s_cbranch_vccz` region: its end, mask and the VGPRs at the branch.
let mut region: Option<(usize, Value, [Option<Value>; 256])> = None;
@@ -865,11 +882,15 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
}
let read_scalar = |source| match source {
ScalarSource::Immediate(value) => Ok(value),
ScalarSource::Register(register) => scalars
.get(usize::from(register))
.copied()
.flatten()
.ok_or_else(|| error("scalar source has no known value")),
ScalarSource::Register(register) => match scalars.get(usize::from(register)) {
Some(ScalarValue::Known(value)) => Ok(*value),
Some(ScalarValue::RuntimeMask) => Err(error(
"scalar source reads a runtime-only SGPR compare mask",
)),
Some(ScalarValue::Uninitialized) | None => {
Err(error("scalar source has no known value"))
}
},
};
let read_vector = |source, operations: &mut Vec<_>, facts: &mut Vec<_>| {
Ok(match source {
@@ -877,8 +898,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => constant(operations, facts, offset, bits),
(None, None) => {
(None, ScalarValue::Known(bits)) => {
constant(operations, facts, offset, bits)
}
(None, _) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
@@ -896,8 +919,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Instruction::VectorAlu { op, .. } if op.writes_vcc() => {
// Guide 3.9: inactive lanes contribute zero to carry-out.
lane_vcc = None;
scalars[VCC_LO] = Some(0);
scalars[VCC_HI] = None;
scalars[VCC_LO] = ScalarValue::Known(0);
scalars[VCC_HI] = ScalarValue::Uninitialized;
continue;
}
Instruction::MoveB32 { .. }
@@ -918,6 +941,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
{
return Err(error("vector memory requires full Wave32 EXEC"));
}
if let Instruction::BufferLoadDword { resource, .. }
| Instruction::BufferStoreDword { resource, .. } = instruction.instruction
{
let start = usize::from(resource);
if scalars[start..start + 4]
.iter()
.any(|value| matches!(value, ScalarValue::RuntimeMask))
{
return Err(error(
"resource descriptor reads a runtime-only SGPR compare mask",
));
}
}
let next = Value(operations.len());
let (dest, operation) = match instruction.instruction {
Instruction::BufferLoadDword { data, .. } => {
@@ -1033,7 +1069,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
*slot = ScalarValue::Known(value);
continue;
}
Instruction::ScalarUnary { op, dst, src } => {
@@ -1045,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
*slot = ScalarValue::Known(value);
if let Some(flag) = flag {
scc = Some(flag);
}
@@ -1070,7 +1106,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
*slot = ScalarValue::Known(value);
if let Some(flag) = flag {
scc = Some(flag);
}
@@ -1094,13 +1130,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
let old = if op.reads_dst() {
slot.ok_or_else(|| error("SOPK reads an uninitialized SGPR"))?
match *slot {
ScalarValue::Known(value) => value,
ScalarValue::RuntimeMask => {
return Err(error("SOPK reads a runtime-only SGPR compare mask"));
}
ScalarValue::Uninitialized => {
return Err(error("SOPK reads an uninitialized SGPR"));
}
}
} else {
0
};
let (value, flag) = op.evaluate(old, simm16, scc_in);
if let Some(value) = value {
*slot = Some(value);
*slot = ScalarValue::Known(value);
}
if let Some(flag) = flag {
scc = Some(flag);
@@ -1112,11 +1156,36 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
continue;
}
// docs/shaders/vector-compare.md sections 3 and 5.
Instruction::VectorCompare { op, src0, src1 } => {
// Both encodings share the Wave32 lane mask implementation.
compare @ (Instruction::VectorCompare { .. }
| Instruction::VectorCompareVop3 { .. }) => {
let (op, name, explicit, sdst, src0, src1) = match compare {
Instruction::VectorCompare { op, src0, src1 } => {
(op, op.assembly_name(), false, VCC_LO, src0, src1)
}
Instruction::VectorCompareVop3 {
op,
sdst,
src0,
src1,
} => (
op.base(),
op.assembly_name(),
true,
usize::from(sdst),
VectorSource::Register(src0),
src1,
),
_ => unreachable!("only vector compares reach this arm"),
};
if exec == 0 {
scalars[VCC_HI] = None;
scalars[VCC_LO] = Some(0);
lane_vcc = None;
if sdst == VCC_LO {
scalars[VCC_HI] = ScalarValue::Uninitialized;
scalars[VCC_LO] = ScalarValue::Known(0);
lane_vcc = None;
} else {
scalars[sdst] = ScalarValue::RuntimeMask;
}
continue;
}
let constant =
@@ -1148,8 +1217,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => constant(&mut operations, &mut facts, bits),
(None, None) => {
(None, ScalarValue::Known(bits)) => {
constant(&mut operations, &mut facts, bits)
}
(None, _) => {
return Err(error("compare reads uninitialized VCC_LO"));
}
}
@@ -1166,6 +1237,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
offset,
Op::LaneMask {
op,
name,
sdst: explicit.then_some(sdst),
src0,
src1,
high,
@@ -1173,9 +1246,13 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
},
));
facts.push(KnownBits::UNKNOWN);
scalars[VCC_LO] = None;
scalars[VCC_HI] = None;
lane_vcc = Some(mask);
if sdst == VCC_LO {
scalars[VCC_LO] = ScalarValue::Uninitialized;
scalars[VCC_HI] = ScalarValue::Uninitialized;
lane_vcc = Some(mask);
} else {
scalars[sdst] = ScalarValue::RuntimeMask;
}
continue;
}
Instruction::Branch { .. }
@@ -1222,9 +1299,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
error("conditional branch reads uninitialized SCC")
})?,
SoppControlOp::BranchVccZero => {
scalars[106].ok_or_else(|| {
error("conditional branch reads uninitialized VCC_LO")
})? == 0
let ScalarValue::Known(bits) = scalars[VCC_LO] else {
return Err(error(
"conditional branch reads uninitialized VCC_LO",
));
};
bits == 0
}
SoppControlOp::BranchExecZero => exec == 0,
SoppControlOp::WaitLoad | SoppControlOp::EndProgram => {
@@ -1259,10 +1339,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
VectorLowering::Vcc(primitive) => {
let mask = match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => {
(None, ScalarValue::Known(bits)) => {
constant(&mut operations, &mut facts, offset, bits)
}
(None, None) => {
(None, _) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
};
@@ -1282,8 +1362,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
lane_vcc = Some(Value(operations.len()));
operations.push((offset, Op::CarryMask { flag, exec }));
facts.push(KnownBits::UNKNOWN);
scalars[VCC_LO] = None;
scalars[VCC_HI] = None;
scalars[VCC_LO] = ScalarValue::Uninitialized;
scalars[VCC_HI] = ScalarValue::Uninitialized;
}
(
Some(dst),
+132
View File
@@ -14,6 +14,110 @@ fn compiles_original_fixture() {
);
}
#[test]
fn vop3_compare_to_vcc_lo_drives_a_runtime_vccz_branch() {
let code: Vec<_> = [
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
0x7e04_0282, // v_mov_b32_e32 v2, 2
0xd4c2_006a, // v_cmp_eq_u32_e64 vcc_lo, v1, v2
0x0202_0501,
0xbf86_0001, // s_cbranch_vccz 1
0x7e02_0302, // v_mov_b32_e32 v1, v2
]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
let shader = compile(Architecture::Gfx1030, &code).unwrap();
assert!(
shader
.disassembly
.contains("v_cmp_eq_u32_e64 vcc_lo, v1, v2")
);
assert!(shader.ir.contains("0008: t2 = wave.mask"));
assert!(shader.ir.contains("0010: branch.vccz t2 -> 0x0018"));
assert!(shader.ir.contains("join.vccz t2"));
assert!(shader.msl.contains("lane_index >= grid"));
}
#[test]
fn vop3_compare_to_s4_rejects_later_scalar_reads() {
for (setup, offset) in [
(&[0x7e02_0281u32, 0x7e04_0282][..], 16), // Initialize both VGPRs.
(&[0xbefe_0380][..], 12), // Empty EXEC. The VGPRs need not be initialized.
] {
let code: Vec<_> = setup
.iter()
.copied()
.chain([
0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2
0x0202_0501,
0xbf06_8004, // s_cmp_eq_u32 s4, 0
0xbefe_03c1, // s_mov_b32 exec_lo, -1
0x7e02_0281, // v_mov_b32_e32 v1, 1
])
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
let error = compile(Architecture::Gfx1030, &code).unwrap_err();
assert!(
matches!(
error,
CompileError::Verify {
offset: actual,
reason: "scalar source reads a runtime-only SGPR compare mask",
} if actual == offset
),
"{error}"
);
}
}
#[test]
fn vop3_compare_mask_cannot_be_read_as_a_buffer_descriptor() {
let code: Vec<_> = [
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
0x7e04_0282, // v_mov_b32_e32 v2, 2
0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2
0x0202_0501,
]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify {
offset: 16,
reason: "resource descriptor reads a runtime-only SGPR compare mask",
})
));
}
#[test]
fn vop3_compare_to_normal_sgpr_preserves_vcc_and_can_be_overwritten() {
let code: Vec<_> = [
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
0x7e04_0282, // v_mov_b32_e32 v2, 2
0xbeea_0381, // s_mov_b32 vcc_lo, 1
0xd4c2_0008, // v_cmp_eq_u32_e64 s8, v1, v2
0x0202_0501,
0xbf86_0001, // s_cbranch_vccz 1
0xbe88_0381, // s_mov_b32 s8, 1
0xbf06_8008, // s_cmp_eq_u32 s8, 0
]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE[28..].iter().copied())
.collect();
let shader = compile(Architecture::Gfx1030, &code).unwrap();
assert!(
shader
.ir
.contains("0014: branch.uniform 0x001c taken=false")
);
}
#[test]
fn load_wait_is_required_before_using_loaded_data() {
let mut code = FIXTURE.to_vec();
@@ -364,6 +468,20 @@ fn vector_integer_forms_lower_to_per_lane_templates() {
);
}
#[test]
fn vop3_integer_forms_lower_to_per_lane_templates() {
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vop3-integer.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vop3-integer.metal")
);
}
#[test]
fn vector_f_and_t_compares_lower_to_operand_free_wave_masks() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin");
@@ -392,6 +510,20 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
);
}
#[test]
fn vop3_compare_forms_lower_to_wave_masks() {
let code = include_bytes!("../../../fixtures/rdna2/vop3-compare.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vop3-compare.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vop3-compare.metal")
);
}
#[test]
fn vector_vcc_fixture_matches_ir_and_msl_goldens() {
let code = include_bytes!("../../../fixtures/rdna2/vector-vcc.bin");
+47 -10
View File
@@ -27,6 +27,8 @@ pub use upload::{
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
const TILE_ROW_BYTES: usize = TILE_BLOCKS * BLOCK_BYTES;
const TILE_BYTES: usize = TILE_BLOCKS * TILE_ROW_BYTES;
#[derive(Debug, PartialEq, Eq)]
pub enum TextureError {
@@ -91,19 +93,30 @@ impl<'a> TiledBc1<'a> {
/// Copies one subresource as tightly packed row-major BC1 block rows.
/// Padded tile slots are excluded, including at partial texel blocks.
pub fn linearize(&self, layer: usize, mip: u32) -> Result<Vec<u8>, TextureError> {
if layer >= self.layers {
if layer >= self.layers || mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
self.mip_extent(mip)?;
let (width, height) = mip_blocks(self.width, self.height, mip);
let base = self.mip_base(layer, mip)?;
let tile_row_stride = width.div_ceil(TILE_BLOCKS) * TILE_BYTES;
let full_tiles = width / TILE_BLOCKS;
let edge_bytes = (width % TILE_BLOCKS) * BLOCK_BYTES;
let mut blocks = Vec::new();
// Construction checked the larger, padded byte count.
blocks
.try_reserve_exact(width * height * BLOCK_BYTES)
.map_err(|_| TextureError::AllocationFailed)?;
// Construction requires the exact padded length, so each selected tile row is in bounds.
for y in 0..height {
for x in 0..width {
blocks.extend_from_slice(&self.block(layer, mip, x, y)?);
let row_start =
base + (y / TILE_BLOCKS) * tile_row_stride + (y % TILE_BLOCKS) * TILE_ROW_BYTES;
for tile in 0..full_tiles {
let start = row_start + tile * TILE_BYTES;
blocks.extend_from_slice(&self.bytes[start..start + TILE_ROW_BYTES]);
}
if edge_bytes != 0 {
let start = row_start + full_tiles * TILE_BYTES;
blocks.extend_from_slice(&self.bytes[start..start + edge_bytes]);
}
}
Ok(blocks)
@@ -124,19 +137,24 @@ impl<'a> TiledBc1<'a> {
if x >= width || y >= height {
return Err(TextureError::OutOfBounds);
}
let mut base = layer * self.layer_bytes;
for prior in 0..mip {
base += mip_bytes(self.width, self.height, prior)?;
}
let base = self.mip_base(layer, mip)?;
// Construction checked the full padded size for every level and layer.
let tile = (y / TILE_BLOCKS) * width.div_ceil(TILE_BLOCKS) + x / TILE_BLOCKS;
let within_tile = (y % TILE_BLOCKS) * TILE_BLOCKS + x % TILE_BLOCKS;
let offset = base + (tile * TILE_BLOCKS.pow(2) + within_tile) * BLOCK_BYTES;
let offset = base + tile * TILE_BYTES + within_tile * BLOCK_BYTES;
self.bytes
.get(offset..offset + BLOCK_BYTES)
.and_then(|bytes| bytes.try_into().ok())
.ok_or(TextureError::InvalidByteLength)
}
fn mip_base(&self, layer: usize, mip: u32) -> Result<usize, TextureError> {
let mut base = layer * self.layer_bytes;
for prior in 0..mip {
base += mip_bytes(self.width, self.height, prior)?;
}
Ok(base)
}
}
fn mip_blocks(width: usize, height: usize, mip: u32) -> (usize, usize) {
@@ -151,7 +169,7 @@ fn mip_bytes(width: usize, height: usize, mip: u32) -> Result<usize, TextureErro
width
.div_ceil(TILE_BLOCKS)
.checked_mul(height.div_ceil(TILE_BLOCKS))
.and_then(|tiles| tiles.checked_mul(TILE_BLOCKS.pow(2) * BLOCK_BYTES))
.and_then(|tiles| tiles.checked_mul(TILE_BYTES))
.ok_or(TextureError::SizeOverflow)
}
@@ -216,6 +234,7 @@ mod tests {
assert_eq!(tex.linearize(1, 0).unwrap(), logical_blocks.as_flattened());
assert_eq!(tex.linearize(1, 1).unwrap(), [20; 8]);
assert_eq!(tex.linearize(2, 0), Err(TextureError::OutOfBounds));
assert_eq!(tex.linearize(0, 2), Err(TextureError::OutOfBounds));
}
#[test]
@@ -242,6 +261,24 @@ mod tests {
assert_eq!(texture.block(0, 0, 2, 2), Ok([12; 8]));
}
#[test]
fn linearizes_odd_tile_edges_in_each_layer() {
// A 21×21 texture uses 9, 4 and 1 tiles across the three mips.
// Mip 1 is 10×10 texels, so only nine of its sixteen slots are logical.
let block = |slot: u8| [slot, 1, 2, 3, 4, 5, 6, !slot];
let bytes: Vec<_> = (0..112).flat_map(block).collect();
let texture = TiledBc1::new(&bytes, 21, 21, 3, 2).unwrap();
for (layer, first_slot) in [(0, 36), (1, 92)] {
let expected: Vec<_> = [0, 1, 4, 2, 3, 6, 8, 9, 12]
.into_iter()
.flat_map(|slot| block(first_slot + slot))
.collect();
assert_eq!(texture.linearize(layer, 1).unwrap(), expected);
let last_mip: Vec<_> = (16..20).flat_map(|slot| block(first_slot + slot)).collect();
assert_eq!(texture.linearize(layer, 2).unwrap(), last_mip);
}
}
#[test]
fn decodes_opaque_and_transparent_bc1_palettes() {
let opaque = decode_bc1([0, 0xf8, 31, 0, 0xe4, 0xe4, 0xe4, 0xe4]);
+2
View File
@@ -40,6 +40,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
## Testing, validation, and benchmarks
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
- [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.
+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: 158 of 158. Accepted Metal forms · Apple M5: 18 of 158. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 185 of 185. Accepted Metal forms · Apple M5: 18 of 185. Accepted guest milestones · X1–X4: 4 of 4</desc>
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
<text x="510" y="58" font-size="13" text-anchor="end">158 / 158</text>
<text x="510" y="58" font-size="13" text-anchor="end">185 / 185</text>
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 158</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 185</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="55.82" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="47.68" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

+4 -3
View File
@@ -40,8 +40,9 @@ XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `Cpu
- a denormal dividend over zero raises divide-by-zero only, not also denormal-operand;
- flush-to-zero also flushes a tiny result that is exact, raising underflow and precision;
- DAZ applies before conversion to an integer;
- an unmasked overflow also records precision.
- DAZ applies before conversion to an integer.
An unmasked overflow records precision only when rounding with an unbounded exponent is inexact (Intel SDM Vol. 1, D.4.2.3, Table D-16). The known-answer cases in `tests/cpu_known_answers.rs` assert this.
None of it has been compared with x86 hardware.
@@ -95,4 +96,4 @@ A feature bit is set only when every instruction of that feature is implemented.
## Rejected on purpose
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
+46 -1
View File
@@ -70,7 +70,8 @@ uses a Win64-aligned stack and terminates with HLT. The result includes the load
guest memory and the entry execution outcome.
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
without guest execution. Without `--report` it writes to `diagnostics/probe`,
where `xenora imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
with their import address table relative virtual addresses. The full inventory,
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
column and records whether each key is registered, its implementation
@@ -498,3 +499,47 @@ compare function. Colour and the stored depth are both read back.
These passes are checked on the GPU with Metal validation against expectations
derived independently from the public semantics; synthetic fixtures only.
### Guest texture binding (descriptor tables)
`GraphicsContext` lets a guest command list sample one texture in the pixel
stage through a D3D12-shaped binding. A draw samples only if a root signature
is bound. Draws without one keep the flat-colour path. The supported subset
is fixed. Anything outside it fails with `GraphicsError::Unsupported` when the
object is created, or with an error at execution. A rejected draw never
reaches the backend. Draws recorded before it in the same list have already
run.
| Object | Supported |
| --- | --- |
| `create_descriptor_heap` | Shader-visible `CBV_SRV_UAV` (0) or `SAMPLER` (1) heaps of 1–64 descriptors. RTV, DSV and CPU-only heaps are unsupported. |
| `create_committed_texture2d` | One level of `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71), 1–64 texels per side. BC1 sizes must be multiples of four. Rows are linear: 4 bytes per texel, or 8 bytes per 4×4 block. Xbox tiling is not handled. |
| `create_shader_resource_view` | A `Texture2D` view of mip 0 of a single-level, single-slice 2D texture, in the resource's own format. |
| `create_sampler` | Point filtering (`MIN_MAG_MIP_POINT`), clamp addressing on U, V and W, no LOD bias and a minimum LOD of 0. |
| `create_root_signature` | Exactly two pixel-visibility descriptor tables, in either order: one with a single SRV range for `t0`, and one with a single sampler range for `s0` (one descriptor each, space 0). Root constants, root descriptors, CBV and UAV ranges, extra tables or ranges and static samplers are unsupported. |
| `cmd_set_descriptor_heaps` | At most one heap of each type. |
| `cmd_set_graphics_root_descriptor_table` | The base must be a GPU handle to a slot of the bound heap of the table's type. The slot must hold a descriptor when a draw reads it. Changing the heaps or binding a different root signature clears every table. Setting the same heaps or the same root signature again keeps them. |
Descriptor handles follow D3D12 pointer arithmetic: the heap start plus
`index × GetDescriptorHandleIncrementSize` (32 here; guests must query the
value). `offset` returns `None` rather than carry into the next heap. CPU and
GPU handles are separate spaces. A textured draw is a `DrawInstanced` of
one instance of three vertices with start instance 0, starting at any vertex. Zero vertices or
instances draw nothing. The sampled texture must be in `COMMON` or a read-only state that includes
`PIXEL_SHADER_RESOURCE`. The software reference draws at most 4096 pixels. Each vertex record holds a float4 position
at byte 0 and a float4 texture coordinate at byte 16, with a stride of at
least 32. Textured indexed draws are unsupported.
The native backend receives a `TexturedDraw` with the bound level and must
bind it to fragment texture 0 and sampler 0, which are the `tex0` and `samp0` arguments of
the translated `image_sample_lz` pixel stage. `NativeCompute::render_rgba8_sampled_bc1`
binds a BC1 level natively for that purpose. The software reference has no
clipping or depth test. A pixel is covered when its centre lies inside or on
an edge of the triangle. The texture coordinate is interpolated affinely, so
`w = 1` is required, and point sampled with
`min(floor(clamp(u, 0, 1) × width), width − 1)`. It decodes BC1 with the
spec-exact `xenora_texture::decode_bc1`. Apple's hardware rounds BC1's two
interpolated palette entries differently (171/84 against 170/85, measured
on an M5 Pro), so the tests use endpoint colours only. Pipeline
state objects do not exist yet, so the backend, not the guest, chooses the
pixel shader. These entry points are not yet wired to guest imports.
+27
View File
@@ -17,6 +17,33 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values (semantic registry) | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
| `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified |
| `v_mul_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_min_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_max_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_min_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_max_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_xnor_b32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_xnor_b32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_sub_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_sub_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_subrev_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_subrev_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_eq_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_le_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_gt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ne_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ge_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_f_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_t_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_eq_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_le_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_gt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ne_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_ge_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_f_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_t_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified |
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
| `s_endpgm` | SOPP, zero immediate (semantic registry) | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
+3 -2
View File
@@ -32,11 +32,11 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
| VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 |
| VOP2 | 47 | 24 | 22 | 24 | 24 | 24 | 7 | 7 | 11 |
| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 |
| VOP3 | 416 | 28 | 28 | 28 | 28 | 28 | 1 | 1 | 17 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 28 | 44 | 44 | 44 | 44 | 0 | 0 | 9 |
| **Total** | 1465 | 142 | 152 | 162 | 158 | 158 | 18 | 18 | 78 |
| **Total** | 1465 | 169 | 179 | 189 | 185 | 185 | 18 | 18 | 83 |
## Unsupported operand variants
@@ -58,6 +58,7 @@ The table counts distinct variant names per family across registry operand rules
| VOP2 | `vop2_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP3 | `vop3_cmp_vgpr2` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc_hi`, `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOPC | `vopc_vcc_half` | `src_exec`, `src_float_inline`, `src_literal`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
+19 -11
View File
@@ -48,20 +48,19 @@ file of its encoding (`rdna2/vop3.toml`) and has exactly these fields:
| `of` | The `name` of the declared base form |
| `family` | The encoding family of this variant; must differ from the form's |
| `opcode` | The XML opcode in that family |
| `operands` | An operand rule of that family whose kind can encode the base form (today `vop3_vgpr2` for VOP2 vector forms) |
| `operands` | An operand rule of that family that can encode the base form (`vop3_vgpr2` for VOP2 vector forms, `vop3_cmp_vgpr2` for VOPC integer compares) |
| `spec`, `verify` | As for a form |
Everything else (operation, signedness, effects, source order) is inherited
from the base form, and the XML check runs on that inherited declaration with
the variant's family, opcode and operand rule, so the VOP3 operand widths and
formats must agree with it. The generator emits one enum per variant rule (`VectorAluVop3Op` for
`vop3_vgpr2`) holding exactly the declared variants, with `from_word` (encoding
The variant inherits the operation, signedness, source order and SCC and EXEC
effects. Its operand rule determines where the result is written. The XML
check uses the variant's family, opcode and operand rule to validate the
inherited declaration. The generator emits one enum per variant rule
(`VectorAluVop3Op` or `VectorCompareVop3Op`) with `from_word` (encoding
bits, then an explicit match on the OP field), `base()` (the inherited form),
`assembly_name()` and `semantics()`, and one `FORMS` row per variant after the
forms. Because the enum has no undeclared members, an instruction cannot name a
VOP3 encoding that does not exist. Every explicit XML operand of the variant,
destination included, must have the data format of the base operand in the same
role (destination, then the sources in rule order). A variant-only rule says so
VOP3 encoding that does not exist. Corresponding explicit XML operands must
have the same data format by role. A variant-only rule says so
in the data (`variant_only = true`), so the RDNA2 planner does not count it as a
rule that can host new forms. A
variant-only rule (one marked `variant_of` in the generator) cannot be used by a
@@ -75,7 +74,15 @@ the registry: VGPR destination, two VGPR sources, ABS, OP_SEL, CLAMP, OMOD and
NEG clear, and SRC2 the assembler's unused inline zero. `v_add_nc_u32_e64` is its
first variant; adding the VOP3 encoding of another VOP2 form under this rule is
one `[[encoding_variant]]` entry. Wider VOP3 operand rules (scalar and inline
sources, legal modifiers) come with the VOP3 batch.
sources, legal modifiers) need separate rules.
`vop3_cmp_vgpr2` uses the same VGPR source and modifier restrictions and
specifies a scalar destination. It requires a base form with a `lane_mask`
write to implicit VCC, and generates an `sdst_lane_mask` effect on the
variant row. The generator checks the base VCC output and the variant's
explicit scalar mask destination against the XML. An SDST of 106 selects
`vcc_lo`. See [the compare contract](vector-compare.md#11-vop3a-encoding-_e64)
for Wave32 lowering and allowed consumers.
## Fields
@@ -199,7 +206,8 @@ integer as SRC0 and a VGPR pair as VSRC1. All three declare a `relation`,
`scc = "unchanged"`, `vcc = "lane_mask"` and `wave = "wave32"`. The XML's implicit
64-bit VCC output must be present and is accounted for by `lane_mask`. Signedness
still matters for `eq` and `lg`, because the MSL lowering casts signed operands.
`v_cmpx_*` (EXEC writes), the VOP3 encoding and Wave64 stay unsupported.
The VOP3A variants redirect the same Wave32 mask to SDST. EXEC-writing
compares (`v_cmpx_*`) and Wave64 stay unsupported.
A SOPC compare must use an operand rule of the compare kind (`sopc_scalar`: two
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
+38 -4
View File
@@ -122,7 +122,7 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned
## 4. Rejected (controlled translation/reference error, never a silent no-op)
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
- VOP3A compares outside the integer subset in section 11.
- SDWA and DPP forms; float compares; v_cmp_class.
- 16-bit compares in the decoder and translator (the reference interpreters
accept the subset in 2a).
@@ -275,12 +275,11 @@ swapped signedness, without the EXEC mask, without the absent-lane bound
(shader validation aborts on the out-of-range read) or with an inverted join.
The 32-bit readback evidence is local agreement with a specification-derived
reference on Apple M5 Pro. The 16-bit compiler evidence is CPU-only.
There is no RDNA 2 or Xbox hardware evidence.
reference on Apple M5 Pro. There is no RDNA 2 or Xbox hardware evidence.
## 10. Limitations
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares.
- Wave32 only. No `v_cmpx`, SDWA, DPP or float compares. VOP3 encodings cover the 32-bit compares only.
- A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there
is no divergent execution. That needs its own contract.
- The skipped region of a runtime `s_cbranch_vccz` holds only integer vector
@@ -289,3 +288,38 @@ There is no RDNA 2 or Xbox hardware evidence.
- Each thread recomputes up to 32 lanes per compare. The cost grows with the
compare's dependency chain. That is fine for fixtures, and no performance is
claimed.
## 11. VOP3A encoding (`_e64`)
All sixteen 32-bit signed and unsigned compares in section 2 also have a 64-bit
VOP3A encoding. The pinned AMD XML supplies each opcode. Bits 7:0 of the first
word are the scalar destination selector (SDST), in the field named VDST.
Selectors 0–105 name scalar general-purpose registers (SGPRs), and 106 names
`vcc_lo`. All other destinations are rejected. Both SRC0 and SRC1 must name
vector general-purpose registers (VGPRs), and the unused SRC2 must be the
assembler's inline-zero selector (128). ABS, OP_SEL, CLAMP, OMOD and NEG must
be clear. The guide describes CLAMP on compares as enabling floating-point
exception signaling (§6.5, p. 48 and §12.9.1, p. 162).
The AMD guide's compare-specific text (§3.9, pp. 19–20 and §13.3.3, p. 252)
specifies an SGPR destination for this encoding. The generic VDST label in
§12.9.1 (p. 162) and §13.3.4 Table 82 (pp. 257–258) describes the VOP3A field
as a VGPR destination. The pinned XML identifies VDST for these compares as
`OPR_SREG`, with the Wave64 pair described by `FMT_NUM_M64`. The Wave32 write
occupies one 32-bit SGPR. The guide defines 32 work-items in §2.1 (pp. 7–8),
32-bit SGPRs in §3.1 Table 2 (p. 12) and one compare result bit per lane in
§12.9 (p. 150). Wave64 stays unsupported.
LLVM 23 `llvm-mc` for gfx1030 with `+wavefrontsize32` assembles
`v_cmp_eq_u32_e64 s4, v1, v2` as bytes `04 00 c2 d4 01 05 02 02`.
Selecting `vcc_lo` changes the first byte to `6a`. The decoder tests cover
the assembler's words for all sixteen forms. This is encoding evidence.
The compare replaces all 32 bits of SDST with the lane mask from section 3,
including zero bits for inactive and absent lanes. It leaves SCC and EXEC
unchanged. VCC is written only when SDST selects `vcc_lo`, which uses the
same lowering and consumers as the VOPC form, including `s_cbranch_vccz`.
Every other SDST is tracked as a runtime-only SGPR result, including under
empty EXEC. Translation rejects later reads of that result, including reads
through resource descriptors. The runtime branch region rules in section 6
also apply here.
+324
View File
@@ -87,6 +87,330 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_i32_i24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_i32_i24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_hi_i32_i24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_i32_i24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_u32_u24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_u32_u24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_hi_u32_u24_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_u32_u24_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_min_i32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_i32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_max_i32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_i32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_min_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_max_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_xnor_b32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_xnor_b32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_sub_nc_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_sub_nc_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_subrev_nc_u32_e64"
encoding = "VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_subrev_nc_u32_e32`"
representation = "8 B"
lowering = "per-thread typed integer template of the VOP2 form"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_eq_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_le_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_gt_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ne_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ge_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_f_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_t_i32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_eq_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_le_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_gt_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ne_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_ge_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_f_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_t_u32_e64"
encoding = "VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error"
representation = "8 B"
lowering = "per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "buffer_store_dword"
encoding = "MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags"
+9
View File
@@ -0,0 +1,9 @@
# Testing and acceptance
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
- [Baseline acceptance](phase-02-baseline.md) and [Phase 01 assurance](phase01-assurance.md) — Candidate-specific evidence.
- [Independent reviews](review-log.md) — Review findings and acceptance records.
- [Mutation testing](mutation.md) and [benchmark protocol](benchmarks.md) — Sensitivity and timing requirements.
- [Infrastructure QA tooling](infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
+7
View File
@@ -1,5 +1,12 @@
# Independent review
## gfx1030 form acceptance
Use the [AMD RDNA2 desktop GPU (gfx1030) form acceptance rule](shader-form-acceptance.md) for entries that
promote instruction forms to `fixture verified`. Record only completed runs with
a named commit, independent runner, host, exact commands and real counts. Raw
logs stay under ignored `artifacts/acceptance/<commit>/`.
## R1. First synthetic compute checkpoint, 2026-11-22
Reviewed the integrated working tree before a candidate commit. The findings below cover the first checkpoint.
+129
View File
@@ -0,0 +1,129 @@
# AMD RDNA2 desktop GPU (gfx1030) form acceptance
This is the promotion rule for AMD RDNA2 desktop GPU (`gfx1030`) instruction
forms in [`docs/status.toml`](../status.toml). It implements the documentation
step of [#302](https://github.com/ranveersoni98/Xenora/issues/302). It does not
claim Xbox-hardware verification or commercial-game compatibility.
The **LLVM three-way decoder check** is the ignored `llvm-mc` comparison in
[`crates/decoder/tests/gfx1030.rs`](../../crates/decoder/tests/gfx1030.rs). It
compares Xenora's decoder with LLVM's gfx1030 decoder over the fixture and
probe encodings; it is encoding evidence, not GPU-semantics evidence.
## Status meanings
| Status | Meaning |
| --- | --- |
| `local known-answer test passed` | The implementation's CPU known-answer test passed locally. This is not independent acceptance. |
| `local Apple M5 readback passed; acceptance pending` | A local native Metal readback passed with validation, but the independence and evidence rules below are incomplete. |
| `fixture verified on Apple M5` | The host-qualified spelling used by three existing rows. `scripts/audit/status.py` treats it as equivalent to `fixture verified`; existing rows do not need re-acceptance solely for this wording. New entries should normally use `fixture verified` and record the host in the review log. |
| `fixture verified` | The form or documented family batch passed independent acceptance at a named commit, with CPU, LLVM and native Metal evidence recorded. |
A skipped test is not a pass. A shader compile without readback is not GPU
verification. Agreement with a spec-derived reference is not agreement with
Xbox hardware.
## Independence
> **Proposed policy, pending maintainer confirmation.** The independence rule in
> this section is the proposal from #302. Do not use it to promote forms until
> the maintainer confirms or revises it.
The person running the acceptance pass must not be the author of the pull
request that added the form being accepted. The runner may use the existing
tests and commands, but must record their own results and review the evidence.
If the maintainer runs the pass for forms they authored, the review-log entry
must say so explicitly; that exception is not silent self-certification.
The expected values used by the test must remain independent of the production
decoder, translator or Metal backend. Do not change fixtures, thresholds or test
filters to make a form pass.
## Acceptance procedure
1. **Use a clean named commit.** Start from a clean checkout of `main` at the
commit being accepted. Record the full commit hash. Do not accept a working
tree with uncommitted changes.
2. **Name the scope.** List each form, or a family batch with an explicit list of
forms, covered by the pass. A family name alone is not enough.
3. **Run the standard gates.** Format, Clippy, workspace tests, fixture checks,
the LLVM three-way decoder check and the native GPU suite must pass. Record
exact commands, environment variables and pass/fail/skip counts.
4. **Run the form's CPU and Metal tests.** The CPU known-answer/reference tests
and the native Metal readback must both pass. Metal API and shader validation
must be enabled. Use a targeted test filter where useful, but keep the full
standard-gate result for the same commit.
5. **Check negative cases.** Unsupported encodings, malformed inputs and any
documented rejection cases for the form must still pass.
6. **Save raw logs.** Put raw output under ignored
`artifacts/acceptance/<commit>/`. Do not commit raw logs.
7. **Write the review-log summary.** Add an entry to
[`review-log.md`](review-log.md) with the commit, runner's GitHub login, host,
scope, exact commands or log path, and CPU/LLVM/Metal results. A reviewer
confirms the entry if the runner is not the maintainer.
8. **Promote only passed forms.** Change `cpu` and `gpu` in `docs/status.toml`
only for forms covered by a passing entry. Regenerate the status tables and
progress graphic, then run `python3 scripts/audit/status.py --check`.
## Standard gate set
Run on native Apple Silicon. The exact host and tool versions belong in the
review-log entry.
```sh
export CARGO_BUILD_JOBS=2
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
cargo test --locked --workspace
scripts/assemble-fixture.sh --check
LLVM_BIN="$(brew --prefix llvm)/bin" \
cargo test --locked -p xenora-decoder --test gfx1030 -- --include-ignored --nocapture
cargo test --locked -p xenora-semantic-review
scripts/test-gpu.sh
python3 scripts/audit/status.py --check
```
For a targeted semantic-review pass, record the filter and use the same Metal
validation environment as `scripts/test-gpu.sh`:
```sh
cargo test --locked -p xenora-semantic-review <cpu-test-filter>
MTL_DEBUG_LAYER=1 \
MTL_SHADER_VALIDATION=1 \
MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 \
MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1 \
cargo test --locked -p xenora-semantic-review <native-metal-test-filter> \
-- --ignored --exact --nocapture --test-threads=1
```
A targeted filter does not replace the standard gate set; it attributes the
result to a form or family batch.
## Review-log entry
Use one row per commit and scope. Add rows to
[`review-log.md`](review-log.md); keep raw output only in `artifacts/`.
| Date | Commit | Runner (GitHub login) | Host and tools | Forms or batch | Commands / raw log | CPU | LLVM | Metal | Review |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| YYYY-MM-DD | full SHA | @login | Mac, macOS, Xcode, Rust, LLVM | explicit form list | exact commands and `artifacts/acceptance/<commit>/` path | pass/fail/skip counts | pass/fail counts | pass/fail/skip counts; validation on | reviewer GitHub login or maintainer exception |
Do not write `pass` without counts. Do not count a skipped native test as Metal
evidence.
## Promotion and failures
After a passing entry, set the accepted rows to `fixture verified` and regenerate:
```sh
python3 scripts/audit/status.py
python3 scripts/audit/status.py --check
```
If any required check fails or skips, leave the form pending. Record the commit,
host, command and failure in the review log, and open a separate issue for the
failure. Do not weaken the test or change the expected result in the acceptance
pass.
The automated status-check enforcement proposed in #302 is a separate change.
Until it lands, reviewers must enforce the review-log requirement manually.
-1
View File
@@ -1 +0,0 @@
/target/
-30
View File
@@ -1,30 +0,0 @@
# Audio API coverage
Proprietary Xbox audio DSP APIs are unsupported; this experiment defines only its own fixture services below.
## Original Xenora fixture services
These Win64 calls are defined only for this experiment under
`xenora_audio_fixture.dll`. The host registers them for a single DSP session
and provides a stream handle to trusted synthetic guest code.
| Import | Arguments |
| --- | --- |
| `SubmitPcm` | RCX stream handle, RDX guest PCM address, R8 byte length, R9D encoding (1 for S16LE, 2 for F32LE) |
| `ScheduleStart` | RCX stream handle, RDX absolute DSP output-frame clock position |
The result in RAX is 0 for accepted, 1 for an invalid handle, 2 for invalid
input, 3 for exhausted capacity or 4 for session failure. An invalid guest
memory range raises Xenora's checked memory fault. PCM must use complete frames,
be appropriately aligned and fit the configured transfer limit. Acceptance
places a command into the FIFO and does not report completed playback.
## Public references
- [Microsoft GDK overview](https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/intro/overviews/introduction)
- [Microsoft XAudio2 introduction](https://learn.microsoft.com/en-us/windows/win32/xaudio2/xaudio2-introduction)
- [Microsoft WAVEFORMATEX frame alignment](https://learn.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatex)
- [Microsoft x64 calling convention](https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention)
- [Apple Audio Queue Services](https://developer.apple.com/documentation/audiotoolbox/audio-queue-services)
- [Apple AudioQueueNewOutput](https://developer.apple.com/documentation/audiotoolbox/audioqueuenewoutput)
- [Apple AudioQueueGetCurrentTime](https://developer.apple.com/documentation/audiotoolbox/audioqueuegetcurrenttime)
-72
View File
@@ -1,72 +0,0 @@
# Architecture
```text
Host PCM ───────────────┐
Gate 6 AudioSubsystem ──┼─> Session staging ─> FIFO commands ─> per-stream PCM
Synthetic guest ABI ────┘ │
v
rate conversion, gain, mix
│
v
offline read or Audio Queue worker
```
A clone of a `Session` shares one bounded state and output clock. The host opens
streams using validated channel layouts and rates. Handles contain a slot and a
generation unique within the process. Session ownership is enforced by exact
matches in the session's tables. Slots allocated again get new handles. A staged
PCM buffer belongs to one stream. Successful submission makes the buffer
in-flight until the renderer transfers its samples into that stream's queue and
retires the handle. The renderer applies pending commands in ticket order at
the beginning of each block. Closing a stream retires its staged buffers and
drops its pending commands. Closing a session invalidates all handles.
There is one active renderer per session. Relative to its clock, a stream can
start or resume at an exact output frame and can be paused without consuming
source samples. Gains apply per output channel. Mono duplicates into stereo.
Stereo downmix is the arithmetic mean. The mixer accumulates in FP64 and clips
once to normalized FP32. Linear interpolation tracks input phase as an integer
ratio of rates across input and output boundaries. On shortage it inserts
silence and holds the remaining source state. Pause and future starts do not
count as underruns. The renderer never waits for input.
Hard limits bound the stream, source-frame, buffer and command counts per
session. PCM allocations and destination capacity are checked before admission.
A failed admission leaves existing audio in place. The DSP serializes its
state with a mutex. Decoding, copying and retiring PCM can allocate on producer
or worker threads. The CoreAudio callback only identifies a reclaimed buffer
and updates atomics. The worker refills three platform-owned buffers and uses
synchronous queue disposal off the callback thread. If disposal fails, it
returns the status and retains callback context for potential late callbacks.
Audio Queue startup queries hardware support through the system framework at
runtime. If the default device cannot open or start at the requested format,
the call returns the platform error. The worker starts with three silence
buffers so startup can fail without consuming source PCM. It currently polls
at 1 ms and requires at least four milliseconds of audio per buffer. Timing
metrics include observed buffer returns, periodic queue-clock samples and
discontinuities. A discontinuity invalidates the queue lead estimate for
that playback session. Stopping flushes the device queue. A device error after
rendering has begun can discard an already mixed block.
## Integration boundary
The optional adapter uses Xenora's existing typed argument reader, import
registry and checked guest memory. The Gate 6 bridge preserves its producer,
PCM storage and existing format IDs. It submits through the same host API as
other PCM clients. It handles a finite batch based on capacity and preserves
source bytes when a submission fails. It does not implicitly replace the
existing application audio path.
## Current limits
- Interleaved S16LE and normalized finite F32LE input. Interleaved FP32 output.
- Mono and stereo at 8 through 192 kHz. No surround, effects graph, codecs,
device selection, hot-plug recovery or drift compensation.
- The linear resampler does not implement anti-alias filtering for downsampling.
- Native output was tested on one M5 Pro. Other Apple Silicon devices depend on
runtime Audio Queue support and remain unmeasured in this experiment.
- The standalone crate does not add shared app, runtime or FFI changes. Wiring
the bridge into Gate 6's app session and native device lifetime requires
coordination with the Gate 6 and runtime owners. Xenora #284 and #293 identify
the overlapping FFI work.
-9
View File
@@ -1,9 +0,0 @@
# Changelog
## Unreleased
- Added a standalone bounded PCM mixer with generation-tracked handles,
ordered commands, synchronized stream starts and deterministic offline output.
- Added opt-in native ARM64 CoreAudio output and diagnostics.
- Added a Gate 6 PCM bridge and typed services for original synthetic Xenora
fixtures.
-207
View File
@@ -1,207 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "dispatch2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags",
"dispatch2",
"objc2",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags",
"objc2",
]
[[package]]
name = "objc2-metal"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
dependencies = [
"bitflags",
"objc2",
"objc2-core-foundation",
"objc2-foundation",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "xenora-audio-dsp"
version = "0.1.0"
dependencies = [
"xenora-ffi",
"xenora-loader",
]
[[package]]
name = "xenora-decoder"
version = "0.1.0"
dependencies = [
"xenora-isa",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
"xenora-metal",
"xenora-shader",
]
[[package]]
name = "xenora-isa"
version = "0.1.0"
[[package]]
name = "xenora-loader"
version = "0.1.0"
dependencies = [
"libc",
"sha2",
]
[[package]]
name = "xenora-metal"
version = "0.1.0"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-metal",
"xenora-texture",
]
[[package]]
name = "xenora-shader"
version = "0.1.0"
dependencies = [
"xenora-decoder",
]
[[package]]
name = "xenora-texture"
version = "0.1.0"
-20
View File
@@ -1,20 +0,0 @@
[package]
name = "xenora-audio-dsp"
version = "0.1.0"
edition = "2024"
rust-version = "1.100"
license = "GPL-3.0-or-later"
description = "Bounded PCM mixer and native macOS audio output experiment"
publish = false
[workspace]
[features]
xenora = ["dep:xenora-loader", "dep:xenora-ffi"]
[dependencies]
xenora-loader = { path = "../../crates/loader", optional = true }
xenora-ffi = { path = "../../crates/ffi", optional = true }
[lints.rust]
unsafe_op_in_unsafe_fn = "deny"
-75
View File
@@ -1,75 +0,0 @@
# Native audio DSP experiment
This Rust library mixes bounded PCM streams to deterministic offline output or the
default CoreAudio playback queue on Apple Silicon. The optional `xenora` feature
exposes the mixer through two original synthetic runtime services and can ingest
PCM from the existing Gate 6 queue.
## Build and test
Run from this directory with Rust 1.100 or later on Apple Silicon macOS.
```sh
cargo test --locked --target aarch64-apple-darwin --all-features
cargo clippy --locked --target aarch64-apple-darwin --all-features --all-targets -- -D warnings
cargo fmt --check
cargo run --locked --release --target aarch64-apple-darwin --example measure
```
The offline benchmark submits and mixes eight stereo PCM streams. Pass
`-- --play` to the same example for a brief, quiet tone on the default CoreAudio
output, with queue timing and underrun counters. Normal tests stay silent.
## Offline rendering
```rust
use xenora_audio_dsp::{Channels, Encoding, Format, Limits, Session};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let output = Format::new(48_000, Channels::Stereo)?;
let source = Format::new(48_000, Channels::Mono)?;
let session = Session::new(output, Limits::default())?;
let stream = session.open_stream(source)?;
session.submit_pcm(stream, Encoding::S16Le, &[0, 0x40, 0, 0xc0])?;
let mut pcm = [0.0; 4];
session.renderer()?.render(&mut pcm)?;
assert_eq!(pcm, [0.5, 0.5, -0.5, -0.5]);
Ok(())
}
```
To ingest Gate 6 audio, make a DSP stream with the same rate and channel count
and call `xenora::transfer_gate6(&mut gate6_audio, &session, stream, 256)`.
That function only drains frames after the DSP accepts them. Call it again
after rendering if the destination has no free frames.
An original trusted guest fixture can call
`xenora::register_fixture_services(&mut registry, &session)` from its host
setup. The host supplies the guest with the raw handle for the fixture's
stream. The [API coverage report](API-COVERAGE.md) describes the exact
synthetic call contract.
## Local verification
The standalone experiment was checked on Apple M5 Pro, macOS 27.2.1,
Rust 1.100.0 and Xcode 27.2. The release example was a native arm64 Mach-O
linked to AudioToolbox and libSystem.
| Check | Observed result |
| --- | --- |
| ARM64 DSP and adapter tests | 15 passed, including 100 session lifecycle cycles |
| Existing ARM64 Xenora workspace tests | 486 passed, 22 ignored |
| Eight streams, 48 kHz, 256-frame blocks | 9.13 µs median and 9.42 µs p95 to submit and mix; 3.63 µs median for mixing and command retirement alone |
| Process memory in the offline benchmark | 6,471,680 bytes maximum resident set, with 278,528 bytes reserved for PCM at a fully staged block |
| Default CoreAudio output, 48 kHz, 256-frame buffers | 47 buffer returns, 12,032 DSP frames submitted, zero DSP underrun frames or queue timeline discontinuities |
| Timing on that CoreAudio run | 83.11 ms to first worker-observed buffer return from the start call, and a sampled queue lead of 1,622 frames (33.8 ms) |
The device measurement includes startup and worker scheduling. Queue lead is
an estimate on the CoreAudio sample timeline. Neither value measures acoustic
latency. Three buffers carry 768 initial silence frames (16 ms at 48 kHz) so
device startup failure leaves the DSP timeline and PCM unchanged.
See the [architecture](ARCHITECTURE.md) for ownership, limits, scheduling and
remaining work. This is a local AI-assisted experiment with independent
agent review of the resampling expectations and Audio Queue ownership.
Maintainer ownership review and human acceptance remain pending.
-111
View File
@@ -1,111 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::hint::black_box;
use std::time::Instant;
use xenora_audio_dsp::{Channels, Encoding, Format, Limits, Session};
fn main() -> Result<(), Box<dyn std::error::Error>> {
match std::env::args().nth(1).as_deref() {
None => offline(),
Some("--play") => native(),
_ => Err("usage: measure [--play]".into()),
}
}
fn offline() -> Result<(), Box<dyn std::error::Error>> {
const BLOCK: usize = 256;
const VOICES: usize = 8;
const ITERATIONS: usize = 1500;
let format = Format::new(48_000, Channels::Stereo)?;
let session = Session::new(format, Limits::default())?;
let inputs = (0..VOICES)
.map(|_| session.open_stream(format))
.collect::<Result<Vec<_>, _>>()?;
let mut renderer = session.renderer()?;
let pcm = [0x00, 0x04, 0x00, 0xfc].repeat(BLOCK);
let mut output = [0.0; 2 * BLOCK];
let mut times = Vec::with_capacity(ITERATIONS);
let mut mix_times = Vec::with_capacity(ITERATIONS);
let mut peak_bytes = 0;
for _ in 0..100 {
for &stream in &inputs {
session.submit_pcm(stream, Encoding::S16Le, &pcm)?;
}
renderer.render(black_box(&mut output))?;
}
for _ in 0..ITERATIONS {
let start = Instant::now();
for &stream in &inputs {
session.submit_pcm(stream, Encoding::S16Le, &pcm)?;
}
let staged_at = Instant::now();
renderer.render(black_box(&mut output))?;
mix_times.push(staged_at.elapsed().as_nanos());
times.push(start.elapsed().as_nanos());
}
for &stream in &inputs {
session.submit_pcm(stream, Encoding::S16Le, &pcm)?;
}
peak_bytes = peak_bytes.max(session.metrics()?.reserved_sample_bytes);
renderer.render(&mut output)?;
let metrics = session.metrics()?;
times.sort_unstable();
mix_times.sort_unstable();
assert_eq!((output[0], output[1]), (0.25, -0.25));
assert_eq!(metrics.underrun_stream_frames, 0);
println!("Offline: {ITERATIONS} × {BLOCK} frames, {VOICES} stereo streams, 48000 Hz");
println!(
"submit+mix p50={} ns p95={} ns; mix p50={} ns p95={} ns",
times[ITERATIONS / 2],
times[ITERATIONS * 95 / 100],
mix_times[ITERATIONS / 2],
mix_times[ITERATIONS * 95 / 100]
);
println!(
"Reserved PCM payload at one fully staged block: {peak_bytes} bytes; staging high-water={} source frames",
metrics.peak_staging_frames
);
Ok(())
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
fn native() -> Result<(), Box<dyn std::error::Error>> {
use std::time::Duration;
use xenora_audio_dsp::coreaudio::Playback;
let format = Format::new(48_000, Channels::Stereo)?;
let limits = Limits {
frames_per_stream: 24_000,
staging_frames: 24_000,
..Limits::default()
};
let session = Session::new(format, limits)?;
let stream = session.open_stream(format)?;
let pcm = (0..20_000)
.flat_map(|frame| {
let envelope = (frame as f32 / 500.0)
.min(1.0)
.min((19_999 - frame) as f32 / 500.0);
let sample =
(frame as f32 * 220.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.015 * envelope;
[sample.to_le_bytes(); 2].into_iter().flatten()
})
.collect::<Vec<_>>();
session.submit_pcm(stream, Encoding::F32Le, &pcm)?;
let playback = Playback::start(&session, 256)?;
std::thread::sleep(Duration::from_millis(260));
let measured = playback.stop()?;
let metrics = session.metrics()?;
assert!(measured.buffer_callbacks > 0);
assert!(measured.queue_clock_frames.is_some_and(|frames| frames > 0));
assert_eq!(metrics.underrun_stream_frames, 0);
assert_eq!(metrics.output_frames, measured.submitted_frames);
println!("Native playback: {measured:?}");
println!("Session: {metrics:?}");
Ok(())
}
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
fn native() -> Result<(), Box<dyn std::error::Error>> {
Err("native playback requires Apple Silicon macOS".into())
}
-487
View File
@@ -1,487 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native ARM64 Audio Queue output. Only the worker calls into the DSP.
use crate::{AudioError, Format, Renderer, Session};
use std::ffi::c_void;
use std::fmt;
use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, mpsc};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
const BUFFER_COUNT: usize = 3;
const UNAVAILABLE: u64 = u64::MAX;
#[derive(Debug)]
pub enum PlaybackError {
Dsp(AudioError),
CoreAudio {
operation: &'static str,
status: i32,
},
InvalidBuffer,
InvalidBlockSize,
Thread(std::io::Error),
WorkerStopped,
}
impl fmt::Display for PlaybackError {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Dsp(err) => write!(out, "DSP playback: {err}"),
Self::CoreAudio { operation, status } => {
write!(out, "{operation} failed (OSStatus {status})")
}
Self::InvalidBuffer => out.write_str("CoreAudio returned an invalid PCM buffer"),
Self::InvalidBlockSize => out.write_str("invalid CoreAudio block size"),
Self::Thread(err) => write!(out, "could not start the audio worker: {err}"),
Self::WorkerStopped => out.write_str("audio worker stopped unexpectedly"),
}
}
}
impl std::error::Error for PlaybackError {}
impl From<AudioError> for PlaybackError {
fn from(error: AudioError) -> Self {
Self::Dsp(error)
}
}
type Result<T> = std::result::Result<T, PlaybackError>;
#[derive(Clone, Copy, Debug, Default)]
pub struct PlaybackMetrics {
pub buffer_callbacks: u64,
pub submitted_frames: u64,
pub priming_frames: u64,
pub queue_clock_frames: Option<u64>,
pub queued_lead_estimate_frames: Option<u64>,
pub time_to_first_return_observed: Option<Duration>,
pub timeline_discontinuities: u64,
}
struct Shared {
stop: AtomicBool,
buffers: [AtomicPtr<QueueBuffer>; BUFFER_COUNT],
returned: AtomicU32,
callbacks: AtomicU64,
submitted: AtomicU64,
priming: AtomicU64,
queue_clock: AtomicU64,
lead: AtomicU64,
first_return: AtomicU64,
discontinuities: AtomicU64,
}
impl Default for Shared {
fn default() -> Self {
Self {
stop: AtomicBool::new(false),
buffers: std::array::from_fn(|_| AtomicPtr::new(ptr::null_mut())),
returned: AtomicU32::new(0),
callbacks: AtomicU64::new(0),
submitted: AtomicU64::new(0),
priming: AtomicU64::new(0),
queue_clock: AtomicU64::new(UNAVAILABLE),
lead: AtomicU64::new(UNAVAILABLE),
first_return: AtomicU64::new(UNAVAILABLE),
discontinuities: AtomicU64::new(0),
}
}
}
impl Shared {
fn metrics(&self) -> PlaybackMetrics {
let read = |value: &AtomicU64| value.load(Ordering::Relaxed);
let clock = read(&self.queue_clock);
let first = read(&self.first_return);
let lead = read(&self.lead);
let submitted = read(&self.submitted);
PlaybackMetrics {
buffer_callbacks: read(&self.callbacks),
submitted_frames: submitted,
priming_frames: read(&self.priming),
queue_clock_frames: (clock != UNAVAILABLE).then_some(clock),
queued_lead_estimate_frames: (lead != UNAVAILABLE).then_some(lead),
time_to_first_return_observed: (first != UNAVAILABLE)
.then(|| Duration::from_nanos(first)),
timeline_discontinuities: read(&self.discontinuities),
}
}
}
/// A native output queue opened at runtime with the session's format on the default device.
pub struct Playback {
shared: Arc<Shared>,
worker: Option<JoinHandle<Result<()>>>,
}
impl Playback {
pub fn start(session: &Session, frames_per_buffer: usize) -> Result<Self> {
let format = session.output_format()?;
let min = (format.rate() as usize).div_ceil(250); // Four milliseconds per buffer.
let max = session.live()?.limits.render_frames.min(4096);
if !(min..=max).contains(&frames_per_buffer) {
return Err(PlaybackError::InvalidBlockSize);
}
let renderer = session.renderer()?;
let shared = Arc::new(Shared::default());
let worker_shared = Arc::clone(&shared);
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
let worker = thread::Builder::new()
.name("xenora-audio".into())
.spawn(move || {
play(
renderer,
format,
frames_per_buffer,
&worker_shared,
ready_tx,
)
})
.map_err(PlaybackError::Thread)?;
if ready_rx.recv().is_err() {
worker.join().map_err(|_| PlaybackError::WorkerStopped)??;
return Err(PlaybackError::WorkerStopped);
}
Ok(Self {
shared,
worker: Some(worker),
})
}
pub fn metrics(&self) -> PlaybackMetrics {
self.shared.metrics()
}
pub fn stop(mut self) -> Result<PlaybackMetrics> {
self.finish()?;
Ok(self.metrics())
}
fn finish(&mut self) -> Result<()> {
self.shared.stop.store(true, Ordering::Release);
match self.worker.take() {
Some(worker) => worker.join().map_err(|_| PlaybackError::WorkerStopped)?,
None => Ok(()),
}
}
}
impl Drop for Playback {
fn drop(&mut self) {
let _ = self.finish();
}
}
fn play(
mut renderer: Renderer,
format: Format,
frames: usize,
shared: &Arc<Shared>,
ready: mpsc::SyncSender<()>,
) -> Result<()> {
let bytes_per_frame = (format.channels().count() * size_of::<f32>()) as u32;
let description = StreamDescription {
sample_rate: f64::from(format.rate()),
format: u32::from_be_bytes(*b"lpcm"),
flags: 1 | (1 << 3), // kLinearPCMFormatFlagIsFloat | kLinearPCMFormatFlagIsPacked
bytes_per_packet: bytes_per_frame,
frames_per_packet: 1,
bytes_per_frame,
channels_per_frame: format.channels().count() as u32,
bits_per_channel: 32,
reserved: 0,
};
let byte_count = frames as u32 * bytes_per_frame;
let mut queue = NativeQueue::new(&description, shared)?;
let mut buffers = [None; BUFFER_COUNT];
let result = (|| {
for (index, slot) in buffers.iter_mut().enumerate() {
let buffer = queue.allocate(byte_count)?;
shared.buffers[index].store(buffer.as_ptr(), Ordering::Release);
*slot = Some(buffer);
}
// A failed allocation, enqueue or start must leave the source and DSP clock intact.
for buffer in buffers.into_iter().flatten() {
queue.enqueue(buffer, byte_count, None)?;
shared.priming.fetch_add(frames as u64, Ordering::Relaxed);
}
let clock_start = Instant::now();
status("AudioQueueStart", unsafe {
AudioQueueStart(queue.raw(), ptr::null())
})?;
if ready.send(()).is_err() {
return Ok(());
}
let mut next_clock_read = clock_start;
while !shared.stop.load(Ordering::Acquire) {
let returned = shared.returned.swap(0, Ordering::Acquire);
if returned != 0 {
let elapsed = clock_start
.elapsed()
.as_nanos()
.min(u128::from(UNAVAILABLE - 1)) as u64;
let _ = shared.first_return.compare_exchange(
UNAVAILABLE,
elapsed,
Ordering::Relaxed,
Ordering::Relaxed,
);
for (index, slot) in buffers.iter().enumerate() {
if returned & (1 << index) != 0 {
queue.enqueue(
slot.ok_or(PlaybackError::InvalidBuffer)?,
byte_count,
Some(&mut renderer),
)?;
shared.submitted.fetch_add(frames as u64, Ordering::Relaxed);
}
}
}
let now = Instant::now();
if now >= next_clock_read {
queue.observe_clock(shared);
next_clock_read = now + Duration::from_millis(10);
}
thread::sleep(Duration::from_millis(1));
}
Ok(())
})();
shared.stop.store(true, Ordering::Release);
let disposal = queue.dispose();
result.and(disposal)
}
struct NativeQueue {
queue: Option<NonNull<c_void>>,
callback_context: *const Shared,
timeline: *mut c_void,
}
impl NativeQueue {
fn new(description: &StreamDescription, shared: &Arc<Shared>) -> Result<Self> {
let context = Arc::into_raw(Arc::clone(shared));
let mut queue = ptr::null_mut();
// SAFETY: matching C ABI. The separately retained context survives until synchronous disposal.
let result = unsafe {
AudioQueueNewOutput(
description,
returned_buffer,
context.cast_mut().cast(),
ptr::null(),
ptr::null(),
0,
&mut queue,
)
};
let Some(queue) = NonNull::new(queue) else {
// With no queue there is no callback registration to retire.
unsafe { drop(Arc::from_raw(context)) };
return status("AudioQueueNewOutput", result).and(Err(PlaybackError::InvalidBuffer));
};
let mut native = Self {
queue: Some(queue),
callback_context: context,
timeline: ptr::null_mut(),
};
status("AudioQueueNewOutput", result)?;
status("AudioQueueCreateTimeline", unsafe {
AudioQueueCreateTimeline(native.raw(), &mut native.timeline)
})?;
if native.timeline.is_null() {
return Err(PlaybackError::InvalidBuffer);
}
Ok(native)
}
fn raw(&self) -> *mut c_void {
self.queue.unwrap().as_ptr()
}
fn allocate(&self, byte_count: u32) -> Result<NonNull<QueueBuffer>> {
let mut out = ptr::null_mut();
status("AudioQueueAllocateBuffer", unsafe {
AudioQueueAllocateBuffer(self.raw(), byte_count, &mut out)
})?;
NonNull::new(out).ok_or(PlaybackError::InvalidBuffer)
}
fn enqueue(
&self,
mut buffer: NonNull<QueueBuffer>,
byte_count: u32,
renderer: Option<&mut Renderer>,
) -> Result<()> {
// SAFETY: the worker owns a fresh buffer or has acquired a completion signal.
let storage = unsafe { buffer.as_mut() };
let data = storage.data.cast::<f32>();
if storage.capacity < byte_count || data.is_null() || !data.is_aligned() {
return Err(PlaybackError::InvalidBuffer);
}
let sample_count = byte_count as usize / size_of::<f32>();
// SAFETY: retained queue buffer with checked alignment and complete interleaved frames.
// Initialize storage before creating the Rust f32 slice.
let samples = unsafe {
data.write_bytes(0, sample_count);
std::slice::from_raw_parts_mut(data, sample_count)
};
if let Some(renderer) = renderer {
renderer.render(samples)?;
}
storage.byte_count = byte_count;
status("AudioQueueEnqueueBuffer", unsafe {
AudioQueueEnqueueBuffer(self.raw(), buffer.as_ptr(), 0, ptr::null())
})
}
fn observe_clock(&self, shared: &Shared) {
let mut stamp = TimeStamp::default();
let mut discontinuity = 0;
let status = unsafe {
AudioQueueGetCurrentTime(self.raw(), self.timeline, &mut stamp, &mut discontinuity)
};
if discontinuity != 0 {
shared.discontinuities.fetch_add(1, Ordering::Relaxed);
}
let clock = if status == 0
&& discontinuity == 0
&& stamp.flags & 1 != 0
&& stamp.sample_time.is_finite()
&& stamp.sample_time >= 0.0
{
stamp.sample_time as u64
} else {
UNAVAILABLE
};
shared.queue_clock.store(clock, Ordering::Relaxed);
// Sample lead on the worker using the submission count from this observation.
// After a discontinuity the original submission epoch is no longer reliable.
let lead = if clock != UNAVAILABLE && shared.discontinuities.load(Ordering::Relaxed) == 0 {
let submitted = shared
.submitted
.load(Ordering::Relaxed)
.saturating_add(shared.priming.load(Ordering::Relaxed));
submitted.saturating_sub(clock)
} else {
UNAVAILABLE
};
shared.lead.store(lead, Ordering::Relaxed);
}
fn dispose(&mut self) -> Result<()> {
let Some(queue) = self.queue.take() else {
return Ok(());
};
// SAFETY: called off the callback thread with no locks. On success no more callbacks run.
let result = unsafe { AudioQueueDispose(queue.as_ptr(), 1) };
if result == 0 {
unsafe { drop(Arc::from_raw(self.callback_context)) };
}
// If disposal fails the callback registration may still be live, so retain the context.
status("AudioQueueDispose", result)
}
}
impl Drop for NativeQueue {
fn drop(&mut self) {
let _ = self.dispose();
}
}
unsafe extern "C" fn returned_buffer(
context: *mut c_void,
_: *mut c_void,
buffer: *mut QueueBuffer,
) {
// SAFETY: Audio Queue holds the explicitly retained Arc pointer until synchronous disposal.
let shared = unsafe { &*context.cast::<Shared>() };
if shared.stop.load(Ordering::Acquire) {
return;
}
for (index, slot) in shared.buffers.iter().enumerate() {
if slot.load(Ordering::Acquire) == buffer {
shared.callbacks.fetch_add(1, Ordering::Relaxed);
shared.returned.fetch_or(1 << index, Ordering::Release);
break;
}
}
}
fn status(operation: &'static str, code: i32) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(PlaybackError::CoreAudio {
operation,
status: code,
})
}
}
#[repr(C)]
struct StreamDescription {
sample_rate: f64,
format: u32,
flags: u32,
bytes_per_packet: u32,
frames_per_packet: u32,
bytes_per_frame: u32,
channels_per_frame: u32,
bits_per_channel: u32,
reserved: u32,
}
#[repr(C)]
struct QueueBuffer {
capacity: u32,
data: *mut c_void,
byte_count: u32,
user_data: *mut c_void,
packet_capacity: u32,
packets: *mut c_void,
packet_count: u32,
}
#[repr(C)]
#[derive(Default)]
struct TimeStamp {
sample_time: f64,
host_time: u64,
rate_scalar: f64,
word_clock: u64,
smpte: [u32; 6],
flags: u32,
reserved: u32,
}
#[link(name = "AudioToolbox", kind = "framework")]
unsafe extern "C" {
fn AudioQueueNewOutput(
description: *const StreamDescription,
callback: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut QueueBuffer),
context: *mut c_void,
run_loop: *const c_void,
mode: *const c_void,
flags: u32,
out: *mut *mut c_void,
) -> i32;
fn AudioQueueAllocateBuffer(queue: *mut c_void, size: u32, out: *mut *mut QueueBuffer) -> i32;
fn AudioQueueEnqueueBuffer(
queue: *mut c_void,
buffer: *mut QueueBuffer,
packet_count: u32,
descriptions: *const c_void,
) -> i32;
fn AudioQueueStart(queue: *mut c_void, at: *const TimeStamp) -> i32;
fn AudioQueueCreateTimeline(queue: *mut c_void, timeline: *mut *mut c_void) -> i32;
fn AudioQueueGetCurrentTime(
queue: *mut c_void,
timeline: *mut c_void,
stamp: *mut TimeStamp,
discontinuity: *mut u8,
) -> i32;
fn AudioQueueDispose(queue: *mut c_void, immediate: u8) -> i32;
}
-709
View File
@@ -1,709 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Bounded interleaved PCM mixing, independent of the guest and output device.
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
pub mod coreaudio;
#[cfg(feature = "xenora")]
pub mod xenora;
use std::collections::VecDeque;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
type Frame = [f32; 2];
type Result<T> = std::result::Result<T, AudioError>;
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioError {
InvalidFormat,
InvalidLength,
InvalidSample,
InvalidGain,
InvalidLimits,
InvalidHandle,
WrongStream,
Closed,
RendererBusy,
QueueFull,
BufferBudget,
StreamLimit,
BufferInFlight,
ClockOverflow,
Poisoned,
}
impl fmt::Display for AudioError {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
let detail = match self {
Self::InvalidFormat => "unsupported PCM format",
Self::InvalidLength => "invalid PCM or render length",
Self::InvalidSample => "PCM sample is not finite or is outside the normalized range",
Self::InvalidGain => "invalid channel gain",
Self::InvalidLimits => "invalid DSP resource limits",
Self::InvalidHandle => "invalid, stale, or foreign audio handle",
Self::WrongStream => "audio buffer belongs to a different stream",
Self::Closed => "audio session is closed",
Self::RendererBusy => "audio session already has a renderer",
Self::QueueFull => "audio command queue is full",
Self::BufferBudget => "audio buffer budget exhausted",
Self::StreamLimit => "audio session stream limit reached",
Self::BufferInFlight => "audio buffer is queued for consumption",
Self::ClockOverflow => "audio timeline or handle generation exhausted",
Self::Poisoned => "audio session lock is poisoned",
};
out.write_str(detail)
}
}
impl std::error::Error for AudioError {}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channels {
Mono = 1,
Stereo = 2,
}
impl Channels {
pub const fn count(self) -> usize {
self as usize
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Format {
rate: u32,
channels: Channels,
}
impl Format {
pub fn new(rate: u32, channels: Channels) -> Result<Self> {
if !(8_000..=192_000).contains(&rate) {
return Err(AudioError::InvalidFormat);
}
Ok(Self { rate, channels })
}
pub const fn rate(self) -> u32 {
self.rate
}
pub const fn channels(self) -> Channels {
self.channels
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Encoding {
S16Le,
F32Le,
}
impl Encoding {
pub const fn frame_bytes(self, channels: Channels) -> usize {
let sample_bytes = match self {
Self::S16Le => 2,
Self::F32Le => 4,
};
sample_bytes * channels.count()
}
fn frames(self, channels: Channels, bytes: &[u8]) -> impl Iterator<Item = Result<Frame>> {
bytes
.chunks_exact(self.frame_bytes(channels))
.map(move |chunk| {
let sample = |index: usize| match self {
Self::S16Le => {
let offset = index * 2;
Ok(
f32::from(i16::from_le_bytes([chunk[offset], chunk[offset + 1]]))
/ 32768.0,
)
}
Self::F32Le => {
let offset = index * 4;
let value =
f32::from_le_bytes(chunk[offset..offset + 4].try_into().unwrap());
if (-1.0..=1.0).contains(&value) {
Ok(value)
} else {
Err(AudioError::InvalidSample)
}
}
};
let left = sample(0)?;
let right = if channels == Channels::Stereo {
sample(1)?
} else {
left
};
Ok([left, right])
})
}
}
#[derive(Debug, Clone, Copy)]
pub struct Limits {
pub streams: usize,
pub frames_per_stream: usize,
pub buffers: usize,
pub staging_frames: usize,
pub commands: usize,
pub render_frames: usize,
}
impl Default for Limits {
fn default() -> Self {
Self {
streams: 8,
frames_per_stream: 4096,
buffers: 32,
staging_frames: 8192,
commands: 64,
render_frames: 4096,
}
}
}
impl Limits {
fn check(self) -> Result<()> {
let valid = (1..=64).contains(&self.streams)
&& (1..=65_536).contains(&self.frames_per_stream)
&& self.streams * self.frames_per_stream <= 262_144
&& (1..=256).contains(&self.buffers)
&& (1..=262_144).contains(&self.staging_frames)
&& (1..=4096).contains(&self.commands)
&& (1..=8192).contains(&self.render_frames);
valid.then_some(()).ok_or(AudioError::InvalidLimits)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StreamHandle(u64);
impl StreamHandle {
pub const fn raw(self) -> u64 {
self.0
}
pub const fn from_raw(value: u64) -> Self {
Self(value)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BufferHandle(u64);
struct Pool<T, const TAG: u64>(Vec<Option<(u64, T)>>);
impl<T, const TAG: u64> Pool<T, TAG> {
fn new(capacity: usize) -> Self {
Self(std::iter::repeat_with(|| None).take(capacity).collect())
}
fn insert(&mut self, value: T, full: AudioError) -> Result<u64> {
let index = self.0.iter().position(Option::is_none).ok_or(full)?;
let generation = NEXT_GENERATION
.try_update(Ordering::Relaxed, Ordering::Relaxed, |generation| {
(generation <= (u64::MAX >> 9)).then_some(generation + 1)
})
.map_err(|_| AudioError::ClockOverflow)?;
let handle = (generation << 9) | TAG | index as u64;
self.0[index] = Some((handle, value));
Ok(handle)
}
fn entry(&mut self, handle: u64) -> Result<&mut Option<(u64, T)>> {
self.0
.get_mut((handle & 255) as usize)
.filter(|entry| entry.as_ref().is_some_and(|(id, _)| *id == handle))
.ok_or(AudioError::InvalidHandle)
}
fn get(&mut self, handle: u64) -> Result<&mut T> {
Ok(&mut self.entry(handle)?.as_mut().unwrap().1)
}
fn take(&mut self, handle: u64) -> Result<T> {
Ok(self.entry(handle)?.take().unwrap().1)
}
fn clear(&mut self) {
self.0.fill_with(|| None);
}
}
#[derive(Debug, Clone, Copy)]
pub enum Control {
Gain([f32; 2]),
Mute(bool),
/// Start or resume when the output clock is at least this frame.
StartAt(u64),
Pause,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Metrics {
pub output_frames: u64,
pub commands_applied: u64,
pub commands_cancelled: u64,
pub command_overruns: u64,
pub buffer_overruns: u64,
pub underrun_stream_frames: u64,
pub last_applied: Option<u64>,
pub live_streams: usize,
pub live_buffers: usize,
pub pending_commands: usize,
pub buffered_source_frames: usize,
pub reserved_sample_bytes: usize,
pub peak_staging_frames: usize,
}
struct Stream {
format: Format,
samples: VecDeque<Frame>,
reserved: usize,
phase: u32,
gain: Frame,
muted: bool,
start_at: Option<u64>,
}
impl Stream {
fn next(&mut self, output_rate: u32) -> Option<Frame> {
self.consume_whole_frames(output_rate);
let first = *self.samples.front()?;
let frame = if self.phase == 0 {
first
} else {
let second = self.samples.get(1)?;
let t = self.phase as f32 / output_rate as f32;
std::array::from_fn(|channel| first[channel] + (second[channel] - first[channel]) * t)
};
self.phase += self.format.rate;
self.consume_whole_frames(output_rate);
Some(frame)
}
fn consume_whole_frames(&mut self, output_rate: u32) {
let count = ((self.phase / output_rate) as usize).min(self.samples.len());
if count > 0 {
self.samples.drain(..count);
self.phase -= count as u32 * output_rate;
}
}
}
struct Buffer {
owner: StreamHandle,
frames: Vec<Frame>,
queued: bool,
}
enum Command {
Control(Control),
Buffer(BufferHandle),
}
struct Pending {
ticket: u64,
stream: StreamHandle,
command: Command,
}
struct State {
closed: bool,
renderer: bool,
output: Format,
limits: Limits,
streams: Pool<Stream, 0>,
buffers: Pool<Buffer, 256>,
staging_frames: usize,
commands: VecDeque<Pending>,
next_ticket: u64,
metrics: Metrics,
}
impl State {
fn reserve_command(&mut self) -> Result<u64> {
if self.commands.len() == self.limits.commands {
self.metrics.command_overruns = self.metrics.command_overruns.saturating_add(1);
return Err(AudioError::QueueFull);
}
let ticket = self.next_ticket;
self.next_ticket = ticket.checked_add(1).ok_or(AudioError::ClockOverflow)?;
Ok(ticket)
}
fn take_buffer(&mut self, handle: BufferHandle) -> Result<Buffer> {
let buffer = self.buffers.take(handle.0)?;
self.staging_frames -= buffer.frames.len();
Ok(buffer)
}
fn apply_commands(&mut self) -> Result<()> {
while let Some(pending) = self.commands.pop_front() {
match pending.command {
Command::Control(control) => {
let stream = self.streams.get(pending.stream.0)?;
match control {
Control::Gain(gain) => stream.gain = gain,
Control::Mute(muted) => stream.muted = muted,
Control::StartAt(frame) => stream.start_at = Some(frame),
Control::Pause => stream.start_at = None,
}
}
Command::Buffer(handle) => {
let buffer = self.take_buffer(handle)?;
let stream = self.streams.get(pending.stream.0)?;
stream.reserved -= buffer.frames.len();
stream.samples.extend(buffer.frames);
}
}
self.metrics.commands_applied = self.metrics.commands_applied.saturating_add(1);
self.metrics.last_applied = Some(pending.ticket);
}
Ok(())
}
}
/// A session has one output clock and up to one active renderer.
#[derive(Clone)]
pub struct Session(Arc<Mutex<State>>);
impl Session {
pub fn new(output: Format, limits: Limits) -> Result<Self> {
limits.check()?;
Ok(Self(Arc::new(Mutex::new(State {
closed: false,
renderer: false,
output,
limits,
streams: Pool::new(limits.streams),
buffers: Pool::new(limits.buffers),
staging_frames: 0,
commands: VecDeque::with_capacity(limits.commands),
next_ticket: 0,
metrics: Metrics::default(),
}))))
}
fn lock(&self) -> Result<MutexGuard<'_, State>> {
self.0.lock().map_err(|_| AudioError::Poisoned)
}
fn live(&self) -> Result<MutexGuard<'_, State>> {
let state = self.lock()?;
if state.closed {
Err(AudioError::Closed)
} else {
Ok(state)
}
}
pub fn output_format(&self) -> Result<Format> {
Ok(self.live()?.output)
}
pub fn stream_format(&self, stream: StreamHandle) -> Result<Format> {
Ok(self.live()?.streams.get(stream.0)?.format)
}
/// An upper bound for validation before guest memory is copied.
pub fn max_pcm_bytes(&self, stream: StreamHandle, encoding: Encoding) -> Result<usize> {
let mut state = self.live()?;
let frames = state
.limits
.frames_per_stream
.min(state.limits.staging_frames);
let format = state.streams.get(stream.0)?.format;
Ok(frames * encoding.frame_bytes(format.channels))
}
/// Available source frames at the time of the call. Other producers can consume this capacity.
pub fn available_pcm_frames(&self, stream: StreamHandle) -> Result<usize> {
let mut state = self.live()?;
let staging = state.limits.staging_frames - state.staging_frames;
let capacity = state.limits.frames_per_stream;
let stream = state.streams.get(stream.0)?;
Ok(staging.min(capacity - stream.samples.len() - stream.reserved))
}
pub fn open_stream(&self, format: Format) -> Result<StreamHandle> {
let mut state = self.live()?;
let capacity = state.limits.frames_per_stream;
if capacity < 2 && !format.rate.is_multiple_of(state.output.rate) {
return Err(AudioError::InvalidLimits);
}
if state.streams.0.iter().all(Option::is_some) {
return Err(AudioError::StreamLimit);
}
state
.streams
.insert(
Stream {
format,
samples: VecDeque::with_capacity(capacity),
reserved: 0,
phase: 0,
gain: [1.0; 2],
muted: false,
start_at: Some(0),
},
AudioError::StreamLimit,
)
.map(StreamHandle)
}
/// Cancel queued commands and retire every buffer owned by this stream.
pub fn close_stream(&self, stream: StreamHandle) -> Result<()> {
let mut state = self.live()?;
state.streams.take(stream.0)?;
let before = state.commands.len();
state.commands.retain(|pending| pending.stream != stream);
let cancelled = before - state.commands.len();
state.metrics.commands_cancelled = state
.metrics
.commands_cancelled
.saturating_add(cancelled as u64);
let mut released = 0;
for slot in &mut state.buffers.0 {
if slot
.as_ref()
.is_some_and(|(_, buffer)| buffer.owner == stream)
{
released += slot.take().unwrap().1.frames.len();
}
}
state.staging_frames -= released;
Ok(())
}
pub fn close(&self) -> Result<()> {
let mut state = self.lock()?;
state.closed = true;
state.metrics.commands_cancelled = state
.metrics
.commands_cancelled
.saturating_add(state.commands.len() as u64);
state.commands.clear();
state.streams.clear();
state.buffers.clear();
state.staging_frames = 0;
Ok(())
}
pub fn allocate_pcm(
&self,
stream: StreamHandle,
encoding: Encoding,
bytes: &[u8],
) -> Result<BufferHandle> {
let mut state = self.live()?;
let channels = state.streams.get(stream.0)?.format.channels;
let stride = encoding.frame_bytes(channels);
if bytes.is_empty() || !bytes.len().is_multiple_of(stride) {
return Err(AudioError::InvalidLength);
}
let count = bytes.len() / stride;
if count > state.limits.frames_per_stream
|| count > state.limits.staging_frames - state.staging_frames
|| state.buffers.0.iter().all(Option::is_some)
{
state.metrics.buffer_overruns = state.metrics.buffer_overruns.saturating_add(1);
return Err(AudioError::BufferBudget);
}
let frames = encoding
.frames(channels, bytes)
.collect::<Result<Vec<_>>>()?;
let handle = state.buffers.insert(
Buffer {
owner: stream,
frames,
queued: false,
},
AudioError::BufferBudget,
)?;
state.staging_frames += count;
state.metrics.peak_staging_frames =
state.metrics.peak_staging_frames.max(state.staging_frames);
Ok(BufferHandle(handle))
}
pub fn retire_buffer(&self, buffer: BufferHandle) -> Result<()> {
let mut state = self.live()?;
if state.buffers.get(buffer.0)?.queued {
return Err(AudioError::BufferInFlight);
}
state.take_buffer(buffer)?;
Ok(())
}
/// Transfer a staged PCM buffer to the queue. The next render retires the handle.
pub fn submit_buffer(&self, stream: StreamHandle, buffer: BufferHandle) -> Result<u64> {
let mut state = self.live()?;
let buffer_slot = state.buffers.get(buffer.0)?;
if buffer_slot.owner != stream {
return Err(AudioError::WrongStream);
}
if buffer_slot.queued {
return Err(AudioError::BufferInFlight);
}
let count = buffer_slot.frames.len();
let limit = state.limits.frames_per_stream;
let dest = state.streams.get(stream.0)?;
if count > limit - dest.samples.len() - dest.reserved {
state.metrics.buffer_overruns = state.metrics.buffer_overruns.saturating_add(1);
return Err(AudioError::BufferBudget);
}
let ticket = state.reserve_command()?;
state.streams.get(stream.0)?.reserved += count;
state.buffers.get(buffer.0)?.queued = true;
state.commands.push_back(Pending {
ticket,
stream,
command: Command::Buffer(buffer),
});
Ok(ticket)
}
pub fn submit_pcm(
&self,
stream: StreamHandle,
encoding: Encoding,
bytes: &[u8],
) -> Result<u64> {
let handle = self.allocate_pcm(stream, encoding, bytes)?;
let result = self.submit_buffer(stream, handle);
if result.is_err() {
// A concurrent close may already have retired the allocation.
let _ = self.retire_buffer(handle);
}
result
}
pub fn control(&self, stream: StreamHandle, control: Control) -> Result<u64> {
if let Control::Gain(gain) = control
&& !gain.into_iter().all(|gain| (0.0..=4.0).contains(&gain))
{
return Err(AudioError::InvalidGain);
}
let mut state = self.live()?;
state.streams.get(stream.0)?;
let ticket = state.reserve_command()?;
state.commands.push_back(Pending {
ticket,
stream,
command: Command::Control(control),
});
Ok(ticket)
}
pub fn renderer(&self) -> Result<Renderer> {
let mut state = self.live()?;
if state.renderer {
return Err(AudioError::RendererBusy);
}
state.renderer = true;
Ok(Renderer(self.clone()))
}
pub fn metrics(&self) -> Result<Metrics> {
let state = self.lock()?;
let mut metrics = state.metrics;
metrics.live_streams = state.streams.0.iter().flatten().count();
metrics.live_buffers = state.buffers.0.iter().flatten().count();
metrics.pending_commands = state.commands.len();
metrics.buffered_source_frames = state.staging_frames
+ state
.streams
.0
.iter()
.flatten()
.map(|(_, stream)| stream.samples.len())
.sum::<usize>();
metrics.reserved_sample_bytes = std::mem::size_of::<Frame>()
* (state
.streams
.0
.iter()
.flatten()
.map(|(_, stream)| stream.samples.capacity())
.sum::<usize>()
+ state
.buffers
.0
.iter()
.flatten()
.map(|(_, buffer)| buffer.frames.capacity())
.sum::<usize>());
Ok(metrics)
}
}
/// Exclusive sink for deterministic offline output or native playback.
pub struct Renderer(Session);
impl Renderer {
/// Apply pending commands in ticket order, then render consecutive interleaved FP32 frames.
pub fn render(&mut self, out: &mut [f32]) -> Result<()> {
let mut state = self.0.live()?;
let output = state.output;
let channels = output.channels.count();
if out.is_empty()
|| !out.len().is_multiple_of(channels)
|| out.len() / channels > state.limits.render_frames
{
return Err(AudioError::InvalidLength);
}
let start = state.metrics.output_frames;
let end = start
.checked_add((out.len() / channels) as u64)
.ok_or(AudioError::ClockOverflow)?;
state.apply_commands()?;
let mut underruns = 0;
for (clock, dest) in (start..end).zip(out.chunks_exact_mut(channels)) {
let mut mixed = [0.0f64; 2];
for (_, stream) in state.streams.0.iter_mut().flatten() {
if stream.start_at.is_none_or(|frame| frame > clock) {
continue;
}
let Some(frame) = stream.next(output.rate) else {
underruns += 1;
continue;
};
if stream.muted {
continue;
}
if channels == 1 {
mixed[0] += (f64::from(frame[0]) + f64::from(frame[1]))
* 0.5
* f64::from(stream.gain[0]);
} else {
for channel in 0..2 {
mixed[channel] +=
f64::from(frame[channel]) * f64::from(stream.gain[channel]);
}
}
}
for (dest, value) in dest.iter_mut().zip(mixed) {
*dest = value.clamp(-1.0, 1.0) as f32;
}
}
state.metrics.output_frames = end;
state.metrics.underrun_stream_frames = state
.metrics
.underrun_stream_frames
.saturating_add(underruns);
Ok(())
}
}
impl Drop for Renderer {
fn drop(&mut self) {
if let Ok(mut state) = self.0.lock() {
state.renderer = false;
}
}
}
-147
View File
@@ -1,147 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Adapters for explicitly authored Xenora workloads and the Gate 6 PCM queue.
//! Retail guest imports remain outside this module.
use crate::{AudioError, Channels, Control, Encoding, Format, Session, StreamHandle};
use xenora_ffi::{AudioSubsystem, XENORA_AUDIO_FORMAT_PCM_F32LE, XENORA_AUDIO_FORMAT_PCM_S16LE};
use xenora_loader::cpu::ExitReason;
use xenora_loader::import_table::ImportName;
use xenora_loader::imports::{ImportRegistry, RegistryError, ServiceStatus};
use xenora_loader::runtime::Call;
pub const MODULE: &str = "xenora_audio_fixture.dll";
pub const SUBMIT_PCM: &str = "SubmitPcm";
pub const SCHEDULE_START: &str = "ScheduleStart";
pub const OK: u64 = 0;
pub const INVALID_HANDLE: u64 = 1;
pub const INVALID_DATA: u64 = 2;
pub const RESOURCE_EXHAUSTED: u64 = 3;
pub const SESSION_ERROR: u64 = 4;
/// Transfer whole Gate 6 frames using its existing PCM storage and format.
pub fn transfer_gate6(
audio: &mut AudioSubsystem,
session: &Session,
stream: StreamHandle,
frame_limit: usize,
) -> crate::Result<usize> {
let channels = match audio.channels {
1 => Channels::Mono,
2 => Channels::Stereo,
_ => return Err(AudioError::InvalidFormat),
};
let format = Format::new(audio.sample_rate, channels)?;
if format != session.stream_format(stream)? {
return Err(AudioError::InvalidFormat);
}
let encoding = match audio.format {
XENORA_AUDIO_FORMAT_PCM_S16LE => Encoding::S16Le,
XENORA_AUDIO_FORMAT_PCM_F32LE => Encoding::F32Le,
_ => return Err(AudioError::InvalidFormat),
};
let stride = encoding.frame_bytes(channels);
if !audio.queue.len().is_multiple_of(stride) {
return Err(AudioError::InvalidLength);
}
let count = frame_limit
.min(audio.queue.len() / stride)
.min(session.available_pcm_frames(stream)?);
if count != 0 {
let bytes = count * stride;
session.submit_pcm(stream, encoding, &audio.queue.make_contiguous()[..bytes])?;
audio.queue.drain(..bytes);
}
Ok(count)
}
/// Register the documented Xenora synthetic ABI for a single session.
/// Existing handlers are never replaced.
pub fn register_fixture_services(
registry: &mut ImportRegistry,
session: &Session,
) -> Result<(), RegistryError> {
for symbol in [SUBMIT_PCM, SCHEDULE_START] {
if registry.has_binding(MODULE, symbol) {
return Err(RegistryError::Duplicate {
module: MODULE.into(),
symbol: symbol.into(),
});
}
}
let output = session.clone();
registry.try_register(
MODULE,
ImportName::Name(SUBMIT_PCM.into()),
ServiceStatus::Implemented,
Box::new(move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let stream = StreamHandle::from_raw(call.u64(0)?);
let address = call.u64(1)?;
let length = call.u64(2)? as usize;
let encoding = match call.u32(3)? {
1 => Encoding::S16Le,
2 => Encoding::F32Le,
_ => return Ok(INVALID_DATA),
};
let limit = match output.max_pcm_bytes(stream, encoding) {
Ok(limit) => limit,
Err(err) => return Ok(error_status(err)),
};
let format = match output.stream_format(stream) {
Ok(format) => format,
Err(err) => return Ok(error_status(err)),
};
let alignment = match encoding {
Encoding::S16Le => 2,
Encoding::F32Le => 4,
};
if address == 0
|| !address.is_multiple_of(alignment)
|| length == 0
|| !length.is_multiple_of(encoding.frame_bytes(format.channels()))
|| length > limit
{
return Ok(INVALID_DATA);
}
let mut bytes = vec![0; length];
memory
.read_bytes(address, &mut bytes)
.map_err(ExitReason::MemoryFault)?;
Ok(output
.submit_pcm(stream, encoding, &bytes)
.map_or_else(error_status, |_| OK))
}),
)?;
let output = session.clone();
registry.try_register(
MODULE,
ImportName::Name(SCHEDULE_START.into()),
ServiceStatus::Implemented,
Box::new(move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let stream = StreamHandle::from_raw(call.u64(0)?);
let frame = call.u64(1)?;
Ok(output
.control(stream, Control::StartAt(frame))
.map_or_else(error_status, |_| OK))
}),
)
}
fn error_status(error: AudioError) -> u64 {
match error {
AudioError::InvalidHandle | AudioError::WrongStream => INVALID_HANDLE,
AudioError::InvalidFormat
| AudioError::InvalidLength
| AudioError::InvalidSample
| AudioError::InvalidGain
| AudioError::InvalidLimits => INVALID_DATA,
AudioError::QueueFull | AudioError::BufferBudget | AudioError::StreamLimit => {
RESOURCE_EXHAUSTED
}
_ => SESSION_ERROR,
}
}
-329
View File
@@ -1,329 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::thread;
use xenora_audio_dsp::{AudioError, Channels::*, Control, Encoding::*, Format, Limits, Session};
fn s16(samples: &[i16]) -> Vec<u8> {
samples
.iter()
.flat_map(|sample| sample.to_le_bytes())
.collect()
}
fn fp(samples: &[f32]) -> Vec<u8> {
samples
.iter()
.flat_map(|sample| sample.to_le_bytes())
.collect()
}
fn pcm_value(sample: i16) -> f32 {
f32::from(sample) / 32768.0
}
fn verify_s16(actual: &[f32], expected: &[i16]) {
assert_eq!(actual.len(), expected.len());
for (&actual, &expected) in actual.iter().zip(expected) {
assert!(
(actual - pcm_value(expected)).abs() < 0.000_002,
"{actual} != {expected}"
);
}
}
#[test]
fn mixer_clips_after_accumulation_and_downmixes_stereo() {
let out = Format::new(48_000, Mono).unwrap();
let dsp = Session::new(out, Limits::default()).unwrap();
let a = dsp.open_stream(out).unwrap();
let b = dsp.open_stream(out).unwrap();
let c = dsp
.open_stream(Format::new(48_000, Stereo).unwrap())
.unwrap();
dsp.submit_pcm(a, S16Le, &s16(&[30000, -30000, 30000, 30000]))
.unwrap();
dsp.submit_pcm(b, S16Le, &s16(&[10000, -10000, 30000, 0]))
.unwrap();
dsp.submit_pcm(c, S16Le, &s16(&[0, 0, 0, 0, -30000, -30000, 32767, -32767]))
.unwrap();
let mut result = [0.0; 4];
dsp.renderer().unwrap().render(&mut result).unwrap();
assert_eq!(result[0], 1.0);
verify_s16(&result[1..], &[-32768, 30000, 30000]);
}
#[test]
fn rational_resampler_continues_across_chunks_and_releases_the_last_frame() {
let dsp = Session::new(Format::new(48_000, Stereo).unwrap(), Limits::default()).unwrap();
let stream = dsp.open_stream(Format::new(32_000, Mono).unwrap()).unwrap();
dsp.submit_pcm(stream, S16Le, &s16(&[0, 3000])).unwrap();
let mut render = dsp.renderer().unwrap();
let mut first = [0.0; 4];
render.render(&mut first).unwrap();
dsp.submit_pcm(stream, S16Le, &s16(&[6000, 9000, 12000]))
.unwrap();
let mut second = [0.0; 10];
render.render(&mut second).unwrap();
verify_s16(&first, &[0, 0, 2000, 2000]);
verify_s16(
&second,
&[
4000, 4000, 6000, 6000, 8000, 8000, 10000, 10000, 12000, 12000,
],
);
let mut silence = [1.0; 2];
render.render(&mut silence).unwrap();
assert_eq!(silence, [0.0; 2]);
assert_eq!(dsp.metrics().unwrap().underrun_stream_frames, 1);
}
#[test]
fn stereo_downsampling_keeps_channels_independent() {
let dsp = Session::new(Format::new(32_000, Stereo).unwrap(), Limits::default()).unwrap();
let stream = dsp
.open_stream(Format::new(48_000, Stereo).unwrap())
.unwrap();
dsp.submit_pcm(
stream,
S16Le,
&s16(&[
0, 12000, 2000, 8000, 4000, 4000, 6000, 0, 8000, -4000, 10000, -8000, 12000, -12000,
]),
)
.unwrap();
let mut result = [0.0; 10];
dsp.renderer().unwrap().render(&mut result).unwrap();
verify_s16(
&result,
&[0, 12000, 3000, 6000, 6000, 0, 9000, -6000, 12000, -12000],
);
}
#[test]
fn block_partition_does_not_change_the_offline_output() {
let input = s16(&(0..1024).collect::<Vec<_>>());
let capture = |blocks: &[usize]| {
let dsp = Session::new(Format::new(48_000, Mono).unwrap(), Limits::default()).unwrap();
let stream = dsp.open_stream(Format::new(44_100, Mono).unwrap()).unwrap();
dsp.submit_pcm(stream, S16Le, &input).unwrap();
let mut render = dsp.renderer().unwrap();
let mut output = vec![0.0; blocks.iter().sum()];
let mut at = 0;
for &size in blocks {
render.render(&mut output[at..at + size]).unwrap();
at += size;
}
output
};
let output = capture(&[1000]);
assert_eq!(output, capture(&[37, 128, 3, 789, 43]));
for k in 0..=6 {
assert_eq!(output[k * 160], pcm_value((k * 147) as i16));
}
}
#[test]
fn simultaneous_streams_start_on_the_same_clock() {
let format = Format::new(48_000, Mono).unwrap();
let dsp = Session::new(format, Limits::default()).unwrap();
for (start, samples) in [(1, &[1000, 2000][..]), (2, &[4000, 8000]), (6, &[16000])] {
let stream = dsp.open_stream(format).unwrap();
dsp.control(stream, Control::StartAt(start)).unwrap();
dsp.submit_pcm(stream, S16Le, &s16(samples)).unwrap();
}
let mut output = [0.0; 8];
dsp.renderer().unwrap().render(&mut output).unwrap();
verify_s16(&output, &[0, 1000, 6000, 8000, 0, 0, 16000, 0]);
}
#[test]
fn ordered_controls_apply_before_the_block_and_pause_holds_samples() {
let format = Format::new(48_000, Stereo).unwrap();
let dsp = Session::new(format, Limits::default()).unwrap();
let stream = dsp.open_stream(format).unwrap();
assert_eq!(dsp.control(stream, Control::Mute(true)), Ok(0));
assert_eq!(dsp.control(stream, Control::Pause), Ok(1));
assert_eq!(
dsp.submit_pcm(stream, F32Le, &fp(&[0.75, -0.5, 0.5, 0.25])),
Ok(2)
);
let mut render = dsp.renderer().unwrap();
let mut out = [90.0; 2];
render.render(&mut out).unwrap();
assert_eq!(out, [0.0; 2]);
assert_eq!(dsp.metrics().unwrap().buffered_source_frames, 2);
dsp.control(stream, Control::Mute(false)).unwrap();
dsp.control(stream, Control::Gain([0.5, 0.25])).unwrap();
dsp.control(stream, Control::StartAt(1)).unwrap();
render.render(&mut out).unwrap();
assert_eq!(out, [0.375, -0.125]);
assert_eq!(dsp.metrics().unwrap().last_applied, Some(5));
}
#[test]
fn stale_foreign_and_wrong_stream_handles_are_rejected() {
let format = Format::new(48_000, Mono).unwrap();
let dsp = Session::new(format, Limits::default()).unwrap();
let other = Session::new(format, Limits::default()).unwrap();
let stream = dsp.open_stream(format).unwrap();
let peer = dsp.open_stream(format).unwrap();
let outside = other.open_stream(format).unwrap();
let buffer = dsp.allocate_pcm(stream, S16Le, &s16(&[1])).unwrap();
assert_eq!(
dsp.submit_buffer(peer, buffer),
Err(AudioError::WrongStream)
);
assert_eq!(
dsp.control(outside, Control::Pause),
Err(AudioError::InvalidHandle)
);
dsp.submit_buffer(stream, buffer).unwrap();
assert_eq!(dsp.retire_buffer(buffer), Err(AudioError::BufferInFlight));
dsp.renderer().unwrap().render(&mut [0.0]).unwrap();
assert_eq!(dsp.retire_buffer(buffer), Err(AudioError::InvalidHandle));
dsp.close_stream(stream).unwrap();
let replacement = dsp.open_stream(format).unwrap();
assert_ne!(stream, replacement);
assert_eq!(dsp.stream_format(stream), Err(AudioError::InvalidHandle));
}
#[test]
fn invalid_frames_and_overruns_leave_existing_audio_intact() {
let format = Format::new(48_000, Mono).unwrap();
let limits = Limits {
streams: 1,
frames_per_stream: 2,
commands: 1,
..Limits::default()
};
let dsp = Session::new(format, limits).unwrap();
let stream = dsp.open_stream(format).unwrap();
assert_eq!(dsp.open_stream(format), Err(AudioError::StreamLimit));
assert_eq!(
dsp.submit_pcm(stream, S16Le, &[1]),
Err(AudioError::InvalidLength)
);
assert_eq!(
dsp.submit_pcm(stream, F32Le, &fp(&[f32::NAN])),
Err(AudioError::InvalidSample)
);
dsp.submit_pcm(stream, S16Le, &s16(&[1000])).unwrap();
assert_eq!(
dsp.submit_pcm(stream, S16Le, &s16(&[2000])),
Err(AudioError::QueueFull)
);
assert_eq!(
dsp.submit_pcm(stream, S16Le, &s16(&[3000, 4000])),
Err(AudioError::BufferBudget)
);
let mut out = [0.0; 2];
dsp.renderer().unwrap().render(&mut out).unwrap();
verify_s16(&out, &[1000, 0]);
let metrics = dsp.metrics().unwrap();
assert_eq!(metrics.command_overruns, 1);
assert_eq!(metrics.buffer_overruns, 1);
assert_eq!(metrics.underrun_stream_frames, 1);
assert_eq!(metrics.live_buffers, 0);
}
#[test]
fn concurrent_producers_render_in_ticket_order() {
let format = Format::new(48_000, Mono).unwrap();
let dsp = Session::new(format, Limits::default()).unwrap();
let stream = dsp.open_stream(format).unwrap();
let mut receipts = thread::scope(|scope| {
(1..=16)
.map(|sample| {
let dsp = &dsp;
scope.spawn(move || {
(
dsp.submit_pcm(stream, S16Le, &s16(&[sample])).unwrap(),
sample,
)
})
})
.collect::<Vec<_>>()
.into_iter()
.map(|thread| thread.join().unwrap())
.collect::<Vec<_>>()
});
receipts.sort_unstable();
let expected = receipts
.into_iter()
.map(|(_, sample)| sample)
.collect::<Vec<_>>();
let mut output = [0.0; 16];
dsp.renderer().unwrap().render(&mut output).unwrap();
verify_s16(&output, &expected);
}
#[test]
fn lifecycle_releases_reservations_in_one_hundred_cycles() {
let format = Format::new(48_000, Mono).unwrap();
for _ in 0..100 {
let dsp = Session::new(format, Limits::default()).unwrap();
let stream = dsp.open_stream(format).unwrap();
let staged = dsp.allocate_pcm(stream, S16Le, &s16(&[1, 2])).unwrap();
dsp.submit_pcm(stream, S16Le, &s16(&[3])).unwrap();
let mut render = dsp.renderer().unwrap();
assert!(matches!(dsp.renderer(), Err(AudioError::RendererBusy)));
dsp.close_stream(stream).unwrap();
assert_eq!(dsp.retire_buffer(staged), Err(AudioError::InvalidHandle));
assert_eq!(dsp.metrics().unwrap().commands_cancelled, 1);
dsp.close().unwrap();
dsp.close().unwrap();
assert_eq!(render.render(&mut [0.0]), Err(AudioError::Closed));
let metrics = dsp.metrics().unwrap();
assert_eq!(
(
metrics.live_streams,
metrics.live_buffers,
metrics.pending_commands,
metrics.reserved_sample_bytes,
metrics.buffered_source_frames
),
(0, 0, 0, 0, 0)
);
}
}
#[test]
fn fractional_resampling_refuses_a_one_frame_capacity() {
let output = Format::new(48_000, Mono).unwrap();
let limits = Limits {
frames_per_stream: 1,
..Limits::default()
};
let dsp = Session::new(output, limits).unwrap();
assert_eq!(
dsp.open_stream(Format::new(32_000, Mono).unwrap()),
Err(AudioError::InvalidLimits)
);
assert_eq!(
dsp.open_stream(Format::new(72_000, Mono).unwrap()),
Err(AudioError::InvalidLimits)
);
let matching = dsp.open_stream(output).unwrap();
dsp.submit_pcm(matching, S16Le, &s16(&[1000])).unwrap();
let mut result = [0.0];
dsp.renderer().unwrap().render(&mut result).unwrap();
verify_s16(&result, &[1000]);
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[test]
fn coreaudio_rejects_a_short_block_before_touching_the_dsp() {
use xenora_audio_dsp::coreaudio::{Playback, PlaybackError};
let output = Format::new(192_000, Stereo).unwrap();
let dsp = Session::new(output, Limits::default()).unwrap();
let stream = dsp.open_stream(output).unwrap();
dsp.submit_pcm(stream, S16Le, &s16(&[1000, 2000])).unwrap();
assert!(matches!(
Playback::start(&dsp, 64),
Err(PlaybackError::InvalidBlockSize)
));
assert_eq!(dsp.metrics().unwrap().output_frames, 0);
let mut samples = [0.0; 2];
dsp.renderer().unwrap().render(&mut samples).unwrap();
verify_s16(&samples, &[1000, 2000]);
}
-116
View File
@@ -1,116 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#![cfg(feature = "xenora")]
use xenora_audio_dsp::{Channels, Format, Limits, Session, xenora::*};
use xenora_ffi::{AudioSubsystem, XENORA_AUDIO_FORMAT_PCM_S16LE};
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::imports::{ImportRegistry, Win64Args};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
#[test]
fn guest_registry_checks_ranges_handles_and_frame_atomicity() {
let format = Format::new(48_000, Channels::Stereo).unwrap();
let dsp = Session::new(format, Limits::default()).unwrap();
let stream = dsp.open_stream(format).unwrap();
let mut registry = ImportRegistry::new();
register_fixture_services(&mut registry, &dsp).unwrap();
assert!(register_fixture_services(&mut registry, &dsp).is_err());
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
0x1000,
4096,
MemoryPermissions::READ_WRITE,
&[0, 0x80, 0xff, 0x7f],
)
.unwrap();
let mut cpu = CpuState::default();
cpu.set(Register::Rcx, stream.raw());
cpu.set(Register::Rdx, 0x1000);
cpu.set(Register::R8, 3);
cpu.set(Register::R9, 1);
let submit = registry.binding(MODULE, SUBMIT_PCM).unwrap();
assert_eq!(
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
Ok(INVALID_DATA)
);
cpu.set(Register::R8, 4);
cpu.set(Register::Rdx, 0x1ffe);
assert!(matches!(
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
Err(ExitReason::MemoryFault(_))
));
assert_eq!(dsp.metrics().unwrap().pending_commands, 0);
cpu.set(Register::Rdx, 0x1000);
assert_eq!(
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
Ok(OK)
);
let mut pcm = [0.0; 2];
dsp.renderer().unwrap().render(&mut pcm).unwrap();
assert_eq!(pcm, [-1.0, 32767.0 / 32768.0]);
dsp.close_stream(stream).unwrap();
assert_eq!(
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
Ok(INVALID_HANDLE)
);
}
#[test]
fn gate6_transfer_reuses_processed_pcm_and_preserves_failed_submission() {
let format = Format::new(48_000, Channels::Mono).unwrap();
let dsp = Session::new(
format,
Limits {
commands: 1,
..Limits::default()
},
)
.unwrap();
let stream = dsp.open_stream(format).unwrap();
let mut gate = AudioSubsystem {
channels: 1,
volume: 0.5,
format: XENORA_AUDIO_FORMAT_PCM_S16LE,
..AudioSubsystem::default()
};
gate.submit(&[0, 0x40, 0, 0xc0]);
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 1), Ok(1));
assert!(transfer_gate6(&mut gate, &dsp, stream, 1).is_err());
assert_eq!(gate.queue.len(), 2);
let mut render = dsp.renderer().unwrap();
let mut output = [0.0];
render.render(&mut output).unwrap();
assert_eq!(output, [0.25]);
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 1), Ok(1));
render.render(&mut output).unwrap();
assert_eq!(output, [-0.25]);
assert!(gate.queue.is_empty());
}
#[test]
fn gate6_transfer_makes_progress_with_a_held_interpolation_frame() {
let output = Format::new(48_000, Channels::Mono).unwrap();
let limits = Limits {
frames_per_stream: 2,
..Limits::default()
};
let dsp = Session::new(output, limits).unwrap();
let stream = dsp
.open_stream(Format::new(32_000, Channels::Mono).unwrap())
.unwrap();
let mut gate = AudioSubsystem {
channels: 1,
sample_rate: 32_000,
..AudioSubsystem::default()
};
gate.submit(&[0, 0, 0, 0x30, 0, 0x60]);
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 1), Ok(1));
let mut render = dsp.renderer().unwrap();
let mut output = [1.0];
render.render(&mut output).unwrap();
assert_eq!(output, [0.0]);
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 2), Ok(1));
render.render(&mut output).unwrap();
assert_eq!(output, [0.25]);
}
+59
View File
@@ -0,0 +1,59 @@
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000000
0010: t2 = const.u32 0x00000001
0014: t3 = const.u32 0x40000001
001c: t4 = const.u32 0x00000001
0020: t5 = wave.mask v_cmp_f_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
002c: t6 = lshl.b32 t1, t2
0030: t7 = xor.b32 t6, t5
0034: t8 = wave.mask v_cmp_lt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0040: t9 = lshl.b32 t7, t2
0044: t10 = xor.b32 t9, t8
0048: t11 = wave.mask v_cmp_eq_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0054: t12 = lshl.b32 t10, t2
0058: t13 = xor.b32 t12, t11
005c: t14 = wave.mask v_cmp_le_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0068: t15 = lshl.b32 t13, t2
006c: t16 = xor.b32 t15, t14
0070: t17 = wave.mask v_cmp_gt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
007c: t18 = lshl.b32 t16, t2
0080: t19 = xor.b32 t18, t17
0084: t20 = wave.mask v_cmp_ne_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0090: t21 = lshl.b32 t19, t2
0094: t22 = xor.b32 t21, t20
0098: t23 = wave.mask v_cmp_ge_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00a4: t24 = lshl.b32 t22, t2
00a8: t25 = xor.b32 t24, t23
00ac: t26 = wave.mask v_cmp_t_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00b8: t27 = lshl.b32 t25, t2
00bc: t28 = xor.b32 t27, t26
00c0: t29 = wave.mask v_cmp_f_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00cc: t30 = lshl.b32 t28, t2
00d0: t31 = xor.b32 t30, t29
00d4: t32 = wave.mask v_cmp_lt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00e0: t33 = lshl.b32 t31, t2
00e4: t34 = xor.b32 t33, t32
00e8: t35 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
00f4: t36 = lshl.b32 t34, t2
00f8: t37 = xor.b32 t36, t35
00fc: t38 = wave.mask v_cmp_le_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0108: t39 = lshl.b32 t37, t2
010c: t40 = xor.b32 t39, t38
0110: t41 = wave.mask v_cmp_gt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
011c: t42 = lshl.b32 t40, t2
0120: t43 = xor.b32 t42, t41
0124: t44 = wave.mask v_cmp_ne_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0130: t45 = lshl.b32 t43, t2
0134: t46 = xor.b32 t45, t44
0138: t47 = wave.mask v_cmp_ge_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0144: t48 = lshl.b32 t46, t2
0148: t49 = xor.b32 t48, t47
014c: t50 = wave.mask v_cmp_t_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
0158: t51 = lshl.b32 t49, t2
015c: t52 = xor.b32 t51, t50
0160: t53 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> s8 exec=0xffffffff
0168: t54 = wave.mask v_cmp_gt_u32_e64 t3, t0 -> vcc_lo exec=0xffffffff
0170: branch.vccz t54 -> 0x0178
0174: t56 = xor.b32 t4, t52
0178: t57 = join.vccz t54, t56, t52
0178: store.u32 output[index], t57
+188
View File
@@ -0,0 +1,188 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]],
uint grid [[threads_per_grid]]) {
uint t0 = input[index];
uint t1 = 0x00000000u;
uint t2 = 0x00000001u;
uint t3 = 0x40000001u;
uint t4 = 0x00000001u;
uint t5 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (false) ? 1u : 0u;
t5 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t6 = t1 << (t2 & 31u);
uint t7 = t6 ^ t5;
uint t8 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) < as_type<int>(t3)) ? 1u : 0u;
t8 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t9 = t7 << (t2 & 31u);
uint t10 = t9 ^ t8;
uint t11 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) == as_type<int>(t3)) ? 1u : 0u;
t11 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t12 = t10 << (t2 & 31u);
uint t13 = t12 ^ t11;
uint t14 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) <= as_type<int>(t3)) ? 1u : 0u;
t14 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t15 = t13 << (t2 & 31u);
uint t16 = t15 ^ t14;
uint t17 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) > as_type<int>(t3)) ? 1u : 0u;
t17 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t18 = t16 << (t2 & 31u);
uint t19 = t18 ^ t17;
uint t20 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) != as_type<int>(t3)) ? 1u : 0u;
t20 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t21 = t19 << (t2 & 31u);
uint t22 = t21 ^ t20;
uint t23 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (as_type<int>(l0) >= as_type<int>(t3)) ? 1u : 0u;
t23 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t24 = t22 << (t2 & 31u);
uint t25 = t24 ^ t23;
uint t26 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (true) ? 1u : 0u;
t26 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t27 = t25 << (t2 & 31u);
uint t28 = t27 ^ t26;
uint t29 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (false) ? 1u : 0u;
t29 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t30 = t28 << (t2 & 31u);
uint t31 = t30 ^ t29;
uint t32 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 < t3) ? 1u : 0u;
t32 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t33 = t31 << (t2 & 31u);
uint t34 = t33 ^ t32;
uint t35 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 == t3) ? 1u : 0u;
t35 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t36 = t34 << (t2 & 31u);
uint t37 = t36 ^ t35;
uint t38 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 <= t3) ? 1u : 0u;
t38 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t39 = t37 << (t2 & 31u);
uint t40 = t39 ^ t38;
uint t41 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 > t3) ? 1u : 0u;
t41 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t42 = t40 << (t2 & 31u);
uint t43 = t42 ^ t41;
uint t44 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 != t3) ? 1u : 0u;
t44 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t45 = t43 << (t2 & 31u);
uint t46 = t45 ^ t44;
uint t47 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 >= t3) ? 1u : 0u;
t47 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t48 = t46 << (t2 & 31u);
uint t49 = t48 ^ t47;
uint t50 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint pass = (true) ? 1u : 0u;
t50 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t51 = t49 << (t2 & 31u);
uint t52 = t51 ^ t50;
uint t53 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (l0 == t3) ? 1u : 0u;
t53 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t54 = 0u;
for (uint lane = 0u; lane < 32u; ++lane) {
uint lane_index = (index & ~31u) + lane;
if (lane_index >= grid) { break; }
uint l0 = input[lane_index];
uint pass = (t3 > l0) ? 1u : 0u;
t54 |= ((0xffffffffu >> lane) & pass) << lane;
}
uint t56 = t4 ^ t52;
uint t57 = t54 != 0u ? t56 : t52;
output[index] = t57;
}
+23
View File
@@ -0,0 +1,23 @@
0000: t0 = load.u32 input[index]
000c: t1 = mul24.i32 t0, t0
0014: t2 = mulhi24.i32 t1, t0
001c: t3 = mul24.u32 t1, t0
0024: t4 = mulhi24.u32 t3, t0
002c: t5 = min.i32 t0, t1
0034: t6 = max.i32 t0, t3
003c: t7 = min.u32 t2, t0
0044: t8 = max.u32 t4, t1
004c: t9 = xnor.b32 t0, t4
0054: t10 = sub.u32 t5, t9
005c: t11 = sub.u32 t8, t0
0064: t12 = xor.b32 t1, t2
0068: t13 = xor.b32 t3, t12
006c: t14 = xor.b32 t4, t13
0070: t15 = xor.b32 t5, t14
0074: t16 = xor.b32 t6, t15
0078: t17 = xor.b32 t7, t16
007c: t18 = xor.b32 t8, t17
0080: t19 = xor.b32 t9, t18
0084: t20 = xor.b32 t10, t19
0088: t21 = xor.b32 t11, t20
008c: store.u32 output[index], t21
+30
View File
@@ -0,0 +1,30 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = as_type<uint>((as_type<int>(t0 << 8u) >> 8)) * as_type<uint>((as_type<int>(t0 << 8u) >> 8));
uint t2 = as_type<uint>(mulhi((as_type<int>(t1 << 8u) >> 8), (as_type<int>(t0 << 8u) >> 8)));
uint t3 = (t1 & 0x00ffffffu) * (t0 & 0x00ffffffu);
uint t4 = mulhi((t3 & 0x00ffffffu), (t0 & 0x00ffffffu));
uint t5 = as_type<uint>(min(as_type<int>(t0), as_type<int>(t1)));
uint t6 = as_type<uint>(max(as_type<int>(t0), as_type<int>(t3)));
uint t7 = min(t2, t0);
uint t8 = max(t4, t1);
uint t9 = ~(t0 ^ t4);
uint t10 = t5 - t9;
uint t11 = t8 - t0;
uint t12 = t1 ^ t2;
uint t13 = t3 ^ t12;
uint t14 = t4 ^ t13;
uint t15 = t5 ^ t14;
uint t16 = t6 ^ t15;
uint t17 = t7 ^ t16;
uint t18 = t8 ^ t17;
uint t19 = t9 ^ t18;
uint t20 = t10 ^ t19;
uint t21 = t11 ^ t20;
output[index] = t21;
}
Binary file not shown.
+85
View File
@@ -0,0 +1,85 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original Wave32 VOP3A vectors for the sixteen integer compare encoding variants.
// Each compare writes vcc_lo through the explicit 64-bit destination field
// (one writes s8), and each wave folds the masks into v2 as
// v2 = (v2 << 1) ^ mask. Sources are VGPRs. This fixture is checked through
// its IR and MSL goldens; the per-lane expected values for these forms are in
// tests/validation/tests/vop3_compare.rs.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word.
s_waitcnt vmcnt(0) // Wait for the load.
v_mov_b32_e32 v2, 0 // Clear the accumulator.
v_mov_b32_e32 v5, 1 // Shift count for the fold.
v_mov_b32_e32 v3, 0x40000001 // Second source: inputs fall below, on and above it.
v_mov_b32_e32 v6, 1 // Low bit for the branch fold.
v_cmp_f_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_lt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_eq_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_le_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_gt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ne_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ge_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_t_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_f_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_lt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_eq_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_le_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_gt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ne_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_ge_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_t_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
v_cmp_eq_u32_e64 s8, v1, v3 // A mask into a plain SGPR, never read.
v_cmp_gt_u32_e64 vcc_lo, v3, v1 // Unsigned 0x40000001 > input.
s_cbranch_vccz 1 // Skip the next fold when no lane passed.
v_xor_b32_e32 v2, v6, v2 // Flip the low bit when some lane passed.
buffer_store_dword v2, v0, s[4:7], 0 idxen // Store the folded word.
s_waitcnt_vscnt null, 0 // Wait for the store.
s_endpgm // End the program.
Binary file not shown.
+31
View File
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original VOP3A vectors for the eleven per-lane integer encoding variants.
// All arithmetic operands are vector general-purpose registers (VGPRs) and every result
// depends on the lane's own input word. XOR folds the results into one word.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word.
s_waitcnt vmcnt(0) // Wait for the load.
v_mul_i32_i24_e64 v2, v1, v1 // Multiply signed 24-bit inputs and keep the low word.
v_mul_hi_i32_i24_e64 v3, v2, v1 // Multiply signed 24-bit inputs and keep the high word.
v_mul_u32_u24_e64 v4, v2, v1 // Multiply unsigned 24-bit inputs and keep the low word.
v_mul_hi_u32_u24_e64 v255, v4, v1 // Multiply unsigned 24-bit inputs and keep the high word.
v_min_i32_e64 v6, v1, v2 // Select the signed minimum.
v_max_i32_e64 v7, v1, v4 // Select the signed maximum.
v_min_u32_e64 v8, v3, v1 // Select the unsigned minimum.
v_max_u32_e64 v9, v255, v2 // Select the unsigned maximum.
v_xnor_b32_e64 v10, v1, v255 // Complement the XOR.
v_sub_nc_u32_e64 v11, v6, v10 // Subtract the second source from the first.
v_subrev_nc_u32_e64 v1, v1, v9 // Subtract the first source from the second, overwriting the first.
v_xor_b32_e32 v13, v2, v3 // Start the XOR fold.
v_xor_b32_e32 v13, v4, v13 // Fold the unsigned product low word.
v_xor_b32_e32 v13, v255, v13 // Fold the unsigned product high word.
v_xor_b32_e32 v13, v6, v13 // Fold the signed minimum.
v_xor_b32_e32 v13, v7, v13 // Fold the signed maximum.
v_xor_b32_e32 v13, v8, v13 // Fold the unsigned minimum.
v_xor_b32_e32 v13, v9, v13 // Fold the unsigned maximum.
v_xor_b32_e32 v13, v10, v13 // Fold the XNOR result.
v_xor_b32_e32 v13, v11, v13 // Fold the subtraction result.
v_xor_b32_e32 v13, v1, v13 // Fold the reverse subtraction result.
buffer_store_dword v13, v0, s[4:7], 0 idxen // Store the folded word.
s_waitcnt_vscnt null, 0 // Wait for the store.
s_endpgm // End the program.
+1 -1
View File
@@ -12,7 +12,7 @@ case "${1:-}" in
esac
for name in add bitwise-branch float-exact or shifts ashr \
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-vcc vector-unary vector-compare-64 vector-compare-16; do
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-vcc vop3-integer vop3-compare vector-unary vector-compare-64 vector-compare-16; do
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
+3 -3
View File
@@ -10,7 +10,7 @@ import sys
import tomllib
registry = Path("docs/claims.toml")
claims = tomllib.loads(registry.read_text())["claim"]
claims = tomllib.loads(registry.read_text(encoding="utf-8"))["claim"]
classes = {}
errors = []
claim_id = re.compile(r"\bCLAIM-[A-Z0-9]+(?:-[A-Z0-9]+)*\b")
@@ -37,10 +37,10 @@ files = [Path("README.md"), Path("AGENTS.md"), *Path("docs").rglob("*"),
for source in files:
if source == registry or source.suffix not in {".md", ".toml", ".rs"}:
continue
for reference in set(claim_id.findall(source.read_text())) - classes.keys():
for reference in set(claim_id.findall(source.read_text(encoding="utf-8"))) - classes.keys():
errors.append(f"{source}: unregistered {reference}")
status = tomllib.loads(Path("docs/status.toml").read_text())
status = tomllib.loads(Path("docs/status.toml").read_text(encoding="utf-8"))
for feature in status["feature"]:
verification = feature.get("hardware_verification", "")
if verification.casefold() != "verified":
+6 -3
View File
@@ -17,10 +17,13 @@ python3 - <<'PY'
import json
from pathlib import Path
import subprocess
import sys
sys.stdout.reconfigure(encoding="utf-8")
executables = set()
for filename in ("native-build.jsonl", "native-tests.jsonl"):
for line in (Path("artifacts") / filename).read_text().splitlines():
for line in (Path("artifacts") / filename).read_text(encoding="utf-8").splitlines():
entry = json.loads(line)
if entry.get("executable"):
executables.add(entry["executable"])
@@ -32,11 +35,11 @@ if not executables:
raise SystemExit("No Cargo executable or loadable dependency artifacts found.")
for path in sorted(executables):
subprocess.run(["file", path], check=True)
archs = subprocess.check_output(["lipo", "-archs", path], text=True).strip()
archs = subprocess.check_output(["lipo", "-archs", path], encoding="utf-8").strip()
print(archs, flush=True)
if archs != "arm64":
raise SystemExit(f"Non-ARM64 build artifact: {path}")
linkage = subprocess.check_output(["otool", "-L", path], text=True)
linkage = subprocess.check_output(["otool", "-L", path], encoding="utf-8")
print(linkage, end="", flush=True)
if any(name in linkage.casefold() for name in ("vulkan", "moltenvk")):
raise SystemExit(f"Unexpected graphics linkage: {path}")
+6 -6
View File
@@ -18,7 +18,7 @@ def table(headers, rows):
def replace_block(path, name, body, check):
original = path.read_text()
original = path.read_text(encoding="utf-8")
start = f"<!-- status:{name}:start -->\n"
stop = f"\n<!-- status:{name}:end -->"
head, _, tail = original.partition(start)
@@ -30,7 +30,7 @@ def replace_block(path, name, body, check):
if check:
print(f"{path}: status table differs from docs/status.toml", file=sys.stderr)
return False
path.write_text(updated)
path.write_text(updated, encoding="utf-8", newline="\n")
return True
@@ -90,12 +90,12 @@ def render_progress(status):
def check_asset(path, svg, check):
if path.exists() and path.read_text() == svg:
if path.exists() and path.read_text(encoding="utf-8") == svg:
return True
if check:
print(f"{path}: progress graphic differs from docs/status.toml", file=sys.stderr)
return False
path.write_text(svg)
path.write_text(svg, encoding="utf-8", newline="\n")
return True
@@ -105,8 +105,8 @@ def main():
check = parser.parse_args().check
root = Path(__file__).resolve().parents[2]
docs = root / "docs"
status = tomllib.loads((docs / "status.toml").read_text())
claims = tomllib.loads((docs / "claims.toml").read_text())
status = tomllib.loads((docs / "status.toml").read_text(encoding="utf-8"))
claims = tomllib.loads((docs / "claims.toml").read_text(encoding="utf-8"))
classes = {claim["id"]: claim["class"] for claim in claims["claim"]}
features = table(
+10 -1
View File
@@ -8,6 +8,10 @@ export MTL_SHADER_VALIDATION=1
export MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1
export MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
# The full semantic-review batch is much larger than the individual GPU tests.
# Cold Apple Silicon runs can exceed two minutes; keep the default bounded but
# allow slower hosts to raise it without editing the script.
export XENORA_SEMANTIC_TIMEOUT=${XENORA_SEMANTIC_TIMEOUT:-300s}
cargo test --locked -p xenora-metal --features gpu-tests --test native_compute --no-run
timeout 30s cargo test --locked -p xenora-metal --features gpu-tests --test native_compute -- \
@@ -25,6 +29,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
--nocapture --test-threads=1
# Guest draws sample textures bound through descriptor tables (#303).
cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures --no-run
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_textures -- \
--nocapture --test-threads=1
# The native app interface runs the trusted fixture's guest draw on Metal.
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
@@ -53,4 +62,4 @@ timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
timeout "$XENORA_SEMANTIC_TIMEOUT" cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
+112
View File
@@ -0,0 +1,112 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Exercise native audit JSON decoding and inspection under an ASCII locale."""
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = (ROOT / "scripts/audit/native.sh").read_text(encoding="utf-8")
AUDIT = SCRIPT.split("python3 - <<'PY'\n", 1)[1].rsplit("\nPY", 1)[0]
# Reader-only cases stop before the native executable inspection.
READER = AUDIT.split("\nif not executables:", 1)[0]
class NativeJsonTests(unittest.TestCase):
def run_audit(self, streams, code=READER):
with tempfile.TemporaryDirectory() as directory:
artifacts = Path(directory) / "artifacts"
artifacts.mkdir()
for name, payload in zip(
("native-build.jsonl", "native-tests.jsonl"), streams, strict=True
):
(artifacts / name).write_bytes(payload)
return subprocess.run(
[
sys.executable,
"-c",
"import locale\n"
"assert locale.getencoding().lower() in ('ascii', 'us-ascii')\n"
+ code
+ "\nprint(json.dumps(sorted(executables)))\n",
],
cwd=directory,
env={
**os.environ,
"LC_ALL": "C",
"PYTHONCOERCECLOCALE": "0",
"PYTHONUTF8": "0",
},
capture_output=True,
encoding="utf-8",
check=False,
)
def test_utf8_in_each_cargo_stream(self):
for stream in (0, 1):
with self.subTest(stream=stream):
entry = {
"executable": "/synthetic/caf\u00e9/bin",
"filenames": ["/synthetic/caf\u00e9/lib.dylib"],
"message": {"rendered": "synthetic diagnostic: \u03bb"},
}
streams = [b'{}\n', b'{}\n']
streams[stream] = (json.dumps(entry, ensure_ascii=False) + "\n").encode(
"utf-8"
)
result = self.run_audit(streams)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout),
["/synthetic/caf\u00e9/bin", "/synthetic/caf\u00e9/lib.dylib"],
)
def test_ascii_streams_keep_deduplicated_artifacts(self):
entry = b'{"executable":"/synthetic/bin","filenames":["/synthetic/lib.so","/synthetic/lib.rlib"]}\n'
result = self.run_audit([entry, entry])
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout), ["/synthetic/bin", "/synthetic/lib.so"]
)
def test_invalid_utf8_is_rejected(self):
result = self.run_audit([b'{"executable":"\xff"}\n', b'{}\n'])
self.assertNotEqual(result.returncode, 0)
self.assertIn("UnicodeDecodeError", result.stderr)
@unittest.skipUnless(
sys.platform == "darwin" and platform.machine() == "arm64",
"requires native ARM64 macOS inspection tools",
)
def test_native_inspection_of_unicode_path_under_ascii_locale(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "fixture.c"
source.write_text("int main(void) { return 0; }\n", encoding="utf-8")
binary = root / "caf\u00e9"
subprocess.run(
["/usr/bin/clang", "-arch", "arm64", str(source), "-o", str(binary)],
check=True,
capture_output=True,
)
entry = (
json.dumps({"executable": str(binary)}, ensure_ascii=False) + "\n"
).encode("utf-8")
for stream in (0, 1):
with self.subTest(stream=stream):
streams = [b'{}\n', b'{}\n']
streams[stream] = entry
result = self.run_audit(streams, code=AUDIT)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn(str(binary), result.stdout)
self.assertIn("Checked 1 native executables", result.stdout)
if __name__ == "__main__":
unittest.main()
@@ -177,7 +177,7 @@ def snapshot():
["SRC2", [[50, 9]]], ["OMOD", [[59, 2]]], ["NEG", [[61, 3]]],
],
"identifier_mask": 0xFFFF0000,
"identifiers": [0xD4000000 | (op << 16) for op in (265, 273, 295)],
"identifiers": [0xD4000000 | (op << 16) for op in (129, 265, 273, 295)],
}
# Values copied from the AMD XML snapshot: VOP3 encodings of VOP2 forms.
for name, opcode, data_format in (
@@ -191,6 +191,14 @@ def snapshot():
["SRC1", data_format, "OPR_SRC_NOLDS", 32, True, False, False, True],
],
}
variants[("V_CMP_LT_I32", "ENC_VOP3")] = {
"instruction": "V_CMP_LT_I32", "encoding": "ENC_VOP3", "opcode": 129,
"operands": [
["VDST", "FMT_NUM_M64", "OPR_SREG", 64, False, True, False, True],
["SRC0", I32, "OPR_SRC", 32, True, False, False, True],
["SRC1", I32, "OPR_SRC_NOLDS", 32, True, False, False, True],
],
}
return {
"source": {"sha256": SHA},
"encodings": {
@@ -309,6 +317,18 @@ def _variant(of, opcode):
}
def compare_variants():
reg = vector_compares()
rule = gen.OPERAND_RULES["vop3_cmp_vgpr2"]
reg["operand_rules"]["vop3_cmp_vgpr2"] = dict(
copy.deepcopy(rule["shape"]), unsupported=sorted(rule["unsupported"])
)
reg["encoding_variant"] = [
dict(_variant("V_CMP_LT_I32", 129), operands="vop3_cmp_vgpr2")
]
return reg
def compares():
reg = registry()
reg["form"] += [
@@ -860,6 +880,25 @@ class Validate(unittest.TestCase):
def test_accepts_encoding_variants(self):
self.assertEqual(self.errors(variants()), [])
def test_compare_variant_routes_mask_to_sdst(self):
reg = compare_variants()
self.assertEqual(self.errors(reg), [])
row = gen.variant_row(reg, reg["encoding_variant"][0])
self.assertEqual((row["vcc"], row["width"], row["wave"]), ("sdst_lane_mask", 32, "wave32"))
def test_rejects_mismatched_compare_variant_destination(self):
reg = compare_variants()
form(reg, "V_CMP_LT_I32")["vcc"] = "unchanged"
self.rejects(reg, "requires a base destination contract of lane_mask, got unchanged")
reg = compare_variants()
reg["operand_rules"]["vop3_cmp_vgpr2"]["dst"]["class"] = "vgpr"
self.rejects(reg, "operand rule vop3_cmp_vgpr2: declaration differs")
snap = snapshot()
snap["variants"][("V_CMP_LT_I32", "ENC_VOP3")]["operands"][0][2] = "OPR_VGPR"
self.rejects(compare_variants(), "VDST is not a scalar mask destination in the XML", snap)
def test_rejects_a_variant_of_an_undeclared_form(self):
reg = variants()
reg["encoding_variant"].append(_variant("V_MUL_HI_I32_I24", 266))
+50 -18
View File
@@ -22,7 +22,7 @@
//! MUL_I32_I24, MUL_HI_I32_I24, MUL_U32_U24, MUL_HI_U32_U24, MIN/MAX (I32,
//! U32), XNOR and ADD/SUB/SUBREV_NC_U32 (any SRC0 a VOPC compare takes; a
//! shift-and-add multiplier and floor division for the high half, the ripple
//! adder for add and subtract), VOP3 add-no-carry, MUBUF
//! adder for add and subtract), VOP3A integer arithmetic and compares, MUBUF
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
//! error. The arithmetic shift is evaluated as a floor division by a power of
//! two rather than with a host signed shift, so the oracle does not share the
@@ -72,18 +72,20 @@ enum Insn {
/// SOPK opcode 0 or 2-16 on SGPR `SDST` (s0-s105) with the raw SIMM16.
SImm(u32, u8, u16),
BranchScc0(usize),
BranchMaskZero {
BranchMask {
target: usize,
register: usize,
nonzero: bool,
},
Branch(usize),
VMov(u8, Src),
VMovFromSgpr(u8, u8),
/// `v_mov_b32_e32 vD, vcc_lo`.
VMovFromVcc(u8),
/// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
/// Integer vector compare into `dst`: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
/// `bits` is 16, 32 or 64; 64-bit register operands name the low register of a pair.
VCmp {
dst: u8,
relation: u8,
signed: bool,
bits: u32,
@@ -207,6 +209,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
return Ok(lanes.iter().map(|lane| lane.written.unwrap()).collect());
}
Insn::VCmp {
dst,
relation,
signed,
bits,
@@ -226,10 +229,12 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
offset,
)
.map(|mask| {
sgpr[106] = Some(mask);
// VCC_HI has no known value after a compare (contract 3).
sgpr[107] = None;
vcc_lane_derived = execution_mask != 0;
sgpr[usize::from(dst)] = Some(mask);
if dst == 106 {
// VCC_HI has no known value after a VCC compare (contract 3).
sgpr[107] = None;
vcc_lane_derived = execution_mask != 0;
}
None
})
}
@@ -301,12 +306,17 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
index_of(program, target, offset).map(Some)
}
}),
Insn::BranchMaskZero { target, register } => {
Insn::BranchMask {
target,
register,
nonzero,
} => {
let takes = |mask| (mask != 0) == nonzero;
if register == 106 && vcc_lane_derived {
let live = lanes.iter().find(|lane| lane.error.is_none()).unwrap();
check_runtime_region(program, pc, target, live, &sgpr, execution_mask, offset)
.and_then(|()| {
if sgpr[106] == Some(0) {
if takes(sgpr[106].unwrap()) {
index_of(program, target, offset).map(Some)
} else {
Ok(None)
@@ -316,7 +326,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
sgpr[register]
.ok_or_else(|| format!("{offset:#x}: uninitialized mask"))
.and_then(|mask| {
if mask == 0 {
if takes(mask) {
index_of(program, target, offset).map(Some)
} else {
Ok(None)
@@ -690,7 +700,7 @@ fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
lane.vgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized v{reg}"))
}
/// Evaluate one VOPC compare for the whole wave and return the new VCC_LO.
/// Evaluate one integer vector compare for the whole wave and return its mask.
fn compare(
lanes: &[Lane],
sgpr: &[Option<u32>; 128],
@@ -1214,7 +1224,7 @@ fn decode(code: &[u8]) -> Result<Vec<(usize, Insn)>, String> {
offset += len;
}
for &(at, insn) in &program {
if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMaskZero { target, .. } =
if let Insn::Branch(target) | Insn::BranchScc0(target) | Insn::BranchMask { target, .. } =
insn
&& !program.iter().any(|(boundary, _)| *boundary == target)
{
@@ -1315,6 +1325,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Err(fail("unsupported VOPC operand"));
}
let insn = Insn::VCmp {
dst: 106,
relation: relation as u8,
signed,
bits,
@@ -1337,14 +1348,34 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
let insn = Insn::VInt(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8);
return Ok((insn, len));
}
if first & 0xffff_0000 == 0xd525_0000 {
let second = word(code, offset + 4)?;
if first >> 26 == 0b110101 {
let dst = first as u8;
let opcode = (first >> 16) & 0x3ff;
let second = word(code, offset + 4).map_err(|_| fail("truncated VOP3A"))?;
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(fail("bad VOP3 add form"));
return Err(fail("unsupported VOP3A modifiers or sources"));
}
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
// Guide §§3.9, 12.7.1 and 12.9.1: re-encoded VOP2 writes a VGPR,
// while VOPC uses the destination field for the scalar mask.
let (src0, src1) = (src0 as u8, src1 as u8);
let insn = match opcode {
128..=135 | 192..=199 if dst <= 106 => Insn::VCmp {
dst,
relation: (opcode % 8) as u8,
signed: opcode < 192,
bits: 32,
src0: CmpSrc::Vgpr(src0),
src1,
},
293 => Insn::VAddNc(dst, src0, src1),
265..=268 | 273..=276 | 286 | 294..=295 => {
Insn::VInt(opcode - 256, dst, CmpSrc::Vgpr(src0), src1)
}
_ => return Err(fail("unsupported VOP3A opcode or destination")),
};
return Ok((insn, 8));
}
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15.
let sop1_op = (first >> 8) & 0xff;
@@ -1429,15 +1460,16 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Ok((Insn::BranchScc0(branch_target(first, offset)?), 4));
}
let tested_register = match first >> 16 {
0xbf86 => Some(106),
0xbf86 | 0xbf87 => Some(106),
0xbf88 => Some(126),
_ => None,
};
if let Some(register) = tested_register {
return Ok((
Insn::BranchMaskZero {
Insn::BranchMask {
target: branch_target(first, offset)?,
register,
nonzero: first >> 16 == 0xbf87,
},
4,
));
+302
View File
@@ -0,0 +1,302 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Wave32 VOP3A integer compares. Guide §3.9 permits an SGPR destination in
//! the 64-bit encoding and describes the fully rewritten per-lane mask.
//! A Wave32 mask has 32 bits (§2.1), so SDST consumes one 32-bit SGPR (§5.2).
//! The opcode relations are in §12.9, the re-encoding in §12.9.1, and the
//! VOP3A fields in §13.3.4. These are spec-derived expectations.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use harness::{Case, words};
const FORMS: [(u32, &str); 16] = [
(128, "v_cmp_f_i32"),
(129, "v_cmp_lt_i32"),
(130, "v_cmp_eq_i32"),
(131, "v_cmp_le_i32"),
(132, "v_cmp_gt_i32"),
(133, "v_cmp_ne_i32"),
(134, "v_cmp_ge_i32"),
(135, "v_cmp_t_i32"),
(192, "v_cmp_f_u32"),
(193, "v_cmp_lt_u32"),
(194, "v_cmp_eq_u32"),
(195, "v_cmp_le_u32"),
(196, "v_cmp_gt_u32"),
(197, "v_cmp_ne_u32"),
(198, "v_cmp_ge_u32"),
(199, "v_cmp_t_u32"),
];
const VALUES: [u32; 10] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
u32::MAX,
0x00ff_ffff,
0x0080_0000,
0xff80_0000,
0x0100_0001,
0xff00_0003,
];
const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0];
fn passes(op: u32, a: u32, b: u32) -> bool {
let operand = |value: u32| {
if op < 192 {
i64::from(value as i32)
} else {
i64::from(value)
}
};
let (a, b) = (operand(a), operand(b));
match op & 7 {
// D[threadId] = 0.
0 => false,
// D[threadId] = (S0 < S1).
1 => a < b,
// D[threadId] = (S0 == S1).
2 => a == b,
// D[threadId] = (S0 <= S1).
3 => a <= b,
// D[threadId] = (S0 > S1).
4 => a > b,
// D[threadId] = (S0 <> S1).
5 => a != b,
// D[threadId] = (S0 >= S1).
6 => a >= b,
// D[threadId] = 1.
_ => true,
}
}
fn expected_mask(op: u32, exec: u32, wave: &[u32], bound: u32, reverse: bool) -> u32 {
// §3.9: VCC[n] = EXEC[n] & (test passed for thread[n]).
// §3.9 uses the same result for the alternate scalar destination.
wave.iter().enumerate().fold(0, |mask, (n, &x)| {
let (a, b) = if reverse { (bound, x) } else { (x, bound) };
mask | (exec & (u32::from(passes(op, a, b)) << n))
})
}
fn vop3(op: u32, dst: u32, reverse: bool) -> [u32; 2] {
let (a, b) = if reverse { (511, 257) } else { (257, 511) };
[0xd400_0000 | op << 16 | dst, a | b << 9 | 128 << 18]
}
fn smov(dst: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | dst << 16, value]
}
fn setup(bound: u32, exec: u32) -> Vec<u32> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1
code.extend([0x7ffe_02ff, bound]); // v255 = literal
code.extend(smov(126, exec));
code
}
fn store(mut code: Vec<u32>) -> Vec<u8> {
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn mask_cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for bound in VALUES {
for reverse in [false, true] {
for exec in MASKS {
for (lanes, dst) in [(7, 106), (32, 106), (45, 106), (45, 0), (45, 105)] {
let mut code = setup(bound, exec);
// Give the old VCC bits on both sides of EXEC.
code.extend(smov(106, 0xa5a5_5a5a));
code.extend(vop3(op, dst, reverse));
code.extend([0xbefe_03c1, 0x7e04_0200 | dst]);
let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect();
let expected = input
.chunks(32)
.flat_map(|wave| {
let mask = expected_mask(op, exec, wave, bound, reverse);
std::iter::repeat_n(mask, wave.len())
})
.collect();
cases.push(Case {
form: name,
family: if dst == 106 { "vcc_lo" } else { "sgpr" },
label: format!("{name} s{dst}, bound={bound:#x}, reverse={reverse}, EXEC={exec:#x}, {lanes} lanes"),
code: store(code),
input,
expected,
});
}
}
}
}
}
cases
}
fn branch_cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for dst in [0, 105, 106] {
for exec in MASKS {
for old_vcc in [0, 0xa5a5_5a5a] {
for nonzero in [false, true] {
let scc = old_vcc != 0;
let mut code = setup(0, u32::MAX);
// Seed s1 to detect an accidental second SGPR write to s0:s1.
code.extend(vop3(199, 1, false));
code.extend(smov(106, old_vcc));
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend([0x7e04_0280, 0x7e08_0280, 0x7e0c_0284]); // v2 = v4 = 0, v6 = 4
code.extend(smov(126, exec));
code.extend(vop3(op, dst, false));
code.extend([
0x7e08_0281, // v4 = 1 only where EXEC was set
0xbefe_03c1,
// Independent bits for the VCC edge, SCC, and EXEC.
if nonzero { 0xbf87_0001 } else { 0xbf86_0001 },
0x7e04_0282, // v2 = 2 on fallthrough
0xbf84_0001,
0x3a04_0d02, // v2 ^= 4 if SCC = 1
0x3a04_0902, // v2 ^= v4
0x7e06_0201,
0x3a04_0702, // v2 ^= s1
0x7e06_026a,
0x3a04_0702, // v2 ^= VCC_LO
]);
// The two waves give opposite results for several relations.
let input: Vec<_> = std::iter::repeat_n(1, 32)
.chain(std::iter::repeat_n(u32::MAX, 13))
.collect();
let mut expected = Vec::new();
for wave in input.chunks(32) {
let mask = expected_mask(op, exec, wave, 0, false);
let vcc = if dst == 106 { mask } else { old_vcc };
// §12.5: if (VCC == 0) / if (VCC != 0), PC = PC + signext(SIMM16 * 4) + 4.
let taken = (vcc != 0) == nonzero;
let s1 = u32::MAX >> (32 - wave.len());
let marker = (u32::from(scc) << 2) | (u32::from(!taken) << 1);
expected.extend(
wave.iter()
.enumerate()
.map(|(n, _)| marker ^ ((exec >> n) & 1) ^ s1 ^ vcc),
);
}
cases.push(Case {
form: name,
family: "vcc branch and flags",
label: format!(
"{name} s{dst}, EXEC={exec:#x}, VCC={old_vcc:#x}, NZ={nonzero}"
),
code: store(code),
input,
expected,
});
}
}
}
}
}
cases
}
#[test]
fn vop3_compare_matches_the_guide() {
let masks = mask_cases();
let branches = branch_cases();
assert_eq!(masks.len(), 16 * 10 * 2 * 4 * 5);
assert_eq!(branches.len(), 16 * 3 * 4 * 2 * 2);
for case in masks.iter().chain(&branches) {
assert_eq!(
xenora_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"reference: {}",
case.label
);
assert_eq!(
independent_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"independent: {}",
case.label
);
}
eprintln!(
"vop3_compare: {} mask and {} branch/flag cases per CPU interpreter",
masks.len(),
branches.len()
);
}
#[test]
fn vop3_compare_rejects_excluded_operands_and_modifiers() {
let mut count = 0;
for (op, name) in FORMS {
let setup = setup(7, u32::MAX);
let offset = setup.len() * 4;
let [head, tail] = vop3(op, 106, false);
let mut check = |alu: &[u32]| {
let mut code = setup.clone();
code.extend(alu);
let code = if alu.len() == 1 {
words(&code)
} else {
// A successful decode would read its mask here and complete.
code.push(0x7e04_026a);
store(code)
};
let input = [1, 2];
let err = xenora_ref::execute(&code, &input).expect_err(name);
assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}");
let err = independent_ref::execute(&code, &input).expect_err(name);
assert!(
err.starts_with(&format!("{offset:#x}:")),
"{name}: {alu:08x?} {err}"
);
count += 1;
};
// ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1.
for bit in 8..16 {
check(&[head | 1 << bit, tail]);
}
for bit in 27..32 {
check(&[head, tail | 1 << bit]);
}
for selector in 0..256 {
check(&[head, (tail & !511) | selector]);
check(&[head, (tail & !(511 << 9)) | selector << 9]);
}
for selector in (0..512).filter(|&s| s != 128) {
check(&[head, (tail & !(511 << 18)) | selector << 18]);
}
for dst in 107..=255 {
check(&[(head & !255) | dst, tail]);
}
check(&[head]);
}
assert_eq!(count, 16 * (13 + 512 + 511 + 149 + 1));
eprintln!("vop3_compare: {count} rejections per CPU interpreter");
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop3_vcc_compare_matches_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
let cases: Vec<_> = mask_cases()
.into_iter()
.filter(|case| case.family == "vcc_lo")
.collect();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"vop3_compare: {} Metal cases in {programs} programs",
cases.len()
);
}
+246
View File
@@ -0,0 +1,246 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Wave32 VOP3A integer ALU forms. AMD RDNA 2 ISA guide §§12.7, 12.7.1,
//! 12.12 and 13.3.4. The expectations use the guide's arithmetic per lane.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use harness::{Case, words};
const FORMS: [(u32, &str); 11] = [
(265, "v_mul_i32_i24"),
(266, "v_mul_hi_i32_i24"),
(267, "v_mul_u32_u24"),
(268, "v_mul_hi_u32_u24"),
(273, "v_min_i32"),
(274, "v_max_i32"),
(275, "v_min_u32"),
(276, "v_max_u32"),
(286, "v_xnor_b32"),
(294, "v_sub_nc_u32"),
(295, "v_subrev_nc_u32"),
];
const VALUES: [u32; 12] = [
0,
1,
2,
0x007f_ffff,
0x0080_0000,
0x0080_0001,
0x00ff_ffff,
0xff80_0000,
0xff00_0003,
0x7fff_ffff,
0x8000_0000,
u32::MAX,
];
const MASKS: [u32; 4] = [u32::MAX, 0x5555_5555, 0x8000_0001, 0];
fn expected(op: u32, a: u32, b: u32) -> u32 {
// S.i24 is bits 23:0 sign-extended from bit 23; S.u24 is zero-extended.
let i24 = |x: u32| (i64::from(x & 0x7f_ffff)) - i64::from(x & 0x80_0000);
let u24 = |x: u32| i64::from(x & 0xff_ffff);
match op {
// D.i32 = S0.i24 * S1.i24.
265 => (i24(a) * i24(b)) as u32,
// D.i32 = (S0.i24 * S1.i24)>>32.
266 => (i24(a) * i24(b)).div_euclid(1 << 32) as u32,
// D.u32 = S0.u24 * S1.u24.
267 => (u24(a) * u24(b)) as u32,
// D.u32 = (S0.u24 * S1.u24)>>32.
268 => (u24(a) * u24(b)).div_euclid(1 << 32) as u32,
// D.i32 = (S0.i32 < S1.i32 ? S0.i32 : S1.i32).
273 => (a as i32).min(b as i32) as u32,
// D.i32 = (S0.i32 >= S1.i32 ? S0.i32 : S1.i32).
274 => (a as i32).max(b as i32) as u32,
// D.u32 = (S0.u32 < S1.u32 ? S0.u32 : S1.u32).
275 => a.min(b),
// D.u32 = (S0.u32 >= S1.u32 ? S0.u32 : S1.u32).
276 => a.max(b),
// D.u32 = ~(S0.u32 ^ S1.u32).
286 => !(a ^ b),
// D.u32 = S0.u32 - S1.u32.
294 => (i64::from(a) - i64::from(b)) as u32,
// D.u32 = S1.u32 - S0.u32.
295 => (i64::from(b) - i64::from(a)) as u32,
_ => unreachable!("test only uses the listed forms"),
}
}
/// VOP3A: OP 25:16, VDST 7:0, three 9-bit sources, inline zero at SRC2.
fn vop3(op: u32, dst: u32, a: u32, b: u32) -> [u32; 2] {
[
0xd400_0000 | op << 16 | dst,
(256 + a) | (256 + b) << 9 | 128 << 18,
]
}
fn vmov(dst: u32, value: u32) -> [u32; 2] {
[0x7e00_02ff | dst << 17, value]
}
fn smov(dst: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | dst << 16, value]
}
fn setup(b: u32, exec: u32, scc: bool) -> Vec<u32> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; // load v1
code.extend(vmov(255, b));
code.extend(vmov(2, 0xabad_1dea));
code.extend(smov(106, 0x1357_9bdf));
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend(smov(126, exec));
code
}
fn finish(mut code: Vec<u32>, dst: u32) -> Vec<u8> {
// Restore EXEC, read D and VCC_LO, and XOR in v1 when SCC is set.
code.extend([
0xbefe_03c1,
0x7e04_0300 | dst,
0x7e0c_026a,
0x3a04_0506,
0xbf84_0001,
0x3a04_0501,
0xe070_2000,
0x8001_0200,
0xbbfd_0000,
0xbf81_0000,
]);
words(&code)
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (op, name) in FORMS {
for b in VALUES {
for (dst, src0, src1) in [
(2, 1, 255),
(2, 255, 1),
(1, 1, 255),
(255, 1, 255),
(255, 255, 255),
] {
for exec in MASKS {
for lanes in [7, 32, 45] {
let scc = dst == 255;
let mut code = setup(b, exec, scc);
code.extend(vop3(op, dst, src0, src1));
let input: Vec<_> = VALUES.into_iter().cycle().take(lanes).collect();
let expected = input
.iter()
.enumerate()
.map(|(lane, &x)| {
let read = |reg| if reg == 1 { x } else { b };
// Guide §3.3: a disabled lane retains its previous VGPR.
let d = if exec & (1 << (lane % 32)) != 0 {
expected(op, read(src0), read(src1))
} else {
match dst {
1 => x,
255 => b,
_ => 0xabad_1dea,
}
};
d ^ 0x1357_9bdf ^ if scc { x } else { 0 }
})
.collect();
cases.push(Case {
form: name,
family: "vop3 integer",
label: format!("{name} v{dst}, v{src0}, v{src1} ({b:#x}), EXEC={exec:#x}, {lanes} lanes"),
code: finish(code, dst),
input,
expected,
});
}
}
}
}
}
cases
}
#[test]
fn vop3_integer_matches_the_guide() {
let cases = cases();
assert_eq!(cases.len(), 11 * 12 * 5 * 4 * 3);
for case in &cases {
assert_eq!(
xenora_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"reference: {}",
case.label
);
assert_eq!(
independent_ref::execute(&case.code, &case.input).unwrap(),
case.expected,
"independent: {}",
case.label
);
}
eprintln!("vop3_integer: {} cases per CPU interpreter", cases.len());
}
#[test]
fn vop3_integer_rejects_excluded_operands_and_modifiers() {
let mut count = 0;
for (op, name) in FORMS {
let setup = setup(7, u32::MAX, false);
let offset = setup.len() * 4;
let [head, tail] = vop3(op, 2, 1, 255);
let mut check = |alu: &[u32]| {
let mut code = setup.clone();
code.extend(alu);
let code = if alu.len() == 1 {
words(&code)
} else {
finish(code, 2)
};
let input = [1, 2];
let err = xenora_ref::execute(&code, &input).expect_err(name);
assert_eq!(err.offset, offset, "{name}: {alu:08x?} {err:?}");
let err = independent_ref::execute(&code, &input).expect_err(name);
assert!(
err.starts_with(&format!("{offset:#x}:")),
"{name}: {alu:08x?} {err}"
);
count += 1;
};
// ABS, OP_SEL and CLAMP in word 0. OMOD and NEG in word 1.
for bit in 8..16 {
check(&[head | 1 << bit, tail]);
}
for bit in 27..32 {
check(&[head, tail | 1 << bit]);
}
for selector in 0..256 {
check(&[head, (tail & !511) | selector]);
check(&[head, (tail & !(511 << 9)) | selector << 9]);
}
for selector in (0..512).filter(|&s| s != 128) {
check(&[head, (tail & !(511 << 18)) | selector << 18]);
}
check(&[head]);
}
assert_eq!(count, 11 * (13 + 512 + 511 + 1));
eprintln!("vop3_integer: {count} rejections per CPU interpreter");
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop3_integer_matches_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
let cases = cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"vop3_integer: {} Metal cases in {programs} programs",
cases.len()
);
}