Compare commits

..
Author SHA1 Message Date
atharvranjan ded1371b99 Correct the GPU-executed test counts in the victory-shader record using libtest JSON output 2026-11-25 15:36:33 -06:00
atharvranjan 6cebcc559e Add the shader GPU test runner script and the victory-shader integration record 2026-11-25 15:22:19 -06:00
atharvranjan 790061e7c0 Vendor victory-shader (GFX10 to DXIL recompiler) from skakwy/victory-mac and add translate_native with BetterXen fixture tests 2026-11-25 15:22:19 -06:00
atharvranjan 8e5856bbcf Detect stalled runs, wait for memory to settle after a stop, and stop bottles through WINEPREFIX (#385) 2026-11-25 15:08:42 -06:00
atharvranjan 566272082a Record the first CrossOver 26.3 execution baseline, backend comparison and licence entry 2026-11-25 14:55:51 -06:00
atharvranjan 64ba56079f Add the D3D11 frame-loop workload, negative controls and reproducible workload builds 2026-11-25 14:55:51 -06:00
atharvranjan e266670e87 Add betterxen-hybrid run and bench: supervised CrossOver launches with structured records and backend comparison 2026-11-25 14:55:50 -06:00
atharvranjan 54b06fea3e Record the victory-mac component review, registry, reuse matrix and notices 2026-11-25 14:41:24 -06:00
atharvranjan 8eb25fb9fe Add original Windows workloads and a checksum-pinned llvm-mingw build script 2026-11-25 14:41:24 -06:00
atharvranjan 40ffea2789 Add betterxen-hybrid guard: memory-pressure supervisor adapted from skakwy's victory-mac memory guard 2026-11-25 14:41:24 -06:00
atharvranjan 80eacf9ac2 Add the betterxen-hybrid crate: host receipt, CrossOver discovery, toolchain probe and frame statistics 2026-11-25 14:33:22 -06:00
atharvranjan d9816e4cb5 Record the upstream integration audit and extend the registry and reuse matrix 2026-11-25 14:33:22 -06:00
atharvranjan 39b628d60d Fix a link in the archived README milestones 2026-11-25 14:23:04 -06:00
atharvranjan 1d70633958 Keep the local Agent Spawning section out of the shared engineering rules
That section was an uncommitted local addition and is not part of main.
2026-11-25 14:22:57 -06:00
atharvranjan a9f55b51f7 State that the native-first-final tag marks the last main commit before the transition 2026-11-25 14:22:38 -06:00
atharvranjan 722388a46d Record the planning transition in the changelog
CrossOver-based hybrid direction, rewritten engineering rules, native work paused and archived, upstream registry and research records.
2026-11-25 14:22:17 -06:00
atharvranjan e7ff293eba Record primary-source verification and finalize the Phase 1 backlog
Add the hybrid research record and a primary-source re-check (CodeWeavers, Apple, DXMT, Wine, Rust toolchain), rename the roadmap's parked section to Parked ideas, and add the matching changelog and docs index entries. Unrelated local work stays uncommitted.
2026-11-25 14:22:09 -06:00
atharvranjan dfaaa07df4 Update README, CONTRIBUTING, docs index, changelog and template for progressive planning
Only this task's hunks are committed; unrelated local edits remain uncommitted.
2026-11-25 14:21:53 -06:00
atharvranjan 962b83c731 Extend the upstream registry with unreviewed candidates
llvm-mingw, Sikarugir, macOS Wine builds, Mythic and Playdock, metadata only.
2026-11-25 14:21:47 -06:00
atharvranjan 7fff77c801 Simplify the roadmap to one active phase and archive the native issue backlog
Five provisional phases with only Phase 1 active, parked ideas, Phase 1 completion criteria, a simple project board guide, the retired H0 to H7 breakdown, and an index of the closed native issues with preserved findings and contributor attribution.
2026-11-25 14:21:47 -06:00
atharvranjan c3684a1ae8 Add progressive planning rules to the engineering rules
Only the current phase has a milestone and open issues; future ideas are parked in the roadmap; issues carry evidence, reuse assessment and validation; no native-only issues.
2026-11-25 14:21:47 -06:00
atharvranjan d561595599 Replace issue templates and add a pull request template
Hybrid task, bug, research, performance, validation and documentation forms with problem, context, scope, dependencies, acceptance, validation and licensing sections. Fix invalid YAML in the agent-task template.
2026-11-25 14:21:47 -06:00
atharvranjan 8cab0b1de8 Describe the hybrid direction in README, CONTRIBUTING, docs index and changelog
Only this task's hunks are committed; unrelated local edits to CHANGELOG.md and docs/README.md remain uncommitted.
2026-11-25 14:21:40 -06:00
atharvranjan d2367dca30 Add the upstream research registry and component reuse matrix
Public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch with license, pin and reuse decisions. VIctory-family projects are excluded from reuse on provenance grounds.
2026-11-25 14:20:55 -06:00
atharvranjan 60ad6c779e Add the CrossOver-based hybrid roadmap and archive the native-first plan
Add docs/roadmap.md (phases H0 to H7, critical path), ADR 0005 (accepted direction; proposed architecture and unverified assumptions kept separate), the deferred native roadmap and the project board setup guide. Archive the native-first plan and the seven retired milestones. Mark the PortWatch review as superseded in part.
2026-11-25 14:20:55 -06:00
atharvranjan ffc7056d26 Rewrite engineering rules for the CrossOver-based hybrid direction
Replace the native-first prohibition on Wine, CrossOver, Rosetta and MoltenVK with dependency, reuse, licensing and provenance rules. Keep the honesty, independent-verification, clean-room, claiming, changelog and subagent rules. CLAUDE.md remains a symlink to AGENTS.md. Resolves #345 once reviewed.
2026-11-25 14:20:55 -06:00
atharvranjan 9923e59114 Merge pull request #296 from maridogolpeador/app/252-open-command
app: add Command-O and show file-picker errors (#252)
2026-11-25 12:08:20 -06:00
atharvranjan feba95fe39 Merge origin/main into app/252-open-command
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:52:31 -06:00
atharvranjan a275de6e2e Merge pull request #295 from maridogolpeador/app/251-inspection-request-order
app: keep inspection results tied to the latest selection (#251)
2026-11-25 11:51:15 -06:00
atharvranjan 25986845da Merge origin/main into app/251-inspection-request-order
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 11:46:03 -06:00
atharvranjan df9652740b Merge pull request #309 from soggyramennoodle/task/255-startup-diagnostics
Report trusted fixture startup progress
2026-11-25 11:42:21 -06:00
atharvranjan 1ca491d8d0 Merge pull request #297 from maridogolpeador/docs/260-texture-format-inventory
docs: inventory texture formats and layouts by stage (#260)
2026-11-25 11:42:08 -06:00
atharvranjan 964a8296f2 Merge pull request #294 from atesahmet0/task/154-cpu-coverage-map
Add the verified CPU/loader coverage map
2026-11-25 11:41:54 -06:00
atharvranjan d8a8c96408 Merge pull request #338 from Thxlx/perf/89-arm64-constant-load
perf: shorten ARM64 loads for zero-extended constants
2026-11-25 11:40:55 -06:00
atharvranjan 50321b3f14 Merge pull request #337 from Thxlx/docs/299-avx-contract 2026-11-25 10:56:04 -06:00
Thilo Schaeffer 1fe07f45ee test: clarify ARM64 assembler offset units
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:05 +01:00
Thilo Schaeffer d486d21813 docs: clarify AVX exception policy and Intel references
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:45:04 +01:00
Thilo Schaeffer 4c92c88b29 perf: shorten ARM64 loads for zero-extended constants
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:31:03 +01:00
Thilo Schaeffer 478e9218ac docs: specify the guest AVX and AVX2 contract
Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com>
2026-11-25 17:21:18 +01:00
Adeeb Rahman 8d2662dcd7 Preserve startup report delivery and worker errors
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:56:31 -05:00
Adeeb Rahman fe1bf568c8 Merge BetterXen main
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 09:51:45 -05:00
maridogolpeador 873652d685 app: run inspection reads on a Dispatch queue, not a concurrency worker (#251)
Review follow-up. The reader blocks on file I/O, and in the
--smoke-inspection-order check on its gate semaphore. Inside
Task.detached that blocked a Swift concurrency worker; with a
single-worker cooperative pool the released newer read could not start
while the older one waited, and the check timed out. The read now runs
on DispatchQueue.global(qos: .userInitiated) and is bridged back with
withCheckedContinuation. The request-number guard is unchanged.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:38:12 -03:00
ates 84f561b12b Fix the documented known-answer count command
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:14:50 +03:00
maridogolpeador 2b113a2e5e docs: separate host API coverage from guest reachability and link sources (#260)
Review follow-up. The Guest column credited the descriptor-table SRVs,
which tests call directly from Rust and the interface contract says
are not yet wired to guest imports. The table now has a Host graphics
API column for them and keeps Guest for paths an original PE fixture
reaches through imported services: today only RGBA8, through the
synthetic xenora.dll texture services of the Gate 5 fixture. Every
repository path is now a relative link, and each format row links the
exact Khronos DFS 1.3 section and Microsoft or Apple page it relies on.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:44 -03:00
maridogolpeador 9a26e1ee36 docs: inventory texture formats and layouts by stage (#260)
Add docs/research/texture-formats.md, built from BetterXen main. For
RGBA8, BC1-BC7 and Depth32Float it separates container recognition,
CPU decoding, layout conversion, native Metal upload and readback,
translated sampling and guest reachability, linking the implementing
files and tests for each cell, including the packed BC footprints from

It cross-references #208 and #209 rather than opening duplicate tasks,
records console layouts, console descriptors and asset or audio
containers as unknowns, and ranks three proposed follow-ups with an
original-fixture recipe, an independent source of expected values and
an owner each. Deferred formats with no demonstrated need are listed.

docs/README.md indexes the page. Research only; no code changed.

Ported from XenoraOSS/Xenora#427 and re-checked against BetterXen main.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:43 -03:00
maridogolpeador c84b80b24f app: route Command-O to the focused window's importer (#252)
Review follow-up. The command set a shared Boolean, so with every
window closed there was no importer to present it, and with several
windows each one bound the same flag. Each ContentView now owns its
importer state and publishes an open action with focusedSceneValue;
OpenExecutableCommand reads it with @FocusedValue, calls it for the
focused window and is disabled when no window provides it. The
inspector button uses the same per-window action. InspectionModel no
longer holds the importer flag; requestImport only clears the previous
selection error.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador ae804f0530 app: gate the inspection-order smoke check instead of sleeping (#251)
Review follow-up. The check used fixed 300/700 ms pauses, so on a
loaded host a late stale read could arrive after an assertion, or the
newer read could finish before the busy-state check. The injected
reader now blocks until the check releases that file, and the check
waits on InspectionModel.finishedReads, which counts every finished
read whether it was published or discarded. A five-second deadline
bounds the wait without deciding the order.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 64e7b16983 app: add Command-O and show file-picker errors (#252)
The inspector had an Open Executable… button but no app-level Open
command, and the file importer's completion ignored failures, so a
picker error was never shown.

- File > Open Executable… with Command-O, after New Window. It calls
  the same requestImport() as the button, so it opens the same
  read-only importer and the chosen file reaches inspect(), the path
  shared with drag and drop and Finder Open With.
- importFinished(_:) handles the importer result: success inspects,
  a user cancellation (CocoaError.userCancelled) shows nothing, and any
  other failure is shown in red with the error's description. The
  message clears on the next request or selection.
- --smoke-import-result checks cancellation, a shown failure and its
  clearing without opening files; scripts/build-app.sh runs it after
  --smoke. It fails with the previous importer handling and without the
  cancellation check.

Opening a file still never starts guest execution, the DBT or the JIT.

Ported from XenoraOSS/Xenora#424.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
maridogolpeador 1ea898b4bf app: keep inspection results tied to the latest selection (#251)
InspectionModel.inspect started a detached read per call and published
status, report and busy whenever any of them finished. A slow first
inspection that completed after a fast second one replaced the newer
report and status, and could clear busy while the newer read was still
running.

- Each inspect call takes a request number; a completion is applied
  only while it is still the latest, so stale success and stale failure
  are discarded. Picker, drag and drop and Finder Open With all go
  through inspect and share this.
- A new selection clears the previous report, and a failed inspection
  of the latest file is shown in red above its report.
- The read is unchanged: size checked before reading, balanced
  security-scoped access, nothing executed. The reader is injectable
  only for the smoke check.
- --smoke-inspection-order drives the model with an injected slow and
  fast reader: slow then fast with either outcome, and busy held for the
  newer request while an older read finishes. scripts/build-app.sh runs
  it after --smoke. All four checks fail without the change.

Ported from XenoraOSS/Xenora#423.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 10:09:31 -03:00
ates 7946968cc4 Address coverage review and merge current main
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 16:03:49 +03:00
atharvranjan 67b8cff9df Merge pull request #326 from MacosPorters/claude/pr-294-review-nftzfu
Rewrite the README around the development phases and launch target
2026-11-25 05:59:17 -06:00
atharvranjan 51c23a2f38 Merge pull request #293 from maridogolpeador/ci/248-app-build
ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
2026-11-25 05:58:01 -06:00
Claude 7d97e67448 Rewrite the README around the development phases and launch target
Reorganize the README around the six development phases and the first
launchable application tracker, add colour-coded Mermaid diagrams and
registry-derived charts, a repository overview and a contributing
section, and correct the texture-sampling and recompiler wording.

Signed-off-by: Claude <noreply@anthropic.com>
2026-11-25 11:53:09 +00:00
atharvranjan d9261db887 Merge pull request #325 from MacosPorters/repo/add-codeowners
Add CODEOWNERS and replace
2026-11-25 04:39:37 -06:00
atharvranjan 5c0c82b3f9 Add a fast repository hygiene check
Add hygiene.yml and scripts/audit/docs_hygiene.py: fail on merge-conflict
markers, broken relative Markdown links and invalid workflow YAML, and
warn (advisory) when source changes lack a changelog entry.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:24:36 -06:00
atharvranjan b71db3c25a Remove the pull request template
Delete .github/PULL_REQUEST_TEMPLATE.md and update CONTRIBUTING.md and
the changelog to match.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:23:03 -06:00
atharvranjan 566f803111 Remove the PR template check
Delete the pr-template workflow, its checker script and tests, and the
CI step that ran those tests. Update CONTRIBUTING.md and the changelog.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:18:06 -06:00
atharvranjan 857c16fcf7 Merge origin/main into repo/add-codeowners
Resolve conflicts in favor of main's development phases and roadmap
text. Keep the game-title wording and PE-Vulkan project renames, the
PortWatch research notes and their docs index link.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:16:38 -06:00
atharvranjan 4f5c6913f5 Replace game-title and upstream-project names in our own docs
Use generic 'commercial title' wording for our own references to a
specific game, rename the ignored diagnostics folders to
title-candidate-* and title-check, and refer to the upstream PE/Vulkan
project as 'PE-Vulkan project' in prose. Third-party URLs and repository
paths are unchanged to keep provenance accurate. Also adds the native
macOS development phases and PortWatch research notes already in the
working tree.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 04:12:59 -06:00
Adeeb Rahman e4ddb05a1a Run startup draw check on native Metal hardware
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:27:42 -05:00
Adeeb Rahman d33a7c6941 Report trusted fixture startup progress
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-25 00:23:04 -05:00
maridogolpeador 4e838207fe ci: check the printed dependency listing and reject empty or failed listings (#248)
Review follow-up. build-app.sh now runs otool -L once in a checked
assignment, prints that output and parses the same text, so a failing
or empty listing fails the gate instead of skipping the loop. Every
Swift executable links libSystem, so an empty list is an error.
Bundle-relative entries (@rpath, @executable_path, @loader_path) get
their own message. The changelog entry now separates the designed CI
behaviour from what has been verified locally.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 02:09:22 -03:00
ates b40bbae1da Refresh the coverage map at merged main b2654e9
The branch now contains main b2654e9, which includes the merged DBT
cache-identity pull and the migration-benchmark checks, so the map pins
its single gate run to that revision: the former self-modifying-code
defect test executes and passes in both DBT engines (cpu_known_answers
50 passed, 0 ignored) and the workspace gate reports 116 result lines
with 1015 passed, 0 failed and 34 ignored. The ignore taxonomy in the
map names all three kinds from their own messages: Metal-gated,
LLVM-gated (gfx1030 AMDGPU target) and manual timing runs.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 08:07:53 +03:00
maridogolpeador b04b41f26a ci: build and smoke-test BetterXen.app on native ARM64 runners (#248)
The CI workflow built and inspected the CLI but never ran
scripts/build-app.sh, so a Swift compile, link or smoke failure in app/
passed CI.

- ci.yml: a second job, "Native app build and smoke", on the same
  macos-26 image, pinned Rust toolchain and CARGO_BUILD_JOBS as the Rust
  job. It verifies an arm64 host without Rosetta, prints the Xcode and
  Swift versions and runs scripts/build-app.sh. The Rust job is
  unchanged.
- build-app.sh: after the lipo check, print file and otool -L for the
  executable and fail if it links anything outside /System/Library/ and
  /usr/lib/.

No Metal fixture runs in the new job; --smoke probes the C interface
and the trusted fixture's headers only. The same change was proposed
upstream as XenoraOSS/Xenora#426.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-25 01:59:03 -03:00
ates 3dd3ef06e2 Merge main into CPU coverage map
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:58:15 +03:00
atharvranjan b2654e93a4 Merge pull request #292 from MacosPorters/fix/migration-benchmark-checks
Run benchmark report tests in CI and record migration integration
2026-11-24 22:52:27 -06:00
ates fee956293d Add the verified CPU/loader coverage map
Document what the CPU and loader tests verify, per operation family, in
docs/testing/cpu-coverage.md: the declared-form inventory (213 operations,
403 forms, 498 opcode slots from the validated registry), the per-operation
engine split (93 native-lowered, 120 shared-semantic, with the conditional
width and encoding gates), a per-artifact evidence table with exact pass
counts from one full workspace gate run on Apple M5, the reconciliation of
the eight operations covered by model tests instead of the assembly-fixture
corpus, and a recorded note that three advisory qa cpu-inventory
unsupported-catalog rows are stale against the implemented and tested forms.
Also updates the docs/README.md description line and adds the CHANGELOG
entry under [Unreleased].

Closes #154.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-25 07:52:19 +03:00
atharvranjan 146d2dd467 Correct Win64 call-entry alignment wording
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:46:05 -06:00
atharvranjan a0d9b85dbf Run benchmark report tests in workspace CI and record migration review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:42:19 -06:00
atharvranjan 5366b93986 Merge pull request #269 from MacosPorters/archive/pull/371/head
Validate DBT caches with executable generations and source revalidation
2026-11-24 22:31:00 -06:00
atharvranjan 50c392111d Merge pull request #266 from MacosPorters/archive/pull/352/head
bench: measure Metal startup in fresh processes and repeated runs (#178)
2026-11-24 22:26:04 -06:00
atharvranjan f43a07ce31 Synchronize cache generation fix with the integrated hosted C runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:25:18 -06:00
atharvranjan 10fd1cd4be Merge pull request #265 from MacosPorters/archive/pull/346/head
metal: budgeted staged RGBA8 texture upload into Private storage (#144)
2026-11-24 22:24:24 -06:00
atharvranjan 95aa10c60f Merge pull request #278 from MacosPorters/archive/pull/394/head
Pack block-compressed texture mip chains by subresource
2026-11-24 22:24:17 -06:00
atharvranjan 873b4fd4a9 Integrate PR #266 and distinguish imported benchmark evidence
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:19:01 -06:00
atharvranjan 120878de2d Integrate PR #265 bounded native Metal texture staging
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:16:37 -06:00
atharvranjan d26af53cef Merge pull request #283 from MacosPorters/archive/pull/420/head
loader: add the Gate A2 hosted C program and its test (#419)
2026-11-24 22:15:23 -06:00
atharvranjan b6ebaaad5e Merge pull request #282 from MacosPorters/archive/pull/418/head
loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
2026-11-24 22:11:50 -06:00
atharvranjan 44ac976291 Retain cache-hit assertions with generation-triggered source revalidation
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:10:24 -06:00
atharvranjan 0bd8e19aac Merge pull request #281 from MacosPorters/archive/pull/401/head
loader: add standard output and printf formatting for a hosted C program (#400)
2026-11-24 22:08:23 -06:00
atharvranjan e93509ef5b Merge pull request #280 from MacosPorters/archive/pull/399/head
loader: add exit, _exit and abort for a hosted C program (#395)
2026-11-24 22:04:34 -06:00
atharvranjan 8344e299c9 Merge pull request #277 from MacosPorters/archive/pull/393/head
loader: add program arguments for a hosted C program (#392)
2026-11-24 22:04:27 -06:00
atharvranjan 433dc43695 Merge pull request #273 from MacosPorters/archive/pull/385/head
loader: add nine C runtime startup services a hosted C program imports (#382)
2026-11-24 22:04:19 -06:00
atharvranjan a0f2d833aa Merge pull request #276 from MacosPorters/archive/pull/390/head
loader: add VirtualProtect, VirtualQuery and __C_specific_handler as stubs (#388)
2026-11-24 22:04:10 -06:00
atharvranjan 61afca42c9 Merge pull request #279 from MacosPorters/archive/pull/397/head
loader: run LOOP, LOOPE, LOOPNE and JRCXZ (#396)
2026-11-24 22:04:02 -06:00
atharvranjan be19e4e28f Merge pull request #275 from MacosPorters/archive/pull/389/head
loader: run LAHF and SAHF and report them in CPUID (#387)
2026-11-24 22:03:56 -06:00
atharvranjan 33ccf7fd55 Merge pull request #271 from MacosPorters/archive/pull/381/head
loader: add FNINIT and the x87 control, status and tag words (#378)
2026-11-24 22:03:49 -06:00
atharvranjan bb62353cfe Merge pull request #274 from MacosPorters/archive/pull/386/head
loader: raise #GP for instructions longer than 15 bytes (#384)
2026-11-24 22:03:42 -06:00
atharvranjan 1f2e7d3bb6 Merge pull request #272 from MacosPorters/archive/pull/383/head
bench: compare two dbt_bench JSON results (#114)
2026-11-24 22:03:34 -06:00
atharvranjan b5b646a58d Warm differential-test caches within the same guest address space
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:02:34 -06:00
atharvranjan 4314071ac7 Validate DBT cache identity with executable generations instead of byte scans
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:14 -06:00
atharvranjan 4e15e5f43b Synchronize PR #275 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:16 -06:00
atharvranjan cf4010ba94 Synchronize PR #271 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:14 -06:00
atharvranjan b9e6a9d365 Synchronize PR #274 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:12 -06:00
atharvranjan a1a1020ebd Synchronize PR #272 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:10 -06:00
atharvranjan e755ee94ed Merge pull request #264 from MacosPorters/archive/pull/340/head
benchmarks: measure gfx1030 metadata identification
2026-11-24 21:57:34 -06:00
atharvranjan e289318132 Merge pull request #267 from MacosPorters/archive/pull/359/head
loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
2026-11-24 21:49:39 -06:00
atharvranjan f685b54e32 Merge pull request #268 from MacosPorters/archive/pull/369/head
loader: add Win64 service ABI preservation tests (#201)
2026-11-24 21:48:28 -06:00
atharvranjan 0690a3ecb4 Merge pull request #284 from MacosPorters/archive/pull/422/head
loader: copy mid-size TLS templates into the zeroed block (#111)
2026-11-24 21:48:22 -06:00
atharvranjan 7286989296 Merge pull request #270 from MacosPorters/archive/pull/374/head
Fix ARM64 variable shift register encoding
2026-11-24 21:47:03 -06:00
Ranveer Soni 4cc703d566 Merge branch 'main' into fix/84-dbt-stale-code-cache 2026-11-25 07:02:16 +05:30
atharvranjan e856f080d1 dbt: retranslate cached blocks when guest code changes (#84)
Each cached block keeps the guest bytes it was translated from and is compared with the current executable bytes on every lookup.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 14:17:40 -06:00
Swastickc b09d96fd62 bench: measure Metal startup in fresh processes and repeated runs (#178)
Add `xenora-bench startup`. It checks one manifest fixture against the
independent reference, then times it phase by phase in two regimes: a
series of fresh child processes that each create the Metal device and
queue, translate and run the fixture once, and one process that
repeats the run. Phases are launch to main, device and queue,
translation, library, pipeline, submission, GPU and readback, reported
as median, p90, p99 and maximum, with raw fresh samples in launch
order.

Every sample must produce the expected output. A wrong output, a
failed or hung child (killed after 60 s) or a damaged sample line
stops the run before any result is written. Children inherit the
environment so the recorded MTL_* validation state applies to both
regimes.

Document the method and one recorded release run on an Apple M4 in
docs/testing/benchmarks.md, and add a changelog entry. Measurement
only.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:59:59 +05:30
Swastickc 6814d78230 metal: budgeted staged RGBA8 texture upload into Private storage (#144)
Add an opt-in staged upload beside the existing direct upload.
plan_staged_upload splits a full RGBA8 upload into submissions of
whole-row bands that never exceed a StagingBudget. It rejects missing,
duplicate or out-of-range mip levels, wrong mip sizes, short row
pitches or byte buffers, and budgets smaller than one row before any
Metal object exists.

MetalRgba8Texture::upload_staged fills a Private-storage texture
through one reused Shared staging buffer with blit copies, and reuses
the buffer only after the previous command buffer completed with
status Completed. read_back copies any mip back as tight RGBA8 bytes
through a blit. A Private texture refuses upload_mip with an error.

Enable objc2-metal's MTLBlitCommandEncoder feature for the blit
encoder; Cargo.lock is unchanged.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:32:49 +05:30
134 changed files with 51786 additions and 599 deletions

No files matched your search

+3 -2
View File
@@ -7,8 +7,9 @@ body:
id: area
attributes:
label: Area
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
description: "hybrid: CrossOver integration, configuration, diagnostics, benchmarks (active). The areas below are preserved native research unless hybrid work requires them. cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
options:
- hybrid
- cpu
- gpu
- runtime
@@ -43,7 +44,7 @@ body:
id: files
attributes:
label: Files
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
description: 'Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.'
render: text
validations:
required: true
+30 -15
View File
@@ -1,42 +1,57 @@
name: Bug report
description: Report a reproducible defect in Xenora or XenoMetal.
description: A reproducible defect.
title: "bug: "
labels: [bug]
body:
- type: markdown
attributes:
value: |
Use synthetic or authorized inputs only. For vulnerabilities, follow SECURITY.md. Remove personal paths, credentials and private data from logs.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. For vulnerabilities follow SECURITY.md.'
- type: textarea
id: description
attributes:
label: Description
description: What went wrong? Identify the affected subsystem and expected behavior.
description: 'What went wrong and what you expected.'
validations:
required: true
- type: textarea
id: steps
attributes:
label: Reproduction steps
description: Include exact commands and a minimal, legally distributable input if applicable.
description: 'Exact commands and a minimal, legally distributable input.'
validations:
required: true
- type: textarea
id: environment
attributes:
label: Environment
description: Commit, macOS, Apple GPU, RAM, Rust, Xcode and relevant tool versions. Include sanitized doctor output if available.
description: 'Commit, macOS, chip, memory, CrossOver and Rosetta 2 versions, graphics backend. Remove personal paths and credentials.'
validations:
required: true
- type: textarea
id: output
id: scope
attributes:
label: Actual output and diagnostics
description: Include expected versus actual results, validation-layer messages and relevant logs.
- type: checkboxes
id: confirmation
label: Scope and dependencies
description: 'Affected area; related issues.'
validations:
required: false
- type: textarea
id: acceptance
attributes:
label: Confirmation
options:
- label: I searched for existing reports and have not included sensitive or unauthorized material.
required: true
label: Acceptance criteria
description: 'When is this fixed?'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How to confirm the fix independently.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: 'Only if third-party code or a dependency is involved.'
validations:
required: false
+50
View File
@@ -0,0 +1,50 @@
name: Documentation
description: Fix, add or restructure documentation.
title: "docs: "
labels: [documentation]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is unclear, wrong or missing.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Pages and sources involved.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Files to change; update docs/README.md if pages are added or moved.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'None if none.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Claims are scoped to their evidence; links work.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'scripts/audit/docs_hygiene.py and claims audit pass.'
validations:
required: true
-31
View File
@@ -1,31 +0,0 @@
name: Feature proposal
description: Propose a compiler, graphics, tooling or other project enhancement.
title: "feat: "
labels: [enhancement]
body:
- type: textarea
id: problem
attributes:
label: Problem or gap
description: Which limitation does this feature address?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed approach
description: Explain the intended behavior and affected components. Link relevant public specifications when available.
validations:
required: true
- type: textarea
id: criteria
attributes:
label: Acceptance criteria
description: What observable results and tests would demonstrate completion?
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives and trade-offs
description: Include limitations, dependency costs or impacts on native ARM64 and Metal if relevant.
-31
View File
@@ -1,31 +0,0 @@
name: Hardware verification report
description: Submit real hardware test results for Xenora.
title: "hardware: "
labels: [needs-verification]
body:
- type: textarea
id: environment
attributes:
label: Test environment
description: Commit, Apple chip/GPU, RAM, macOS, Xcode/Metal version, Rust version, validation settings. Do not include serial numbers or registry IDs.
validations:
required: true
- type: textarea
id: commands
attributes:
label: Commands and inputs
description: Include exact commands and synthetic or authorized fixture identifiers.
validations:
required: true
- type: textarea
id: results
attributes:
label: Results
description: Report actual output, pass/fail/skip counts, and limitations. Compilation alone does not prove execution.
validations:
required: true
- type: textarea
id: performance
attributes:
label: Performance data (optional)
description: Include repetitions, warm-up, timing method, validation state and variability if reporting measurements.
+57
View File
@@ -0,0 +1,57 @@
name: Hybrid engineering task
description: Integration, configuration, diagnostics or tooling around CrossOver.
title: "task: "
labels: [track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Performance investigation
description: Measure or improve performance with evidence.
title: "perf: "
labels: [performance,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. Do not promise gains before measuring.'
- type: textarea
id: problem
attributes:
label: Problem and metric
description: 'Which metric (average FPS, 1% low, frame-time percentiles, CPU or GPU use, memory, startup, shader compile latency) and why.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Workload, hardware (reference: M4, 24 GB), software versions, settings.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'Measurement only, or change as well.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Measurement protocol (#353) and baseline (#355).'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Measured before-and-after under equivalent conditions, with variance.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'Correctness and rendering equivalence verified before the result counts.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+37 -22
View File
@@ -1,42 +1,57 @@
name: Technical research
description: Record an ISA, Metal or publicly documented graphics research finding.
name: Upstream research or dependency evaluation
description: Assess a project, component or license from public sources.
title: "research: "
labels: [research]
labels: [research,track: hybrid]
body:
- type: markdown
attributes:
value: Use only public, authorized sources. Do not link to leaked SDKs, private documentation or unauthorized game content.
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: question
id: problem
attributes:
label: Research question or finding
label: Question
description: 'The decision this research informs.'
validations:
required: true
- type: textarea
id: sources
id: context
attributes:
label: Sources and applicability
description: URLs, specification sections or revision, exact architecture and license/provenance if relevant.
label: Technical context
description: 'What is already known; link docs/research/upstream-registry.md entries.'
validations:
required: true
- type: dropdown
id: evidence
- type: textarea
id: scope
attributes:
label: Evidence class (highest applicable)
options:
- A - Measured on named hardware
- B - Normative source for exact target
- C - Normative source for related target
- D - Non-normative official material
- E - Independent software behavior
- F - Uncorroborated community claim
- U - Unknown or assumption
label: Scope
description: 'Which versions or components; desk research or execution.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: 'Other issues or decisions; execution may need a maintainer-approved environment.'
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Each claim cites vendor or upstream documentation, or a recorded observation of a stated version; unknowns stay marked unknown.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation, limitations and proposed next steps
description: Distinguish Apple or desktop RDNA observations from Xbox behavior.
label: Validation requirements
description: 'Independent re-derivation and evidence class (A to U).'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
+57
View File
@@ -0,0 +1,57 @@
name: Testing and validation
description: Add or run a validation for a workload or behaviour.
title: "validate: "
labels: [needs-verification,track: hybrid]
body:
- type: markdown
attributes:
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
- type: textarea
id: problem
attributes:
label: Problem
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
validations:
required: true
- type: textarea
id: context
attributes:
label: Technical context
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
validations:
required: true
- type: textarea
id: scope
attributes:
label: Scope
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
validations:
required: true
- type: textarea
id: dependencies
attributes:
label: Dependencies
description: "Blocking issues or decisions; write 'none' if none."
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: 'Observable, checkable results.'
validations:
required: true
- type: textarea
id: validation
attributes:
label: Validation requirements
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
validations:
required: true
- type: textarea
id: licensing
attributes:
label: Licensing and provenance
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
validations:
required: true
-40
View File
@@ -1,40 +0,0 @@
## Summary
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
## Implementation and evidence
<!-- Describe affected subsystems, architecture assumptions, specification sections and upstream provenance where applicable. -->
## Verification
<!-- List actual commands and outcomes. Include hardware, validation-layer state and pass/fail/skip counts for GPU tests. Mark unrun checks explicitly. -->
| Check | Result / evidence |
| --- | --- |
| Formatting and lint | |
| Unit / integration tests | |
| GPU / differential tests | |
| Fuzzing / mutation / benchmarks, if relevant | |
## Compatibility and limitations
<!-- Note unsupported behavior, regressions, interface changes, performance effects and remaining uncertainty. -->
## Checklist
- [ ] I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
- [ ] I did not report skipped or unrun tests as passing.
- [ ] I updated applicable documentation, claims and status records.
- [ ] Third-party code and fixtures have verified licenses and provenance, or none were added.
- [ ] No restricted materials, credentials or private data are included.
- [ ] My commits are signed off under the DCO.
## AI assistance
<!-- Describe material assistance and the checks you personally performed, or state none. -->
+29
View File
@@ -0,0 +1,29 @@
## Related issue
Closes #
## Summary
## Technical changes
## Tests performed
Commands, versions, pass/fail/skip counts and hardware. A skipped test is not a pass.
## Performance impact
Measured before and after under equivalent conditions, or "none expected" with reason.
## Compatibility impact
Workloads, macOS or CrossOver versions and hardware affected. Do not claim support that was not tested.
## Known limitations
## Third-party code attribution
Source repository, exact commit, license, modifications. "None" if none.
## Dependency and licensing considerations
New or changed dependencies, license compatibility with GPL-3.0-or-later, redistribution limits (proprietary components are never bundled). DCO: commits are signed off.
+30 -2
View File
@@ -63,8 +63,6 @@ jobs:
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
@@ -90,3 +88,33 @@ jobs:
file "$binary"
test "$(lipo -archs "$binary")" = arm64
otool -L "$binary"
native-app:
name: Native app build and smoke
runs-on: macos-26
timeout-minutes: 20
env:
CARGO_BUILD_JOBS: 3
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify runner architecture
run: |
uname -m
test "$(uname -m)" = arm64
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install native Rust
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal
rustc -vV
- name: Show Swift and Xcode
run: |
xcodebuild -version
swift --version
# Builds the locked C ABI library and the Swift app together, checks the
# executable is arm64-only and links only system libraries, and runs
# `--smoke`. This is an app build and smoke result, not GPU verification.
- name: Build BetterXen.app and run its smoke check
run: scripts/build-app.sh
+43
View File
@@ -0,0 +1,43 @@
name: Repository hygiene
# Fast checks on tracked files that need no Rust toolchain and no network:
# merge-conflict markers, broken relative Markdown links and invalid workflow
# YAML (scripts/audit/docs_hygiene.py). A second, advisory step warns when
# source or script changes arrive without a CHANGELOG.md update; it never fails.
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: hygiene-${{ github.ref }}
cancel-in-progress: true
jobs:
hygiene:
name: Repository hygiene
runs-on: ubuntu-24.04-arm
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
- name: Install PyYAML
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
- name: Check documentation and workflow files
run: python3 scripts/audit/docs_hygiene.py --require-yaml
- name: Remind about the changelog (advisory)
if: github.event_name == 'pull_request'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
changed="$(git diff --name-only "$BASE_SHA"...HEAD || true)"
if printf '%s\n' "$changed" | grep -Eq '^(crates|scripts|shaders|fixtures)/' \
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
fi
-38
View File
@@ -1,38 +0,0 @@
name: PR template
# Fails when a pull request description does not follow
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
# is edited; comments never start it. Runs on the base branch: pull request
# code is never checked out or executed, and the description is read as data.
#
# To make it blocking, mark the "PR template / description" check as required
# in the branch protection rule for main.
on:
pull_request_target:
types: [opened, edited, reopened, synchronize]
permissions: {}
jobs:
description:
runs-on: ubuntu-24.04-arm
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the description against the template
run: |
set -u
status=0
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
cat "$RUNNER_TEMP/result.txt"
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -ne 0 ]; then
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
fi
exit "$status"
+2 -2
View File
@@ -36,8 +36,8 @@
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
/diagnostics/title-candidate-*/
/diagnostics/title-check/
# Native application build output
/app/.build/
+38 -18
View File
@@ -1,40 +1,60 @@
# BetterXen engineering rules
### Native Apple Silicon
These rules apply to every contributor and coding agent. They were rewritten on the `planning/hybrid-first-transition` branch when BetterXen moved from native-first to CrossOver-based hybrid development. `CLAUDE.md` is a symlink to this file. The decision is recorded in `docs/adr/0005-crossover-hybrid-direction.md`; the plan is `docs/roadmap.md`.
Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dependencies, Wine, CrossOver, Windows compatibility layers, OpenGL fallback rendering, or unnecessary graphics abstraction layers.
### Direction
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
- The guest architecture being decoded may be x86-64, but BetterXen itself runs natively on ARM64.
- BetterXen is hybrid-first Apple Silicon compatibility research. **CrossOver is the primary compatibility foundation and hybrid is the only active development direction.** CrossOver is an externally installed dependency unless its license explicitly permits another distribution model.
- BetterXen's own work is the layer around it: integration, configuration, environment management, diagnostics, reproducible testing, benchmarking and measured optimization. Reuse established infrastructure before writing an independent replacement; write one only for a demonstrated limitation.
- The independent native implementation (x86-64 decoder, ARM64 translator, runtime, gfx1030 shader compiler, Metal backend) is **preserved and paused**. Do not delete it, expand its roadmap, create speculative native issues or assign contributors to it by default. Native work is allowed only when hybrid development directly requires it, or after an explicit maintainer decision to resume (`docs/research/native-roadmap.md`). Keep its tests passing.
- This is the intended architecture, not a verified Xbox compatibility stack. Do not assume CrossOver, Rosetta 2 or D3DMetal provide Xbox runtime compatibility; verify the actual capabilities and integration boundaries of the installed versions.
### Planning
- Planning is progressive. Only the current phase has a milestone and open issues; the roadmap outlines later phases provisionally and `Parked ideas` holds future items. Do not create speculative issues, trackers or milestones for distant phases; promote an idea when its prerequisites are met.
- Every new issue states a specific problem, the evidence it is needed, a deliverable, upstream references, a reuse assessment, dependencies, acceptance criteria and a validation method. Do not create administrative issues to manage planning.
- Do not open native-only issues. If hybrid work needs a native component, file a focused hybrid issue.
### Dependencies and reuse
- Wine-based compatibility infrastructure, CrossOver, Rosetta 2 where supported and technically appropriate, and D3DMetal (subject to its license terms) are permitted. DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX and similar projects may be evaluated and used where appropriate. Legitimate external dependencies and open-source implementations are encouraged.
- Before integrating or copying anything: verify the exact license of the component (the file for copied source, not just the repository), check compatibility with GPL-3.0-or-later and with every other selected component, preserve copyright notices, record the source repository and exact commit or version, document modifications, and add the entry to `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved. Never remove upstream notices.
- Do not bundle, modify or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Do not assume a proprietary component can be incorporated into GPL-licensed source. Distinguish open-source parts from proprietary parts in every assessment.
- Do not bypass licensing or activation requirements of any dependency.
- Provenance first: exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds, including VIctory, its forks and similar efforts, are discovery references at documentation level; adopt nothing from them without a per-file provenance and license review recorded in the registry. Game-specific, asset-specific and decryption-related code is never adopted.
### Native Apple Silicon host
- BetterXen's own host executables, libraries and tools must support ARM64 natively; verify with file, lipo -archs and otool -L. Do not add x86-64 host executables that BetterXen itself builds or ships.
- Rosetta 2 may be used where Apple supports it and CrossOver or another selected component relies on it for x86-64 guest code. Record versions and its support status; do not depend on it for BetterXen's own code.
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
- Use aarch64-apple-darwin as the Rust target.
- Use aarch64-apple-darwin as the Rust target. Metal is the host graphics API. Do not add graphics abstraction layers beyond what a selected component or a measured need justifies.
- SPIR-V remains permitted as a compiler intermediate representation.
### Honesty and evidence
- Never report a test as passed unless it ran and passed. Never count a skipped test as GPU verification.
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities or implementation status.
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities, interface details, product capabilities or implementation status. Never promise a performance improvement before measuring it.
- Never claim a clean build unless the commands actually succeeded.
- Never present planned features as working. State clearly that game execution is not supported unless demonstrated.
- Never replace GPU tests with mocks and then claim GPU support.
- Unknown information is classified as unknown and becomes a documented research task.
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
- Unknown information is classified as unknown and becomes a documented research task. Facts about CrossOver, Rosetta 2, D3DMetal and other upstreams must cite vendor or upstream documentation, or a recorded observation of a stated version.
- Every hardware claim carries an evidence class (see docs/claims.toml). Never present a lower-class claim as if it were a higher-class one.
- Never claim "verified on Xbox hardware". BetterXen has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
- A phase is complete only with the evidence its exit conditions name. Do not derive progress from commits, lines of code, closed issues or isolated passing fixtures.
### Independence of verification
- The agent that writes a component does not certify it. The two independent reviewers (section 5) re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
- The agent that writes a component does not certify it. Independent reviewers re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
- The same faulty code must never produce both the expected and the actual values in a test.
### Legal and clean-room
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
- Use only publicly accessible documentation, publicly licensed software and authorized materials. All validation uses independently authored or authorized workloads. Never obtain or use leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections. Do not attempt to bypass documentation access restrictions.
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
- Include a plain statement in docs/legal.md: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
- Keep BetterXen's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
- docs/legal.md states: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. This is not legal advice; contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Keep BetterXen's own implementation original where it is original. Never copy, port, translate or adapt source from emulator projects built for leaked or unauthorized material (for example PE-Vulkan, KyTx, AnyPS5 and similar).
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
- Never place restricted material in the repository or its Git history.
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
@@ -43,7 +63,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
No AI slop (section 29).
Read docs/interfaces.md and docs/progress.md before implementation.
Read docs/roadmap.md, docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
@@ -84,7 +104,7 @@ A coding agent claims in the name of the person it works for and follows the sam
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
- Test: `cargo test --workspace`
- Verify the synthetic fixtures: `scripts/assemble-fixture.sh --check`
- Run native GPU correctness: `scripts/test-gpu.sh`
- Run native GPU correctness (preserved native research): `scripts/test-gpu.sh`
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
@@ -101,4 +121,4 @@ Preserve the configured Git author and committer identity.
## Ownership
Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
These are responsibility areas, not personal assignments; do not assign people without their agreement. Hybrid integration owns the CrossOver assessment, integration boundary, configuration, diagnostics and benchmarks. Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
+54 -1
View File
@@ -9,7 +9,34 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and run them on the Apple GPU through D3D12 under CrossOver 26.3 (D3DMetal), plus `scripts/hybrid/run-shader-gpu-tests.sh`, which runs them through `betterxen-hybrid run`. Local results on the M4, not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words (add, float-exact, bitwise-branch, or, shifts, ashr) matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed (wave-wide reductions), 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
- Added `--stall-timeout` and a memory-settle wait to `betterxen-hybrid run`/`bench` (#385): a run that prints nothing for the given time is stopped and classified `stalled`, and after any stop the supervisor waits (up to `--settle-bound`, default 60 s) until free memory is back above the start threshold and records whether it recovered. Based on supervision lessons from skakwy's victory-mac (reimplemented, not copied). Also fixes a defect found by the first real stall run: stopping a bottle used `CX_BOTTLE`, which does not select the bottle, so a stopped Windows process kept running; it now sets `WINEPREFIX`. Verified with 4 new unit tests (stub launcher) and a real CrossOver 26.3 run on the M4: a silent workload was stopped as `stalled` after 4.7 s of a 120 s timeout, nothing was left running, and the next run passed. The low-memory recovery path is only tested with an injected memory reader. Not independently reviewed.
- Added `betterxen-hybrid run` and `bench`: launch a Windows program through an installed CrossOver (`bin/wine --bottle`, an interface CodeWeavers does not document for macOS), with timeout, the memory guard, failure classification (passed, failed exit, timed out, stopped on low memory, cannot execute, no graphics device), sampled CrossOver process memory and CPU, thermal notes, recognised host-noise diagnostics and frame statistics, and write a JSON record; `bench` repeats a workload across graphics backends. Locally verified with 24 unit tests (stub launcher) and with real runs on CrossOver 26.3 on the Apple M4.
- Executed the original Windows workloads under CrossOver 26.3 for the first time (`docs/research/crossover-baseline-2026-11-25.md`). x86-64 C, Rust, Direct3D 11 clear and triangle/frame-loop programs passed; all four ARM64 builds were rejected by CrossOver (`cannot execute`). Five-repeat, 2000-frame comparison of default, D3DMetal, DXMT, DXVK and wined3d on a trivial offscreen workload: D3DMetal's median submit-and-wait was about 1.8 times the others; this is not rendering performance. Observed on one machine, not independently reproduced, using an undocumented backend variable.
- Added `workloads/d3d11-frameloop` (indexed triangle, shaders, event-query frame loop) and negative controls for both Direct3D programs; made workload builds byte-reproducible on one machine with `--no-insert-timestamp`.
- Added `betterxen-hybrid guard`, a memory-pressure supervisor: it refuses to start a command when system-wide free memory is below a threshold and stops it (SIGTERM, then SIGKILL) when memory drops below a limit, reporting why. It is adapted from the memory guard in contributor skakwy's `victory-mac` `mac/run-victory.sh` (GPL-3.0, used with his permission) and reimplemented in Rust. Locally verified with 6 unit tests and three end-to-end runs (refuse, pass-through, stop) on macOS 27.0; the `memory_pressure -Q` output format is not a documented interface; not independently reviewed.
- Added original Windows workloads and a build script (#364, #365): a C and a Rust self-checking console program and a Direct3D 11 clear-and-readback program (`workloads/`), built for x86-64 and ARM64 with a checksum-verified llvm-mingw 20261117 by `scripts/hybrid/build-windows-workloads.sh` (`docs/research/hybrid-toolchain.md`). All six outputs were confirmed as the right PE architecture with `file`. **The x86-64 outputs were later run under CrossOver (see below).**
- Extended `docs/research/upstream-integration-audit.md` with a component-level review of skakwy's `victory-mac`: the reported ~1 FPS is, in his own notes, 1 to 1.9 s per frame of a leaked console-game dump measured by his runtime, so it is not reproducible or adoptable here. His Windows cross-link wrapper failed with Homebrew `llvm@17` and was not integrated; his Metal swizzle and D3DMetal-internals fixes are rejected; game-specific loader patches are rejected.
- Added the `betterxen-hybrid` crate (`crates/hybrid`, no third-party dependencies, native arm64) with `host`, `crossover`, `toolchain`, `frames` and `receipt` commands that print JSON: a host receipt (macOS, chip, memory, core split, whether an x86_64 binary runs under Rosetta, GPU and Metal family), CrossOver discovery limited to `Info.plist` metadata, `lipo -archs` and the documented `BottleDir` and `ManagedBottleDirs` preferences, a Windows cross-compiler probe, and frame-time statistics (nearest-rank percentiles, 1 % and 0.1 % lows, stutter count). Locally verified: 13 unit tests, clippy with warnings denied, and a run on the Apple M4 reference machine, where CrossOver is **not installed** (the report says so) and only Homebrew mingw-w64 x86_64 and i686 compilers were found. CrossOver discovery has been tested on a synthetic bundle only and has never inspected a real CrossOver; nothing launches a program or measures a game. Not independently reviewed (#353, #350, #364, #145).
- Added `docs/research/upstream-integration-audit.md` and registry and reuse-matrix rows for skakwy/victory-mac, MacBox, ScarlettMac, ossover, Whisky and rum (source read through the GitHub API, nothing executed, no code copied). Findings: MacBox and ScarlettMac are GPL-2.0 and game-specific, so they are rejected; the Game Porting Toolkit licence text (a third-party copy of version 4.0) limits use to developing, testing or evaluating games and distribution to non-commercial; contributor-reported frame results (about 1 FPS, then two rendered frames) are recorded as unverified.
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed.
- Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally.
- Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub.
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
### Removed
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
- Replaced our own references to a specific commercial game title (README non-affiliation line, research and integration notes, ignored diagnostics folder names) with generic "commercial title" wording. The ignored folder names are now `diagnostics/title-candidate-*` and `diagnostics/title-check`. Third-party repository names, URLs and code-span paths in research notes are unchanged so their provenance stays accurate. Our own prose references to the upstream project formerly named in the research notes now read "PE-Vulkan project". Added the PortWatch native-macOS research notes. No behavior change.
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
- Removed the contributor avatar section from the README.
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
@@ -20,6 +47,7 @@ remains unsupported.
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
- 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 uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result.
- 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`.
@@ -33,6 +61,10 @@ remains unsupported.
- 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
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
@@ -40,6 +72,27 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
- Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification.
- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run.
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
only; nothing was optimized.
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
`upload` and its callers are unchanged. Not yet independently accepted.
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
@@ -49,7 +102,7 @@ remains unsupported.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+6 -2
View File
@@ -1,6 +1,10 @@
# Contributing to BetterXen
BetterXen is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
BetterXen is hybrid-first Apple Silicon compatibility research built around an externally installed CrossOver, with a preserved but paused independent native implementation. Contributions should improve verified behavior rather than expand untested claims.
## Which work is active
The only active development track is the CrossOver-based hybrid architecture in [docs/roadmap.md](docs/roadmap.md). Planning is progressive: only the current milestone (Phase 1) has open issues; ideas for later phases are parked in the roadmap. Native research is paused, its backlog is closed and indexed in [docs/research/native-issue-archive.md](docs/research/native-issue-archive.md), and the few native issues still open only have assigned contributors with open pull requests. Do not start native work; if hybrid development needs a native component, file a focused hybrid issue. Pick an open issue in the current milestone and check its dependencies first. The engineering rules in `AGENTS.md` permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal (subject to licensing) and allow evaluating DXMT, DXVK, VKD3D-Proton and MoltenVK. CrossOver is proprietary: do not bundle or redistribute any of it, and record the exact versions you test. Before adopting or copying any upstream code, verify its license and provenance and add it to the [upstream registry](docs/research/upstream-registry.md); projects built around leaked or unauthorized game builds are not a source of code. Use the issue templates (hybrid task, bug, research, performance, validation, documentation) and fill in the licensing and provenance section.
## Getting started
@@ -44,7 +48,7 @@ Before incorporating third-party code, verify per-file license compatibility wit
## Pull requests
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
- Describe what changes and why, link the issue you claimed with `Closes #<number>`, state which checks you actually ran, and disclose material AI assistance. Separate unverified work from supported behavior.
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
- Never include secrets, personal paths, credentials or private data in patches or logs.
Generated
+213 -8
View File
@@ -2,6 +2,23 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "betterxen"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
"xenora-shader",
]
[[package]]
name = "betterxen-hybrid"
version = "0.1.0"
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -126,6 +143,24 @@ dependencies = [
"objc2-foundation",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "sha2"
version = "0.10.9"
@@ -137,12 +172,60 @@ dependencies = [
"digest",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -150,16 +233,132 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "betterxen"
name = "victory-shader"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
"xenora-shader",
"thiserror",
"windows",
"windows-sys",
"zlib-rs",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
]
[[package]]
@@ -243,3 +442,9 @@ dependencies = [
[[package]]
name = "xenora-texture"
version = "0.1.0"
[[package]]
name = "zlib-rs"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
+126 -48
View File
@@ -1,62 +1,119 @@
<div align="center">
# BetterXen
BetterXen is a community-maintained continuation. Original Git history, licenses and contributor attribution are retained. See the [project history and migration notes](docs/migration.md) for source attribution and imported issue and pull-request records.
**Hybrid-first Apple Silicon compatibility research built around CrossOver, with preserved independent native ARM64 and Metal research (paused).**
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
[![Native Rust checks](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: Metal](https://img.shields.io/badge/graphics-native%20Metal-8957e5)
![Language: Rust](https://img.shields.io/badge/language-Rust%201.100-dea584?logo=rust&logoColor=white)
![Status: experimental](https://img.shields.io/badge/status-experimental-d29922)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
BetterXen is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
**The paused native implementation described below uses no Wine, CrossOver, Rosetta or Vulkan runtime. The active hybrid direction intends to use CrossOver and Rosetta 2, subject to research and licensing review.**
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
> [!IMPORTANT]
> **Current direction.** BetterXen's only active development track is a CrossOver-based hybrid architecture: CrossOver (installed externally) as the compatibility foundation, with BetterXen providing whatever integration, configuration, diagnostics, benchmarking and optimization research shows is missing. This is the *intended* architecture, **not a verified Xbox compatibility stack**: no Xbox title has been shown to run through it, and CrossOver is not assumed to provide Xbox runtime compatibility. Work is at the research stage (Phase 1). Planning is progressive: only the current phase has open issues. The independent native implementation described below is **preserved but paused indefinitely**. See the [roadmap](docs/roadmap.md), [ADR 0005](docs/adr/0005-crossover-hybrid-direction.md), the [upstream research registry](docs/research/upstream-registry.md) and the [deferred native roadmap](docs/research/native-roadmap.md). The rewritten engineering rules are in [AGENTS.md](AGENTS.md).
BetterXen is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
</div>
BetterXen is a community-maintained, open-source project written primarily in Rust. Its native research implementation (paused) builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend. The host runs as ARM64 code; the x86-64 code being emulated is guest data.
> [!IMPORTANT]
> **BetterXen is experimental.** Verified work is restricted to independently authored synthetic programs and shaders. Authentic Xbox executable loading, system-service compatibility and commercial game execution are **not supported**. Progress is measured by reproducible tests, not by estimated game compatibility percentages. See the [current limitations](#current-limitations).
> [!CAUTION]
> **BetterXen strictly opposes piracy.** BetterXen is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. BetterXen is not affiliated with Microsoft or any other publisher or platform holder.
[![Native Rust checks](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
---
## How it fits together
One guest program travels through three native subsystems. Every stage is checked against an independently derived expectation.
```mermaid
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
flowchart LR
A["Original PE32+<br/>test program"]:::guest --> B["Loader<br/>relocations, TLS, imports"]:::guest
B --> C["x86-64 interpreter<br/>+ ARM64 translator"]:::cpu
C --> D["Typed runtime<br/>services"]:::cpu
D --> E["Guest graphics<br/>commands"]:::gpu
S["Original gfx1030<br/>shader bytes"]:::shader --> T["RDNA 2 decoder<br/>+ validated IR"]:::shader --> U["Metal Shading<br/>Language"]:::shader
E --> M["Native Metal<br/>pipelines"]:::gpu
U --> M
M --> G["Apple Silicon GPU<br/>+ readback"]:::gpu
G --> V{"Matches the<br/>independent<br/>CPU reference?"}:::check
S -.-> R["Independent<br/>CPU reference"]:::check -.-> V
classDef guest fill:#ddf4ff,stroke:#0969da,color:#0a3069
classDef cpu fill:#dafbe1,stroke:#1a7f37,color:#0f5323
classDef shader fill:#fbefff,stroke:#8250df,color:#512a97
classDef gpu fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef check fill:#ffebe9,stroke:#cf222e,color:#82071e
```
Legend: 🟦 guest loading · 🟩 guest CPU and services · 🟪 shader translation · 🟨 native Metal · 🟥 independent verification.
---
## What works today?
## Roadmap
BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
The active plan is the [roadmap](docs/roadmap.md): **Phase 1 — CrossOver Research, Feasibility and Baseline** is the only active phase, and later phases are provisional and will be defined from its findings. The current issues are in the [Phase 1 milestone](https://github.com/MacosPorters/betterxen/milestone/9). The native implementation's six phases and the X1 to X25 capability map are archived in [docs/archive/readme-native-milestones.md](docs/archive/readme-native-milestones.md) and the [native-first plan](docs/archive/development-phases-native-first.md). Native work is paused indefinitely and resumes only after an explicit maintainer decision.
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
### Development milestones
| Milestone | Implementation | Status |
| --- | --- | --- |
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Follow the [BetterXen development phases](docs/development-phases.md) for the current work order and existing issue/PR dependencies. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
---
## Repository at a glance
Counts below come from the generated registries and were read from the repository, not measured on new runs. They describe synthetic fixtures only.
| Area | Where | What exists today |
| --- | --- | --- |
| Guest CPU | `crates/loader` | A generated x86-64 decoder and interpreter, plus a native ARM64 dynamic binary translator (DBT) for a bounded subset. The instruction registry declares 213 operations, 403 forms and 498 opcode slots; 93 operations have at least one form lowered to ARM64 and the rest run through shared interpreter semantics. See the [instruction registry](docs/cpu/instruction-registry.md). |
| Executable loading | `crates/loader` | PE32+ loading, relocations, thread-local storage, import binding and a static inspection report. |
| Runtime services | `crates/loader`, `crates/import-gen` | A typed service registry: 47 declared services (7 implemented, 37 partial, 3 stubs), all exercised through guest dispatch, none independently accepted. See the [registry](docs/runtime/registry.md) and [generated coverage](docs/runtime/services.md). Guest threads run on a deterministic scheduler on one host thread. |
| Shader ISA | `crates/isa`, `crates/decoder`, `crates/shader`, `crates/ref` | The RDNA 2 (gfx1030) instruction snapshot lists 1,465 forms; 189 are decoder-supported, 185 are lowered to Metal Shading Language, and 18 are Metal-verified on fixtures. See the [semantic coverage](docs/shaders/semantic-coverage.md). An independent CPU reference checks GPU output. |
| Metal backend | `crates/metal` | Native compute, blend, indexed-draw, depth and sampled-texture passes, with Metal API and shader validation. |
| Textures | `crates/texture` | Upload, readback, BC1 to BC7 decoding and sampler code. |
| Application | `app`, `crates/ffi` | A Swift macOS app over a versioned C interface: frame loop, interactive input, persistent resources, audio and a sandboxed virtual filesystem, all against synthetic guests. |
| Test and tooling | `tests`, `fuzz`, `benchmarks`, `scripts` | Original guest programs, independent validation, fuzz targets (CPU decode, PE parse, instruction streams, fixtures, reference, runtime services), mutation testing, correctness-gated benchmarks, and audit scripts for claims, status tables and dependency direction. |
The `betterxen` command-line tool provides `info`, `demo`, `inspect <pe>`, `probe --pe <path> --mode static`, `run`, `imports` and `shaders`. Run `cargo run -p betterxen` with no arguments to see its usage.
### Where the numbers stand
Counts come from the repository's generated registries at this revision. They describe synthetic fixtures only and are not compatibility percentages.
```mermaid
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d0d7de','pieTitleTextSize':'16px','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
pie showData title Guest CPU — 213 declared x86-64 operations
"Lowered to ARM64 (at least one native form)" : 93
"Shared interpreter semantics only" : 120
```
```mermaid
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d4a72c','pie3':'#cf222e','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
pie showData title Runtime services — 47 declared, none independently accepted
"Implemented" : 7
"Partial" : 37
"Stub" : 3
```
```mermaid
%%{init: {'theme':'base','themeVariables':{'xyChart':{'plotColorPalette':'#8250df'}}}}%%
xychart-beta
title "gfx1030 instruction forms by stage (1,465 identified)"
x-axis ["Decoder-supported", "Lowered to MSL", "Metal-verified"]
y-axis "Forms" 0 --> 200
bar [189, 185, 18]
```
---
## Native graphics translation
BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
@@ -177,9 +234,9 @@ Implemented and tested functionality includes:
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture-sampling instructions are not yet implemented.**
**Translated texture sampling covers one instruction and one sampler mode.** A guest draw with the translated `image_sample_lz` pixel stage and a point/clamp sampler matched the software reference and hand-derived images on a local Apple M5 Pro run (one-level RGBA8 and an 8×8 BC1 texture). Other image instructions, filtering modes and formats are not implemented, and this is local verification, not independent acceptance.
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
The texture upload and readback paths use authored Metal kernels. They should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
Xbox-specific texture layouts and additional compression formats require further research and validation.
@@ -230,13 +287,22 @@ flowchart TD
L --> M
K --> M
end
classDef guestNode fill:#dafbe1,stroke:#1a7f37,color:#0f5323
classDef shaderNode fill:#fbefff,stroke:#8250df,color:#512a97
classDef metalNode fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef checkNode fill:#ffebe9,stroke:#cf222e,color:#82071e
class A,B,C,D guestNode
class E,F,G,H shaderNode
class I,J,K metalNode
class L,M checkNode
```
BetterXen's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
The native ARM64 dynamic recompiler covers a bounded subset of x86-64 instructions; the rest run through the shared interpreter semantics (see the [CPU coverage map](docs/testing/cpu-coverage.md) once it lands). The project does not provide a complete Xbox operating-system implementation.
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
@@ -254,8 +320,8 @@ The following remain unsupported or incomplete:
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
| Graphics | Translated texture sampling and broader resource binding |
| Textures | Authentic Xbox memory layouts and translated sampling |
| Graphics | Broader translated texture sampling (one instruction and sampler mode exist) and broader resource binding |
| Textures | Authentic Xbox memory layouts and broader translated sampling |
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
@@ -351,9 +417,21 @@ Testing distinguishes between:
Compiling a shader is not equivalent to proving its GPU output is correct.
### Contributing
Contributions are welcome, and several people and coding agents work in this repository at once. To avoid duplicated work:
1. Read every comment on an issue and check for open pull requests that link it.
2. Claim the issue with a plain reply (for example "I'm taking this. Plan: ...") before you edit anything. The earliest live claim wins, and a claim is stale only after about seven days without a pull request.
3. Stay inside the files the issue lists, and put `Closes #<n>` in the pull request description.
4. Sign off every commit (DCO) and use only public documentation and original code. Anyone who has seen leaked or confidential Xbox material must not contribute.
5. Update `CHANGELOG.md` for meaningful changes. Changes to `main` need maintainer review through [CODEOWNERS](.github/CODEOWNERS).
See [CONTRIBUTING.md](CONTRIBUTING.md), [docs/legal.md](docs/legal.md) and the [documentation index](docs/README.md) for the full rules.
### Where the work is heading
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
See the [roadmap](docs/roadmap.md) for the current phase and the [changelog](CHANGELOG.md) for unreleased additions. The paused native implementation's open research items are listed under [current limitations](#current-limitations).
---
@@ -367,6 +445,6 @@ BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, any game publisher or Apple.
---
+4
View File
@@ -15,3 +15,7 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission. The stall detection and memory-settle logic in `crates/hybrid/src/run.rs` follows supervision lessons from the same repository (`mac/PROGRESS.md`, `crates/victory-core/src/notes.rs`) and is reimplemented, not copied.
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
+213 -6
View File
@@ -638,13 +638,65 @@ final class InspectionModel: ObservableObject {
@Published var report = ""
@Published var status: Int32 = Int32(XENORA_OK)
@Published var busy = false
@Published var importing = false
/// Why the last file selection could not be used, shown until the next selection.
@Published var selectionError: String?
/// Called when a window is about to show the read-only file importer, from its
/// button or File > Open Executable…. Each window presents its own importer.
func requestImport() {
selectionError = nil
}
/// Handles the importer's completion. A cancelled picker is not a failure.
func importFinished(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
inspect(url)
case .failure(let error):
if let cocoa = error as? CocoaError, cocoa.code == .userCancelled {
return
}
selectionError = "The selected file could not be opened: \(error.localizedDescription)"
}
}
/// Reads and reports one file off the main thread. Replaceable only for the
/// `--smoke-inspection-order` check.
private let reader: @Sendable (URL) -> (Int32, String)
/// Number of the latest `inspect` call. Only that call may publish a result.
private var latestRequest: UInt64 = 0
/// Reads that have finished, whether their result was published or discarded.
/// `--smoke-inspection-order` waits on it instead of on a fixed delay.
private(set) var finishedReads: UInt64 = 0
init(reader: @escaping @Sendable (URL) -> (Int32, String) = InspectionModel.run) {
self.reader = reader
}
var failed: Bool { !busy && fileName != nil && status != Int32(XENORA_OK) }
func inspect(_ url: URL) {
latestRequest &+= 1
let request = latestRequest
selectionError = nil
fileName = url.lastPathComponent
report = ""
status = Int32(XENORA_OK)
busy = true
let reader = reader
Task {
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
// The read blocks on file I/O (and, in `--smoke-inspection-order`, on
// its gate), so it runs on a Dispatch queue instead of occupying a
// Swift concurrency worker that other tasks may need.
let (newStatus, newReport) = await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
continuation.resume(returning: reader(url))
}
}
finishedReads &+= 1
// A newer selection owns the published state, including `busy`;
// an older read that finishes late is discarded.
guard request == latestRequest else { return }
status = newStatus
report = newReport
busy = false
@@ -685,17 +737,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
/// Opens the file importer of the focused window. Absent when no window can
/// present it, which disables File > Open Executable….
struct OpenExecutableKey: FocusedValueKey {
typealias Value = () -> Void
}
extension FocusedValues {
var openExecutable: OpenExecutableKey.Value? {
get { self[OpenExecutableKey.self] }
set { self[OpenExecutableKey.self] = newValue }
}
}
/// File > Open Executable… (Command-O), routed to the focused window's importer.
struct OpenExecutableCommand: Commands {
@FocusedValue(\.openExecutable) private var openExecutable
var body: some Commands {
CommandGroup(after: .newItem) {
Button("Open Executable…") { openExecutable?() }
.keyboardShortcut("o")
.disabled(openExecutable == nil)
}
}
}
struct InspectorView: View {
@ObservedObject var model: InspectionModel
let openImporter: () -> Void
var body: some View {
Section("Executable inspection (read-only)") {
HStack {
Button("Open Executable…") { model.importing = true }
Button("Open Executable…") { openImporter() }
Text("or drop a file on this window").foregroundStyle(.secondary)
}
if let error = model.selectionError {
Text(error).foregroundStyle(.red)
}
if let name = model.fileName {
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
if model.failed {
Text("Inspection of \(name) failed (status \(model.status)).")
.foregroundStyle(.red)
}
ScrollView {
Text(model.report)
.font(.system(.caption, design: .monospaced))
@@ -716,12 +802,19 @@ struct ContentView: View {
@ObservedObject var model: FrameModel
@ObservedObject var loop: FrameLoopModel
@ObservedObject var inspection = InspectionModel.shared
/// This window's importer. Kept per window so only the window that asked shows it.
@State private var importing = false
private var frame: GuestFrame? { model.frame }
private var running: Bool { model.running }
private func openImporter() {
inspection.requestImport()
importing = true
}
var body: some View {
Form {
InspectorView(model: inspection)
InspectorView(model: inspection, openImporter: openImporter)
Section("Guest display") {
if let image = frame?.image {
Image(decorative: image, scale: 1)
@@ -822,8 +915,8 @@ struct ContentView: View {
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
if case .success(let url) = result { inspection.inspect(url) }
.fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in
inspection.importFinished(result)
}
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first, url.isFileURL else { return false }
@@ -831,6 +924,7 @@ struct ContentView: View {
return true
}
.frame(minWidth: 520, minHeight: 680)
.focusedSceneValue(\.openExecutable, openImporter)
}
}
@@ -841,6 +935,7 @@ struct BetterXenApp: App {
var body: some Scene {
WindowGroup("BetterXen") { ContentView(model: model, loop: loop) }
.commands { OpenExecutableCommand() }
}
}
@@ -1009,6 +1104,118 @@ if CommandLine.arguments.contains("--smoke-frame") {
exit(frame.status == XENORA_OK ? 0 : 1)
}
// `--smoke-inspection-order` checks that only the latest selection publishes an
// inspection result. Files are never read: an injected reader blocks until the check
// releases that file, so the check, not timing, decides which read finishes first.
// It needs no GPU.
if CommandLine.arguments.contains("--smoke-inspection-order") {
final class ReadGates: @unchecked Sendable {
private let lock = NSLock()
private var gates: [String: DispatchSemaphore] = [:]
func gate(_ name: String) -> DispatchSemaphore {
lock.lock()
defer { lock.unlock() }
if let gate = gates[name] { return gate }
let gate = DispatchSemaphore(value: 0)
gates[name] = gate
return gate
}
func release(_ name: String) { gate(name).signal() }
}
let gates = ReadGates()
// "<scenario>-<a|b>-<ok|fail>"; a gate that is never released times out
// instead of hanging, and the check then fails on its own deadline.
let reader: @Sendable (URL) -> (Int32, String) = { url in
let name = url.lastPathComponent
_ = gates.gate(name).wait(timeout: .now() + 10)
let status = name.hasSuffix("-ok") ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT)
return (status, "report \(name)")
}
func file(_ name: String) -> URL { URL(fileURLWithPath: "/nonexistent/\(name)") }
Task { @MainActor in
var failures: [String] = []
// Waits for the model to finish `count` reads. The deadline only bounds the
// check; the order of completions is set by releasing gates.
@MainActor func settle(_ model: InspectionModel, _ count: UInt64, _ label: String) async -> Bool {
let deadline = Date().addingTimeInterval(5)
while model.finishedReads < count {
if Date() > deadline {
failures.append("\(label): read \(count) did not finish")
return false
}
try? await Task.sleep(nanoseconds: 2_000_000)
}
return true
}
@MainActor func expect(_ model: InspectionModel, _ name: String, busy: Bool, report: String, ok: Bool, _ label: String) {
let actual = "file=\(model.fileName ?? "-") busy=\(model.busy) status=\(model.status) report=\(model.report)"
if model.fileName != name || model.busy != busy || model.report != report
|| (model.status == Int32(XENORA_OK)) != ok {
failures.append("\(label): \(actual)")
}
}
// The newer read finishes first; the older one finishes afterwards and must
// change nothing, whatever its outcome.
for (scenario, first, second, ok) in [("s1", "a-ok", "b-ok", true), ("s2", "a-fail", "b-ok", true),
("s3", "a-ok", "b-fail", false)] {
let (older, newer) = ("\(scenario)-\(first)", "\(scenario)-\(second)")
let model = InspectionModel(reader: reader)
model.inspect(file(older))
model.inspect(file(newer))
gates.release(newer)
if await settle(model, 1, "\(older) then \(newer)") {
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "\(newer) finished")
}
gates.release(older)
if await settle(model, 2, "\(older) then \(newer)") {
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "stale \(older) finished")
}
}
// The older read finishes first and must not clear the newer request's busy state.
let model = InspectionModel(reader: reader)
model.inspect(file("s4-a-ok"))
model.inspect(file("s4-b-fail"))
gates.release("s4-a-ok")
if await settle(model, 1, "s4") {
expect(model, "s4-b-fail", busy: true, report: "", ok: true, "stale s4-a-ok finished first")
}
gates.release("s4-b-fail")
if await settle(model, 2, "s4") {
expect(model, "s4-b-fail", busy: false, report: "report s4-b-fail", ok: false, "s4-b-fail finished")
}
for failure in failures { print("smoke-inspection-order: FAILED \(failure)") }
print("smoke-inspection-order: \(failures.isEmpty ? "ok" : "\(failures.count) failed")")
exit(failures.isEmpty ? 0 : 1)
}
dispatchMain()
}
// `--smoke-import-result` checks how a file-importer result reaches the inspector:
// a cancelled picker shows nothing, a failure is shown, and a new selection clears it.
// No file is opened or read.
if CommandLine.arguments.contains("--smoke-import-result") {
let ok = MainActor.assumeIsolated { () -> Bool in
var failures: [String] = []
let model = InspectionModel()
model.importFinished(.failure(CocoaError(.userCancelled)))
if model.selectionError != nil || model.fileName != nil { failures.append("cancel shows a message") }
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
if model.selectionError == nil || model.fileName != nil { failures.append("failure is not shown") }
model.requestImport()
if model.selectionError != nil { failures.append("reopening keeps the old message") }
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
model.inspect(URL(fileURLWithPath: "/nonexistent/import-result-check"))
if model.selectionError != nil || model.fileName != "import-result-check" {
failures.append("a new selection keeps the old message")
}
for failure in failures { print("smoke-import-result: FAILED \(failure)") }
return failures.isEmpty
}
print("smoke-import-result: \(ok ? "ok" : "failed")")
exit(ok ? 0 : 1)
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
+17 -2
View File
@@ -162,10 +162,21 @@ struct BatchResult {
pipelined: Stats,
}
mod startup;
mod startup_report;
fn main() -> Result<(), Box<dyn Error>> {
// Taken before anything else so a fresh startup child can report the time
// from its parent's spawn to `main`.
let entered = SystemTime::now();
let mut args = std::env::args().skip(1).peekable();
match args.peek().map(String::as_str) {
Some("startup") => return startup::run(args.skip(1)),
Some("startup-child") => return startup::child(entered, args.skip(1)),
_ => {}
}
let mut output = PathBuf::from("benchmarks/results");
let mut reps = DEFAULT_REPS;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--output" => {
@@ -179,7 +190,11 @@ fn main() -> Result<(), Box<dyn Error>> {
.map_err(|_| "--reps must be a positive integer")?;
}
"--help" | "-h" => {
println!("usage: xenora-bench [--output DIR] [--reps N]");
println!(
"usage: xenora-bench [--output DIR] [--reps N]\n \
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
[--reps N] [--output DIR]"
);
return Ok(());
}
other => return Err(format!("unknown argument {other}").into()),
+405
View File
@@ -0,0 +1,405 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
//!
//! `xenora-bench startup` checks one manifest fixture against the independent
//! reference, then measures it two ways:
//!
//! - **Fresh process.** It launches its own executable `--processes` times. Each
//! child creates the Metal device and queue, translates the fixture, runs it
//! once with `run_words_profiled`, checks the output and prints one sample line.
//! - **Repeated.** In this process it creates one device, then translates and runs
//! the same fixture `--reps` times. The first run is reported on its own.
//!
//! Every sample must produce the expected words. One wrong output, failed child or
//! unparsable sample line stops the run before anything is written. The
//! numbers describe this host only; two distributions do not explain each other.
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
use crate::startup_report::Report;
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
const DEFAULT_PROCESSES: usize = 30;
const DEFAULT_REPS: usize = 100;
/// A fresh process that has not exited by then is killed and fails the run.
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
pub(crate) const PHASES: [&str; 8] = [
"spawn_to_main",
"device",
"translate",
"library",
"pipeline",
"submit",
"gpu",
"readback",
];
/// One run's phase timings, indexed like [`PHASES`].
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
impl Sample {
fn line(&self) -> String {
let fields: Vec<String> = PHASES
.iter()
.zip(self.0)
.map(|(name, value)| format!("{name}={value:e}"))
.collect();
format!("startup-sample {}", fields.join(" "))
}
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
pub(crate) fn parse(line: &str) -> Result<Self, String> {
let rest = line
.strip_prefix("startup-sample ")
.ok_or("missing startup-sample prefix")?;
let fields: Vec<&str> = rest.split(' ').collect();
if fields.len() != PHASES.len() {
return Err(format!(
"expected {} fields, got {}",
PHASES.len(),
fields.len()
));
}
let mut sample = Self::default();
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
let value = field
.strip_prefix(name)
.and_then(|v| v.strip_prefix('='))
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
if !value.is_finite() || value < 0.0 {
return Err(format!("{name} must be finite and non-negative"));
}
sample.0[i] = value;
}
Ok(sample)
}
}
/// Median, tail and extremes of one phase.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Summary {
pub(crate) n: usize,
pub(crate) min: f64,
pub(crate) median: f64,
pub(crate) p90: f64,
pub(crate) p99: f64,
pub(crate) max: f64,
}
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
if values.is_empty() {
return None;
}
let mut sorted = values.to_vec();
sorted.sort_by(f64::total_cmp);
Some(Summary {
n: sorted.len(),
min: sorted[0],
median: percentile(&sorted, 0.5),
p90: percentile(&sorted, 0.9),
p99: percentile(&sorted, 0.99),
max: sorted[sorted.len() - 1],
})
}
struct Options {
fixture: Option<String>,
words: Option<usize>,
processes: usize,
reps: usize,
output: PathBuf,
}
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
let n: usize = value
.ok_or_else(|| format!("{flag} needs a count"))?
.parse()
.map_err(|_| format!("{flag} must be a positive integer"))?;
if n == 0 {
return Err(format!("{flag} must be at least 1"));
}
Ok(n)
}
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
let mut options = Options {
fixture: None,
words: None,
processes: DEFAULT_PROCESSES,
reps: DEFAULT_REPS,
output: PathBuf::from("artifacts/startup"),
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
"--words" => options.words = Some(count(args.next(), "--words")?),
"--processes" => options.processes = count(args.next(), "--processes")?,
"--reps" => options.reps = count(args.next(), "--reps")?,
"--output" => {
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
}
other => return Err(format!("unknown startup argument {other}")),
}
}
Ok(options)
}
/// The fixture to time and its word count, after the reference agrees with it.
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
let fixture = match &options.fixture {
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
None => fixtures.into_iter().next(),
}
.ok_or("fixture not found in benchmarks/manifest.toml")?;
let code = fs::read(&fixture.path)?;
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
if reference != fixture.expected {
return Err("reference disagrees with hand-derived expected values".into());
}
let words = options
.words
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
Ok((fixture, words))
}
/// Translates and runs the fixture once on `metal`, checking the output.
fn run_once(
metal: &NativeCompute,
fixture: &Fixture,
words: usize,
sample: &mut Sample,
) -> Result<(), Box<dyn Error>> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let start = Instant::now();
let code = fs::read(&fixture.path)?;
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
sample.0[2] = start.elapsed().as_secs_f64();
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|e| e.to_string())?;
if profile.output != expected {
return Err(format!("{} output disagrees with known answers", fixture.name).into());
}
sample.0[3] = profile.library_seconds;
sample.0[4] = profile.pipeline_seconds;
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
sample.0[6] = profile.gpu_seconds;
sample.0[7] = profile.readback_seconds;
Ok(())
}
fn unix_nanos(time: SystemTime) -> u128 {
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
}
/// Entry point of one fresh child process, called first thing in `main`.
///
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
/// time just before it spawned this process.
pub(crate) fn child(
entered: SystemTime,
mut args: impl Iterator<Item = String>,
) -> Result<(), Box<dyn Error>> {
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let mut sample = Sample::default();
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
sample.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut sample)?;
println!("{}", sample.line());
Ok(())
}
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
vec![
"--fixture".into(),
fixture.name.clone(),
"--words".into(),
words.to_string(),
]
}
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
///
/// The child inherits this process's environment on purpose, so its `MTL_*`
/// validation settings are the ones the run's metadata records.
fn spawn_child(
exe: &std::path::Path,
fixture: &Fixture,
words: usize,
) -> Result<(f64, String), Box<dyn Error>> {
let started = Instant::now();
let spawned = unix_nanos(SystemTime::now());
let mut child = Command::new(exe)
.arg("startup-child")
.arg(spawned.to_string())
.args(forwarded(fixture, words))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
// Drain both pipes while waiting, so a child that writes more than a pipe
// buffer (validation logs, for example) cannot block and look like a hang.
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut pipe) = pipe {
let _ = pipe.read_to_string(&mut text);
}
text
})
};
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > CHILD_TIMEOUT {
child.kill()?;
child.wait()?;
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
}
std::thread::sleep(Duration::from_millis(1));
};
let seconds = started.elapsed().as_secs_f64();
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
if !status.success() {
return Err(format!("{status}: {}", stderr.trim()).into());
}
Ok((seconds, stdout))
}
/// Runs both regimes and writes `startup.json` and `report.md`.
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let exe = std::env::current_exe()?;
let mut fresh = Vec::with_capacity(options.processes);
let mut wall = Vec::with_capacity(options.processes);
for i in 0..options.processes {
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
wall.push(seconds);
let line = stdout
.lines()
.find(|l| l.starts_with("startup-sample "))
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
}
let mut first = Sample::default();
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
first.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut first)?;
let mut repeated = Vec::with_capacity(options.reps);
for _ in 0..options.reps {
let mut sample = Sample::default();
run_once(&metal, &fixture, words, &mut sample)?;
repeated.push(sample);
}
let metadata = Metadata::collect(&metal.device_name(), options.reps);
let dir = options
.output
.join(slug(&metadata.device))
.join(&metadata.run_id);
fs::create_dir_all(&dir)?;
fs::write(dir.join("metadata.json"), metadata.to_json())?;
let report = Report {
fixture: &fixture.name,
words,
fresh: &fresh,
wall: &wall,
first: &first,
repeated: &repeated,
};
fs::write(dir.join("startup.json"), report.json())?;
let markdown = report.markdown(&metadata);
fs::write(dir.join("report.md"), &markdown)?;
println!("{markdown}");
println!("Startup results written to {}", dir.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_lines_round_trip() {
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
}
#[test]
fn sample_lines_reject_damaged_input() {
let line = Sample([1.0; PHASES.len()]).line();
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
// Phases out of order are refused even when every name is present.
let swapped = line
.replacen("device=", "TMP=", 1)
.replacen("translate=", "device=", 1)
.replacen("TMP=", "translate=", 1);
assert!(Sample::parse(&swapped).is_err());
}
#[test]
fn summary_uses_interpolated_percentiles() {
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
// 0.99 * 99 = 98.01 between 99 and 100.
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
let s = summarize(&values).unwrap();
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
assert!((s.median - 50.5).abs() < 1e-9);
assert!((s.p90 - 90.1).abs() < 1e-9);
assert!((s.p99 - 99.01).abs() < 1e-9);
assert_eq!(summarize(&[]), None);
let one = summarize(&[3.0]).unwrap();
assert_eq!(
(one.median, one.p90, one.p99, one.max),
(3.0, 3.0, 3.0, 3.0)
);
}
#[test]
fn options_reject_bad_counts_and_flags() {
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
let defaults = parse(&[]).unwrap();
assert_eq!(
(defaults.processes, defaults.reps),
(DEFAULT_PROCESSES, DEFAULT_REPS)
);
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
assert!(parse(&["--processes", "0"]).is_err());
assert!(parse(&["--reps", "-1"]).is_err());
assert!(parse(&["--words"]).is_err());
assert!(parse(&["--fast"]).is_err());
}
}
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! JSON and markdown output of `xenora-bench startup` (#178).
use std::fmt::Write as _;
use crate::startup::{PHASES, Sample, Summary, summarize};
use crate::{Metadata, json_str};
pub(crate) struct Report<'a> {
pub(crate) fixture: &'a str,
pub(crate) words: usize,
pub(crate) fresh: &'a [Sample],
pub(crate) wall: &'a [f64],
pub(crate) first: &'a Sample,
pub(crate) repeated: &'a [Sample],
}
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
samples.iter().map(|s| s.0[phase]).collect()
}
fn summary_json(summary: Option<Summary>) -> String {
summary.map_or_else(
|| "null".to_string(),
|s| {
format!(
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
s.n, s.min, s.median, s.p90, s.p99, s.max
)
},
)
}
impl Report<'_> {
pub(crate) fn json(&self) -> String {
let mut out = format!(
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
json_str(self.fixture),
self.words,
summary_json(summarize(self.wall))
);
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
let _ = writeln!(out, " \"{regime}\": {{");
for (i, phase) in PHASES.iter().enumerate() {
let comma = if i + 1 < PHASES.len() { "," } else { "" };
let summary = if regime == "repeated" && i < 2 {
None
} else {
summarize(&column(samples, i))
};
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
}
out.push_str(" },\n");
}
let first: Vec<String> = PHASES
.iter()
.zip(self.first.0)
.skip(1)
.map(|(p, v)| format!("\"{p}\": {v:e}"))
.collect();
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
// Raw fresh-process samples in launch order, so a cold first process
// (for example an empty Metal shader cache) stays visible.
let rows: Vec<String> = self
.fresh
.iter()
.zip(self.wall)
.map(|(sample, wall)| {
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
format!("[{}, {wall:e}]", phases.join(", "))
})
.collect();
let _ = writeln!(
out,
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
PHASES
.iter()
.map(|p| json_str(p))
.collect::<Vec<_>>()
.join(", "),
rows.join(",\n ")
);
out
}
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
let ms = |v: f64| format!("{:.3}", v * 1e3);
let mut out = format!(
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
self.fixture,
self.words,
metadata.device,
metadata.profile,
metadata.commit,
metadata.api_validation,
metadata.shader_validation,
metadata.power,
metadata.thermal,
self.fresh.len(),
self.repeated.len(),
);
for (i, phase) in PHASES.iter().enumerate() {
let fresh = summarize(&column(self.fresh, i));
let repeated = (i >= 2)
.then(|| summarize(&column(self.repeated, i)))
.flatten();
let cells = |s: Option<Summary>| {
s.map_or_else(
|| "– | – | – | –".to_string(),
|s| {
format!(
"{} | {} | {} | {}",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
)
},
)
};
let first = if i == 0 {
"–".to_string()
} else {
ms(self.first.0[i])
};
let _ = writeln!(
out,
"| `{phase}` | {} | {first} | {} |",
cells(fresh),
cells(repeated)
);
}
if let Some(s) = summarize(self.wall) {
let _ = writeln!(
out,
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
);
}
out
}
}
+120 -17
View File
@@ -2,10 +2,10 @@
use std::error::Error;
use std::ffi::OsString;
use std::fs::{self, File};
use std::fs::{self, File, OpenOptions};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::process::{Child, Command, ExitCode, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -16,6 +16,10 @@ use xenora_loader::{
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
#[path = "startup_report.rs"]
mod startup_report;
use startup_report::{Events, JOURNAL_ERROR_EXIT, Journal, Termination, WATCHDOG_EXIT};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe");
const WALL_LIMIT: Duration = Duration::from_secs(15);
@@ -27,7 +31,7 @@ const TICKET: u64 = 17;
const DRAW_RESULT: u64 = 0x42;
const EXTENT: [usize; 2] = [4, 3];
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]";
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report <path>]";
struct Options {
path: PathBuf,
@@ -35,6 +39,8 @@ struct Options {
worker: bool,
trace: bool,
hud: bool,
report: Option<PathBuf>,
journal: Option<PathBuf>,
}
impl Options {
@@ -42,6 +48,8 @@ impl Options {
let mut args = args.into_iter();
let mut path = None;
let mut max_steps = None;
let mut report = None;
let mut journal = None;
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
while let Some(arg) = args.next() {
match arg.to_str() {
@@ -56,6 +64,16 @@ impl Options {
.ok_or("--max-steps must be in 1..=10000")?,
);
}
Some("--startup-report") if report.is_none() => {
report = Some(PathBuf::from(
args.next().ok_or("missing --startup-report path")?,
));
}
Some("--startup-journal") if journal.is_none() => {
journal = Some(PathBuf::from(
args.next().ok_or("missing worker journal path")?,
));
}
Some("--experimental") if !experimental => experimental = true,
Some("--trace") if !trace => trace = true,
Some("--metal-hud") if !hud => hud = true,
@@ -66,12 +84,17 @@ impl Options {
if !experimental {
return Err("run requires --experimental".into());
}
if (worker && report.is_some()) || (!worker && journal.is_some()) {
return Err("invalid startup report option for this process".into());
}
Ok(Self {
path: path.ok_or("missing --pe path")?,
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
worker,
trace,
hud,
report,
journal,
})
}
}
@@ -85,7 +108,7 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
}
};
let result = if options.worker {
run_worker(&options).map(|()| ExitCode::SUCCESS)
worker_command(&options)
} else {
launch_worker(&options)
};
@@ -99,8 +122,26 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
}
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
let journal = options
.report
.as_ref()
.map(|_| Journal::create())
.transpose()?;
let executable = std::env::current_exe()?;
let destination = options
.report
.as_ref()
.map(|path| {
OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|error| format!("could not create startup report: {error}"))
})
.transpose()?;
let started = Instant::now();
let mut child = Command::new(std::env::current_exe()?)
let mut command = Command::new(executable);
command
.args([
"run",
"--experimental",
@@ -112,29 +153,73 @@ fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
.arg(options.max_steps.to_string())
.arg("--pe")
.arg(&options.path)
.stdin(Stdio::null())
.spawn()?;
.stdin(Stdio::null());
if let Some(journal) = &journal {
command.arg("--startup-journal").arg(journal.path());
}
let termination = command
.spawn()
.and_then(|child| supervise(child, started, WALL_LIMIT));
if let (Some(journal), Some(destination)) = (&journal, destination)
&& let Err(error) = journal.finish(destination, &termination)
{
eprintln!("could not write startup report: {error}");
if matches!(&termination, Ok(Termination::Exited(status)) if status.success()) {
return Ok(ExitCode::FAILURE);
}
}
match termination? {
Termination::Exited(status) => match status.code() {
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
None => Err(format!("worker terminated: {status}").into()),
},
Termination::Deadline => {
Err("experimental worker exceeded its 15 second wall deadline".into())
}
}
}
fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Result<Termination> {
loop {
match child.try_wait() {
Ok(Some(status)) => {
return match status.code() {
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
None => Err(format!("worker terminated: {status}").into()),
};
}
Ok(None) if started.elapsed() < WALL_LIMIT => {
Ok(Some(status)) => return Ok(Termination::Exited(status)),
Ok(None) if started.elapsed() < limit => {
std::thread::sleep(Duration::from_millis(10));
}
status => {
let _ = child.kill();
child.wait()?;
status?;
return Err("experimental worker exceeded its 15 second wall deadline".into());
return Ok(Termination::Deadline);
}
}
}
}
fn worker_command(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
let mut events = match options.journal.as_deref().map(Events::open).transpose() {
Ok(events) => events,
Err(error) => {
eprintln!("could not open startup journal: {error}");
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
}
};
let result = run_worker(options, events.as_mut());
if let Some(events) = events.as_mut() {
if let Err(error) = &result {
events.failure(error.as_ref());
}
if let Some(error) = events.write_error() {
if let Err(error) = result {
eprintln!("run failed: {error}");
}
eprintln!("could not write startup journal: {error}");
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
}
}
result.map(|()| ExitCode::SUCCESS)
}
fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
let valid_metadata =
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
@@ -158,14 +243,14 @@ fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
.ok_or_else(|| rejection.into())
}
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), Box<dyn Error>> {
std::thread::Builder::new()
.name("xenora-deadline".into())
.spawn(|| {
std::thread::sleep(WALL_LIMIT);
// The supervisor also enforces this deadline. The worker retains
// its own deadline if it is invoked directly.
std::process::exit(124);
std::process::exit(i32::from(WATCHDOG_EXIT));
})?;
let fixture = verify_fixture(&options.path)?;
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
@@ -232,6 +317,16 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
imports,
options.max_steps,
|event| {
if let Some(events) = events.as_deref_mut() {
events.stage(match &event {
StartupEvent::Parsed { .. } => "parsed",
StartupEvent::Mapped { .. } => "mapped",
StartupEvent::Relocated { .. } => "relocated",
StartupEvent::ImportsBound { .. } => "imports_bound",
StartupEvent::TlsCompleted { .. } => "tls_completed",
StartupEvent::Entering { .. } => "entry",
});
}
if options.trace {
trace_startup(event);
}
@@ -244,6 +339,11 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
.take();
let exit = startup.execution.exit_reason;
let rax = startup.execution.final_state.get(Register::Rax);
if exit == ExitReason::Halt
&& let Some(events) = events.as_deref_mut()
{
events.stage("exit");
}
if options.trace {
println!(
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
@@ -264,6 +364,9 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
return Err("trusted fixture startup or result differs from the expected values".into());
}
let frame = result.ok_or("guest halted without a draw")??;
if let Some(events) = events {
events.stage("framebuffer");
}
if options.trace {
println!(
"trace stage=framebuffer extent={}x{} verified_pixels={}",
+399
View File
@@ -0,0 +1,399 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::fmt::Write as _;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use std::process::ExitStatus;
use std::sync::atomic::{AtomicUsize, Ordering};
pub(super) const WATCHDOG_EXIT: u8 = 124;
pub(super) const JOURNAL_ERROR_EXIT: u8 = 125;
const VERSION: &str = "1";
const RECORD_SEPARATOR: char = '\t';
const MAX_BYTES: usize = 8192;
const MAX_ERROR_BYTES: usize = 2048;
const STAGES: [&str; 8] = [
"parsed",
"mapped",
"relocated",
"imports_bound",
"tls_completed",
"entry",
"exit",
"framebuffer",
];
pub(super) struct Journal(PathBuf);
impl Journal {
pub(super) fn create() -> io::Result<Self> {
static NEXT: AtomicUsize = AtomicUsize::new(0);
loop {
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let directory =
std::env::temp_dir().join(format!("betterxen-startup-{}-{id}", std::process::id()));
match fs::DirBuilder::new().mode(0o700).create(&directory) {
Ok(()) => return Ok(Self(directory)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
pub(super) fn path(&self) -> PathBuf {
self.0.join("events")
}
fn read(&self) -> Report {
let mut bytes = Vec::new();
match File::open(self.path())
.and_then(|file| file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes))
{
Ok(_) => Report::parse(&bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => Report::default(),
Err(_) => Report {
integrity: "unreadable",
..Report::default()
},
}
}
pub(super) fn finish(
&self,
mut destination: File,
termination: &io::Result<Termination>,
) -> io::Result<()> {
destination.write_all(self.read().json(termination).as_bytes())
}
}
impl Drop for Journal {
fn drop(&mut self) {
let _ = fs::remove_file(self.path());
let _ = fs::remove_dir(&self.0);
}
}
pub(super) struct Events(File, Option<io::Error>);
impl Events {
pub(super) fn open(path: &Path) -> io::Result<Self> {
OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map(|file| Self(file, None))
}
pub(super) fn stage(&mut self, stage: &str) {
self.record(format_args!("{VERSION}\t{stage}"));
}
pub(super) fn failure(&mut self, error: &dyn std::error::Error) {
let message = error.to_string();
let end = message.floor_char_boundary(MAX_ERROR_BYTES);
let mut encoded = String::with_capacity(end * 2);
for byte in message[..end].bytes() {
write!(encoded, "{byte:02x}").unwrap();
}
self.record(format_args!(
"{VERSION}\tfailure\t{}\t{encoded}",
u8::from(end < message.len())
));
}
fn record(&mut self, arguments: std::fmt::Arguments<'_>) {
if self.1.is_none() {
self.1 = writeln!(self.0, "{arguments}").err();
}
}
pub(super) fn write_error(&self) -> Option<&io::Error> {
self.1.as_ref()
}
}
pub(super) enum Termination {
Exited(ExitStatus),
Deadline,
}
struct Report {
completed: usize,
error: Option<String>,
error_truncated: bool,
integrity: &'static str,
}
impl Default for Report {
fn default() -> Self {
Self {
completed: 0,
error: None,
error_truncated: false,
integrity: "complete",
}
}
}
impl Report {
fn parse(bytes: &[u8]) -> Self {
let mut report = Self::default();
let bounded = &bytes[..bytes.len().min(MAX_BYTES)];
for line in bounded.split_inclusive(|&byte| byte == b'\n') {
let Some(line) = line.strip_suffix(b"\n") else {
report.integrity = "truncated";
break;
};
if !std::str::from_utf8(line).is_ok_and(|line| report.record(line)) {
report.integrity = "malformed";
break;
}
}
if bytes.len() > MAX_BYTES {
report.integrity = "oversized";
}
report
}
fn record(&mut self, line: &str) -> bool {
let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else {
return false;
};
if self.error.is_some() {
return false;
}
if STAGES.get(self.completed) == Some(&record) {
self.completed += 1;
return true;
}
let Some((truncated, encoded)) = record
.strip_prefix("failure\t")
.and_then(|s| s.split_once('\t'))
else {
return false;
};
if !matches!(truncated, "0" | "1")
|| encoded.len() > MAX_ERROR_BYTES * 2
|| !encoded.len().is_multiple_of(2)
|| !encoded.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return false;
}
let (pairs, _) = encoded.as_bytes().as_chunks::<2>();
let Some(message) = pairs
.iter()
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
.collect::<Option<Vec<_>>>()
.and_then(|bytes| String::from_utf8(bytes).ok())
else {
return false;
};
self.error = Some(message);
self.error_truncated = truncated == "1";
true
}
fn json(&self, termination: &io::Result<Termination>) -> String {
let unwritable = matches!(termination, Ok(Termination::Exited(status))
if status.code() == Some(i32::from(JOURNAL_ERROR_EXIT)));
let integrity = if unwritable {
"unwritable"
} else {
self.integrity
};
let (outcome, status, detail) = match termination {
Ok(Termination::Deadline) => (
"timeout",
None,
Some("worker exceeded the wall deadline".into()),
),
Err(error) => ("unknown", None, Some(error.to_string())),
Ok(Termination::Exited(status)) if status.code() == Some(i32::from(WATCHDOG_EXIT)) => (
"timeout",
Some(status),
Some("worker watchdog expired".into()),
),
Ok(Termination::Exited(status)) if unwritable => (
"unknown",
Some(status),
Some("worker could not write its startup journal".into()),
),
Ok(Termination::Exited(status))
if status.success()
&& self.error.is_none()
&& self.completed == STAGES.len()
&& self.integrity == "complete" =>
{
("verified", Some(status), None)
}
Ok(Termination::Exited(status))
if status.code().is_some() && !status.success() && self.error.is_some() =>
{
("stage_failure", Some(status), None)
}
Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => {
("early_exit", Some(status), Some(status.to_string()))
}
Ok(Termination::Exited(status)) => ("unknown", Some(status), Some(status.to_string())),
};
let stages = &STAGES[..self.completed];
let records = stages
.iter()
.map(|stage| format!(r#"{{"schema_version":{VERSION},"stage":"{stage}"}}"#))
.collect::<Vec<_>>()
.join(",");
let last = json_string(stages.last().copied());
let error = json_string(self.error.as_deref());
let detail = json_string(detail.as_deref());
let code = status
.and_then(|status| status.code())
.map_or("null".into(), |code| code.to_string());
format!(
"{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n",
integrity, self.error_truncated
)
}
}
fn json_string(value: Option<&str>) -> String {
let Some(value) = value else {
return String::from("null");
};
let mut escaped = String::from("\"");
for ch in value.chars() {
match ch {
'"' => escaped.push_str("\\\""),
'\\' => escaped.push_str("\\\\"),
'\0'..='\u{1f}' => write!(escaped, "\\u{:04x}", u32::from(ch)).unwrap(),
_ => escaped.push(ch),
}
}
escaped.push('"');
escaped
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
use std::time::{Duration, Instant};
#[test]
fn journal_write_error_surfaces_in_report() {
use std::os::unix::process::ExitStatusExt;
let journal = Journal::create().unwrap();
fs::write(journal.path(), b"1\tparsed\n").unwrap();
let mut events = Events(File::open(journal.path()).unwrap(), None);
events.stage("mapped");
assert!(events.write_error().is_some());
let status = ExitStatus::from_raw(i32::from(JOURNAL_ERROR_EXIT) << 8);
let result = journal.read().json(&Ok(Termination::Exited(status)));
assert!(
result.contains(r#""record_integrity":"unwritable""#),
"{result}"
);
assert!(
result.contains(r#""last_completed_stage":"parsed""#),
"{result}"
);
}
#[test]
fn terminal_failure_keeps_signal_detail_after_all_stages() {
use std::os::unix::process::ExitStatusExt;
let journal = Journal::create().unwrap();
let mut events = Events::open(&journal.path()).unwrap();
for stage in STAGES {
events.stage(stage);
}
events.failure(&io::Error::other("late error"));
let report = journal.read();
assert_eq!(report.integrity, "complete");
let result = report.json(&Ok(Termination::Exited(ExitStatus::from_raw(15))));
assert!(result.contains(r#""outcome":"unknown""#), "{result}");
assert!(result.contains(r#""error":"late error""#), "{result}");
assert!(result.contains("signal: 15"), "{result}");
}
#[test]
fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() {
for (script, limit, outcome, code) in [
("exit 9", Duration::from_secs(2), "early_exit", "9"),
("exit 124", Duration::from_secs(2), "timeout", "124"),
("kill -TERM $$", Duration::from_secs(2), "unknown", "null"),
(
"exec sleep 5",
Duration::from_millis(250),
"timeout",
"null",
),
] {
let journal = Journal::create().unwrap();
let started = Instant::now();
let child = Command::new("/bin/sh")
.args([
"-c",
&format!("printf '1\\tparsed\\n' > \"$1\"; {script}"),
"worker",
])
.arg(journal.path())
.spawn()
.unwrap();
let termination = super::super::supervise(child, started, limit);
let report = journal.read().json(&termination);
assert!(
report.contains(&format!(r#""outcome":"{outcome}""#)),
"{report}"
);
assert!(
report.contains(&format!(r#""worker_exit_code":{code}"#)),
"{report}"
);
assert!(
report.contains(r#""last_completed_stage":"parsed""#),
"{report}"
);
}
}
#[test]
fn invalid_records_keep_only_the_valid_prefix() {
let mut oversized = b"1\tparsed\n1\tmapped".to_vec();
oversized.resize(MAX_BYTES + 1, b'x');
for (bytes, integrity) in [
(&b"1\tparsed\n1\tmapped"[..], "truncated"),
(&b"1\tparsed\n1\tentry\n1\tmapped\n"[..], "malformed"),
(&b"1\tparsed\n1\tfailure\t0\tqq\n"[..], "malformed"),
(oversized.as_slice(), "oversized"),
] {
let journal = Journal::create().unwrap();
fs::write(journal.path(), bytes).unwrap();
let report = journal.read();
assert_eq!(report.completed, 1);
assert_eq!(report.integrity, integrity);
assert!(report.error.is_none());
}
}
#[test]
fn failure_preserves_original_context_with_bounded_utf8() {
let journal = Journal::create().unwrap();
let mut events = Events::open(&journal.path()).unwrap();
events.stage("parsed");
let message = format!("line\nwith \"quote\" and \\{}", "é".repeat(MAX_ERROR_BYTES));
events.failure(&io::Error::other(&message[..]));
let report = journal.read();
assert_eq!(
report.error.as_deref(),
Some(&message[..message.floor_char_boundary(MAX_ERROR_BYTES)])
);
assert!(report.error_truncated);
let json = report.json(&Ok(Termination::Deadline));
assert!(
json.contains(r#"line\u000awith \"quote\" and \\"#),
"{json}"
);
}
}
+109
View File
@@ -0,0 +1,109 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use std::process::Command;
const STARTUP_STAGES: &[&str] = &[
"parsed",
"mapped",
"relocated",
"imports_bound",
"tls_completed",
"entry",
];
#[test]
fn trusted_fixture_preserves_step_failure() {
let report = run_fixture("1", false);
assert!(report.contains(r#""outcome":"stage_failure""#), "{report}");
assert!(
report.contains(r#""last_completed_stage":"entry""#),
"{report}"
);
assert!(report.contains("step budget exhausted"), "{report}");
assert_stages(&report, STARTUP_STAGES);
assert!(!report.contains(r#""stage":"exit""#), "{report}");
}
#[test]
#[ignore = "requires a native Metal device with Apple family 7 capabilities"]
fn trusted_fixture_reports_verified_progress() {
let report = run_fixture("100", true);
assert!(report.contains(r#""outcome":"verified""#), "{report}");
assert!(
report.contains(r#""last_completed_stage":"framebuffer""#),
"{report}"
);
let stages = [STARTUP_STAGES, &["exit", "framebuffer"]].concat();
assert_stages(&report, &stages);
}
fn run_fixture(steps: &str, success: bool) -> String {
let path = std::env::temp_dir().join(format!(
"betterxen-report-test-{}-{steps}.json",
std::process::id()
));
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let output = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args([
"run",
"--experimental",
"--pe",
fixture,
"--max-steps",
steps,
"--startup-report",
])
.arg(&path)
.output()
.unwrap();
let report = std::fs::read_to_string(&path);
if report.is_ok() {
std::fs::remove_file(&path).unwrap();
}
assert_eq!(output.status.success(), success, "{output:?}, {report:?}");
report.unwrap()
}
fn assert_stages(report: &str, stages: &[&str]) {
assert!(report.contains(r#""schema_version":1"#), "{report}");
let mut remaining = report;
for stage in stages {
remaining = remaining
.split_once(&format!(r#""stage":"{stage}""#))
.unwrap()
.1;
}
}
#[test]
fn existing_report_path_prevents_worker_launch() {
let path = std::env::temp_dir().join(format!(
"betterxen-report-existing-{}.json",
std::process::id()
));
std::fs::write(&path, "previous report").unwrap();
let result = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args([
"run",
"--experimental",
"--pe",
"missing-fixture",
"--startup-report",
])
.arg(&path)
.output()
.unwrap();
let contents = std::fs::read_to_string(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(contents, "previous report");
assert!(!result.status.success());
let stderr = String::from_utf8(result.stderr).unwrap();
assert!(
stderr.contains("could not create startup report"),
"{stderr}"
);
assert!(!stderr.contains("No such file or directory"), "{stderr}");
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "betterxen-hybrid"
description = "Host receipt, CrossOver discovery, frame-time statistics and Windows cross-toolchain probes for the hybrid direction"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[[bin]]
name = "betterxen-hybrid"
path = "src/main.rs"
+13
View File
@@ -0,0 +1,13 @@
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
//! never a guessed value.
use std::process::Command;
pub fn run(program: &str, args: &[&str]) -> Option<String> {
let out = Command::new(program).args(args).output().ok()?;
if !out.status.success() {
return None;
}
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
Some(s)
}
+162
View File
@@ -0,0 +1,162 @@
//! Discover installed CrossOver bundles and read standard bundle metadata.
//!
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
//! interface (#350). The graphics backend of a bottle is deliberately not read.
use crate::cmdutil::run;
use crate::json::Json;
use std::path::{Path, PathBuf};
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
#[derive(Debug, Clone, PartialEq)]
pub struct Install {
pub path: PathBuf,
pub bundle_id: Option<String>,
pub short_version: Option<String>,
pub build_version: Option<String>,
pub executable_archs: Option<Vec<String>>,
pub minimum_macos: Option<String>,
}
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
let mut v = vec![
PathBuf::from("/Applications/CrossOver.app"),
home.join("Applications/CrossOver.app"),
];
if let Some(found) = run(
"/usr/bin/mdfind",
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
) {
for line in found.lines().filter(|l| !l.is_empty()) {
let p = PathBuf::from(line);
if !v.contains(&p) {
v.push(p);
}
}
}
v
}
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
candidates.iter().filter_map(|p| inspect(p)).collect()
}
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
pub fn inspect(app: &Path) -> Option<Install> {
let plist = app.join("Contents/Info.plist");
if !plist.is_file() {
return None;
}
let json = run(
"/usr/bin/plutil",
&["-convert", "json", "-o", "-", plist.to_str()?],
)?;
let exe = crate::host_string(&json, "CFBundleExecutable");
let archs = exe.and_then(|e| {
let p = app.join("Contents/MacOS").join(e);
run("/usr/bin/lipo", &["-archs", p.to_str()?])
.map(|s| s.split_whitespace().map(String::from).collect())
});
Some(Install {
path: app.to_path_buf(),
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
build_version: crate::host_string(&json, "CFBundleVersion"),
executable_archs: archs,
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
})
}
/// A documented CrossOver preference, or None when unset or unreadable.
pub fn preference(key: &str) -> Option<String> {
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
}
impl Install {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("path", Json::str(self.path.display().to_string())),
("bundle_id", Json::opt_str(self.bundle_id.clone())),
("short_version", Json::opt_str(self.short_version.clone())),
("build_version", Json::opt_str(self.build_version.clone())),
(
"executable_archs",
self.executable_archs.as_ref().map_or(Json::Null, |a| {
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
}),
),
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
(
"bundle_id_is_codeweavers_crossover",
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
// A synthetic bundle written by the test: it proves the metadata path, not that
// any real CrossOver build has this layout.
fn fake_bundle(dir: &Path) -> PathBuf {
let app = dir.join("CrossOver.app");
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
fs::write(
app.join("Contents/Info.plist"),
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>CrossOver</string>
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
<key>CFBundleShortVersionString</key><string>99.1.2</string>
<key>CFBundleVersion</key><string>12345</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
</dict></plist>"#,
)
.unwrap();
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
app
}
#[test]
fn reads_bundle_metadata() {
if !cfg!(target_os = "macos") {
return;
}
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp).unwrap();
let app = fake_bundle(&tmp);
let i = inspect(&app).expect("inspect");
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
assert_eq!(i.build_version.as_deref(), Some("12345"));
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
assert!(
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
"{:?}",
i.executable_archs
);
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
fs::remove_dir_all(&tmp).unwrap();
}
#[test]
fn missing_or_plistless_bundle_is_none() {
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
assert!(inspect(&tmp.join("X.app")).is_none());
assert!(inspect(&tmp.join("Nope.app")).is_none());
fs::remove_dir_all(&tmp).unwrap();
}
}
+192
View File
@@ -0,0 +1,192 @@
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
//!
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
//! percentile interval. These definitions are fixed here so reports are comparable; other
//! tools define lows differently (for example as the mean of the worst 1 %).
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct FrameStats {
pub frames: usize,
pub total_ms: f64,
pub mean_ms: f64,
pub avg_fps: f64,
pub min_ms: f64,
pub max_ms: f64,
pub p50_ms: f64,
pub p95_ms: f64,
pub p99_ms: f64,
pub p999_ms: f64,
pub low_1pct_fps: f64,
pub low_01pct_fps: f64,
/// Frames longer than twice the median interval.
pub stutters: usize,
}
#[derive(Debug, PartialEq)]
pub enum FrameError {
Empty,
Invalid { index: usize, value: f64 },
Parse { line: usize, text: String },
}
impl std::fmt::Display for FrameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FrameError::Empty => write!(f, "no frame intervals"),
FrameError::Invalid { index, value } => {
write!(
f,
"frame {index}: interval {value} is not a positive finite number of milliseconds"
)
}
FrameError::Parse { line, text } => {
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
}
}
}
}
impl std::error::Error for FrameError {}
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
let n = sorted.len();
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
sorted[rank.min(n) - 1]
}
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
if intervals_ms.is_empty() {
return Err(FrameError::Empty);
}
for (index, &value) in intervals_ms.iter().enumerate() {
if !value.is_finite() || value <= 0.0 {
return Err(FrameError::Invalid { index, value });
}
}
let mut sorted = intervals_ms.to_vec();
sorted.sort_by(|a, b| a.total_cmp(b));
let total: f64 = intervals_ms.iter().sum();
let n = sorted.len();
let p50 = nearest_rank(&sorted, 50.0);
let p99 = nearest_rank(&sorted, 99.0);
let p999 = nearest_rank(&sorted, 99.9);
Ok(FrameStats {
frames: n,
total_ms: total,
mean_ms: total / n as f64,
avg_fps: n as f64 / (total / 1000.0),
min_ms: sorted[0],
max_ms: sorted[n - 1],
p50_ms: p50,
p95_ms: nearest_rank(&sorted, 95.0),
p99_ms: p99,
p999_ms: p999,
low_1pct_fps: 1000.0 / p99,
low_01pct_fps: 1000.0 / p999,
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
})
}
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
let mut out = Vec::new();
for (i, line) in text.lines().enumerate() {
let t = line.trim();
if t.is_empty() || t.starts_with('#') {
continue;
}
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
line: i + 1,
text: t.to_string(),
})?;
out.push(v);
}
Ok(out)
}
impl FrameStats {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("frames", Json::Num(self.frames as f64)),
("total_ms", Json::Num(self.total_ms)),
("mean_ms", Json::Num(self.mean_ms)),
("avg_fps", Json::Num(self.avg_fps)),
("min_ms", Json::Num(self.min_ms)),
("max_ms", Json::Num(self.max_ms)),
("p50_ms", Json::Num(self.p50_ms)),
("p95_ms", Json::Num(self.p95_ms)),
("p99_ms", Json::Num(self.p99_ms)),
("p999_ms", Json::Num(self.p999_ms)),
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
("percentile_method", Json::str("nearest-rank")),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
// Expected values below are worked out by hand, not produced by analyze().
#[test]
fn known_answer_ten_frames() {
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
let s = analyze(&v).unwrap();
assert_eq!(s.frames, 10);
assert_eq!(s.total_ms, 200.0);
assert_eq!(s.mean_ms, 20.0);
assert_eq!(s.avg_fps, 50.0);
assert_eq!(s.p50_ms, 10.0); // rank 5
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
assert_eq!(s.p99_ms, 100.0);
assert_eq!(s.low_1pct_fps, 10.0);
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
}
#[test]
fn stutter_threshold_is_strict() {
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
assert_eq!(s.stutters, 1);
}
#[test]
fn one_frame_per_second() {
let s = analyze(&[1000.0, 1000.0]).unwrap();
assert_eq!(s.avg_fps, 1.0);
}
#[test]
fn rejects_bad_input() {
assert_eq!(analyze(&[]), Err(FrameError::Empty));
assert!(matches!(
analyze(&[1.0, 0.0]),
Err(FrameError::Invalid { index: 1, .. })
));
assert!(matches!(
analyze(&[f64::NAN]),
Err(FrameError::Invalid { .. })
));
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
}
#[test]
fn parses_text() {
assert_eq!(
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
vec![16.5, 8.0]
);
assert_eq!(
parse_intervals("1\nabc\n"),
Err(FrameError::Parse {
line: 2,
text: "abc".into()
})
);
}
}
+140
View File
@@ -0,0 +1,140 @@
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
//!
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
use crate::cmdutil::run;
use crate::json::Json;
#[derive(Debug, Clone, PartialEq)]
pub struct HostReceipt {
pub macos_version: Option<String>,
pub macos_build: Option<String>,
pub chip: Option<String>,
pub apple_silicon: Option<bool>,
pub memory_bytes: Option<u64>,
pub logical_cpus: Option<u32>,
pub performance_cores: Option<u32>,
pub efficiency_cores: Option<u32>,
/// True only if an x86_64 slice of a system binary actually executed.
pub rosetta_executes_x86_64: Option<bool>,
pub gpu_name: Option<String>,
pub gpu_cores: Option<String>,
pub metal_support: Option<String>,
pub host_arch_of_this_binary: &'static str,
}
fn sysctl(name: &str) -> Option<String> {
run("/usr/sbin/sysctl", &["-n", name])
}
pub fn collect() -> HostReceipt {
let gpu = run(
"/usr/sbin/system_profiler",
&["SPDisplaysDataType", "-json"],
)
.and_then(|j| parse_gpu(&j));
HostReceipt {
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
macos_build: sysctl("kern.osversion"),
chip: sysctl("machdep.cpu.brand_string"),
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
// now; it does not distinguish "not installed" from "disabled".
rosetta_executes_x86_64: Some(
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
),
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
host_arch_of_this_binary: std::env::consts::ARCH,
}
}
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
let model = string_value(json, "sppci_model")?;
Some((
model,
string_value(json, "sppci_cores"),
string_value(json, "spdisplays_mtlgpufamilysupport"),
))
}
fn string_value(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('"')?;
let end = rest.find('"')?;
Some(rest[..end].to_string())
}
impl HostReceipt {
pub fn to_json(&self) -> Json {
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
Json::obj(vec![
("macos_version", Json::opt_str(self.macos_version.clone())),
("macos_build", Json::opt_str(self.macos_build.clone())),
("chip", Json::opt_str(self.chip.clone())),
(
"apple_silicon",
self.apple_silicon.map_or(Json::Null, Json::Bool),
),
(
"memory_bytes",
self.memory_bytes
.map_or(Json::Null, |x| Json::Num(x as f64)),
),
("logical_cpus", n(self.logical_cpus)),
("performance_cores", n(self.performance_cores)),
("efficiency_cores", n(self.efficiency_cores)),
(
"rosetta_executes_x86_64",
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
),
("gpu_name", Json::opt_str(self.gpu_name.clone())),
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
("metal_support", Json::opt_str(self.metal_support.clone())),
(
"receipt_binary_arch",
Json::str(self.host_arch_of_this_binary),
),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_gpu_fixture() {
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
let g = parse_gpu(j).unwrap();
assert_eq!(g.0, "Apple M4");
assert_eq!(g.1.as_deref(), Some("10"));
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
}
#[test]
fn missing_gpu_is_none() {
assert!(parse_gpu("{}").is_none());
}
#[test]
fn collect_runs_on_this_host() {
let r = collect();
if cfg!(target_os = "macos") {
assert!(r.macos_version.is_some());
assert!(r.memory_bytes.unwrap() > 0);
}
assert!(r.to_json().render().contains("receipt_binary_arch"));
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
#[derive(Debug, Clone, PartialEq)]
pub enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
pub fn str(s: impl Into<String>) -> Json {
Json::Str(s.into())
}
pub fn opt_str(s: Option<String>) -> Json {
s.map_or(Json::Null, Json::Str)
}
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
pub fn render(&self) -> String {
let mut out = String::new();
self.write(&mut out, 0);
out.push('\n');
out
}
fn write(&self, out: &mut String, depth: usize) {
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) if n.is_finite() => {
if n.fract() == 0.0 && n.abs() < 1e15 {
out.push_str(&format!("{}", *n as i64));
} else {
out.push_str(&format!("{n}"));
}
}
// JSON has no NaN or infinity; refuse to invent a number.
Json::Num(_) => out.push_str("null"),
Json::Str(s) => escape(s, out),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
pad(out, depth + 1);
item.write(out, depth + 1);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push(']');
}
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (k, v)) in fields.iter().enumerate() {
pad(out, depth + 1);
escape(k, out);
out.push_str(": ");
v.write(out, depth + 1);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
pad(out, depth);
out.push('}');
}
}
}
}
fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes_and_nests() {
let j = Json::obj(vec![
("a", Json::str("q\"\\\n\u{1}")),
(
"b",
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
),
("c", Json::Num(f64::NAN)),
]);
let r = j.render();
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
assert!(r.contains("0.5"));
assert!(r.contains(r#""c": null"#));
}
}
+32
View File
@@ -0,0 +1,32 @@
//! BetterXen hybrid tooling: read-only inspection and measurement helpers around an
//! externally installed CrossOver. Nothing here launches a game or claims compatibility.
pub mod cmdutil;
pub mod crossover;
pub mod frames;
pub mod host;
pub mod json;
pub mod memory;
pub mod run;
pub mod toolchain;
/// Value of a top-level string key in flat JSON produced by `plutil -convert json`.
pub fn host_string(json: &str, key: &str) -> Option<String> {
let needle = format!("\"{key}\"");
let at = json.find(&needle)? + needle.len();
let rest = json[at..]
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
+325
View File
@@ -0,0 +1,325 @@
use betterxen_hybrid::{crossover, frames, host, json::Json, memory, run, toolchain};
use std::path::PathBuf;
use std::process::ExitCode;
const USAGE: &str = "usage: betterxen-hybrid <command>
host host receipt (JSON)
crossover [--app P] CrossOver installs and documented preferences (JSON)
toolchain Windows cross-compilers found on PATH (JSON)
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
run CMD; refuse to start / stop it when free memory is low
run --bottle B [--backend X] [--timeout S] [--stall-timeout S] [--settle-bound S] [--expect TEXT] [--out DIR]
[--min-start-free N] [--min-free N] -- EXE [ARGS...]
run a Windows program through CrossOver; write a JSON record
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
run the program per backend N times; summarise frame times
receipt host + crossover + toolchain in one JSON document";
fn crossover_json(app: Option<PathBuf>) -> Json {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let cands = match app {
Some(p) => vec![p],
None => crossover::candidate_paths(&home),
};
let installs = crossover::discover(&cands);
Json::obj(vec![
("installed", Json::Bool(!installs.is_empty())),
(
"installs",
Json::Arr(installs.iter().map(|i| i.to_json()).collect()),
),
(
"bottle_dir_preference",
Json::opt_str(crossover::preference("BottleDir")),
),
(
"managed_bottle_dirs_preference",
Json::opt_str(crossover::preference("ManagedBottleDirs")),
),
(
"searched",
Json::Arr(
cands
.iter()
.map(|p| Json::str(p.display().to_string()))
.collect(),
),
),
(
"note",
Json::str(
"Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).",
),
),
])
}
fn toolchain_json() -> Json {
let path = std::env::var("PATH").unwrap_or_default();
Json::Arr(
toolchain::probe(&path)
.iter()
.map(|c| c.to_json())
.collect(),
)
}
fn guard(args: &[String]) -> ExitCode {
let mut limits = memory::Limits {
min_start_free: 70,
min_free: 20,
poll: std::time::Duration::from_secs(1),
grace: std::time::Duration::from_secs(10),
};
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args.get(i + 1).and_then(|v| v.parse::<u8>().ok());
match (args[i].as_str(), v) {
("--min-start-free", Some(v)) => limits.min_start_free = v,
("--min-free", Some(v)) => limits.min_free = v,
_ => {
eprintln!("{USAGE}");
return ExitCode::from(2);
}
}
i += 2;
}
let Some(cmd) = args.get(i + 1) else {
eprintln!("{USAGE}");
return ExitCode::from(2);
};
match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) {
memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS,
memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8),
other => {
eprintln!("guard: {other:?}");
ExitCode::from(3)
}
}
}
struct RunArgs {
cfg: run::RunConfig,
backends: Vec<String>,
repeat: u32,
out: Option<PathBuf>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut bottle = None;
let mut backend = None;
let mut backends = Vec::new();
let mut repeat = 1u32;
let mut timeout = 300u64;
let mut stall = None;
let mut settle = 60u64;
let mut expect = None;
let mut out = None;
let (mut min_start, mut min_free) = (50u8, 15u8);
let mut i = 0;
while i < args.len() && args[i] != "--" {
let v = args
.get(i + 1)
.ok_or_else(|| format!("{} needs a value", args[i]))?
.clone();
match args[i].as_str() {
"--bottle" => bottle = Some(v),
"--backend" => backend = Some(v),
"--backends" => backends = v.split(',').map(String::from).collect(),
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
"--expect" => expect = Some(v),
"--out" => out = Some(PathBuf::from(v)),
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
"--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?,
o => return Err(format!("unknown option {o}")),
}
i += 2;
}
let program = args.get(i + 1).ok_or("missing program after --")?.clone();
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
let installs = crossover::discover(&crossover::candidate_paths(&home));
let install = installs.first().ok_or("no CrossOver installation found")?;
let wine = run::wine_path(&install.path);
if !wine.is_file() {
return Err(format!(
"{} not found in this CrossOver build",
wine.display()
));
}
let work = out
.clone()
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs"));
Ok(RunArgs {
cfg: run::RunConfig {
wine,
bottle: bottle.ok_or("--bottle is required")?,
backend,
program,
args: args[i + 2..].to_vec(),
timeout: std::time::Duration::from_secs(timeout),
limits: memory::Limits {
min_start_free: min_start,
min_free,
poll: std::time::Duration::from_millis(250),
grace: std::time::Duration::from_secs(10),
},
expect,
work_dir: work,
stall_timeout: stall.map(std::time::Duration::from_secs),
settle_bound: std::time::Duration::from_secs(settle),
read_free: memory::free_percentage,
},
backends,
repeat,
out,
})
}
fn crossover_build() -> Option<String> {
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
crossover::discover(&crossover::candidate_paths(&home))
.first()
.and_then(|i| {
Some(format!(
"{} ({})",
i.short_version.clone()?,
i.build_version.clone()?
))
})
}
fn save(dir: &std::path::Path, name: &str, j: &Json) {
let _ = std::fs::create_dir_all(dir);
let _ = std::fs::write(dir.join(name), j.render());
}
fn run_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) => a,
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let r = run::execute(&a.cfg, crossover_build());
print!("{}", r.json.render());
if let Some(dir) = &a.out {
save(
dir,
&format!(
"run-{}.json",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
),
&r.json,
);
}
if r.class == run::Class::Passed {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn bench_cmd(args: &[String]) -> ExitCode {
let a = match parse_run_args(args) {
Ok(a) if !a.backends.is_empty() => a,
Ok(_) => {
eprintln!("bench needs --backends\n{USAGE}");
return ExitCode::from(2);
}
Err(e) => {
eprintln!("{e}\n{USAGE}");
return ExitCode::from(2);
}
};
let build = crossover_build();
let mut per_backend = Vec::new();
let mut all_ok = true;
for b in &a.backends {
let mut runs = Vec::new();
for _ in 0..a.repeat {
let mut cfg = a.cfg.clone();
cfg.backend = if b == "default" {
None
} else {
Some(b.clone())
};
let r = run::execute(&cfg, build.clone());
all_ok &= r.class == run::Class::Passed;
runs.push(r.json);
}
per_backend.push(Json::obj(vec![
("backend", Json::str(b.clone())),
("runs", Json::Arr(runs)),
]));
}
let doc = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-bench/0")),
("repeat", Json::Num(a.repeat as f64)),
("host", host::collect().to_json()),
("results", Json::Arr(per_backend)),
]);
print!("{}", doc.render());
if let Some(dir) = &a.out {
save(dir, "bench.json", &doc);
}
if all_ok {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("run") => return run_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("bench") => return bench_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
_ => {}
}
if std::env::args().nth(1).as_deref() == Some("guard") {
return guard(&std::env::args().skip(2).collect::<Vec<_>>());
}
let args: Vec<String> = std::env::args().skip(1).collect();
let result: Result<Json, String> = match args.first().map(String::as_str) {
Some("host") => Ok(host::collect().to_json()),
Some("crossover") => {
let app = match args.get(1).map(String::as_str) {
Some("--app") => args.get(2).map(PathBuf::from),
_ => None,
};
Ok(crossover_json(app))
}
Some("toolchain") => Ok(toolchain_json()),
Some("frames") => match args.get(1) {
None => Err("frames needs a file".into()),
Some(f) => std::fs::read_to_string(f)
.map_err(|e| format!("{f}: {e}"))
.and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string()))
.and_then(|v| frames::analyze(&v).map_err(|e| e.to_string()))
.map(|s| s.to_json()),
},
Some("receipt") => Ok(Json::obj(vec![
("schema", Json::str("betterxen-hybrid-receipt/0")),
("host", host::collect().to_json()),
("crossover", crossover_json(None)),
("windows_cross_compilers", toolchain_json()),
])),
_ => Err(USAGE.into()),
};
match result {
Ok(j) => {
print!("{}", j.render());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("{e}");
ExitCode::from(2)
}
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Memory-pressure supervision of a child process.
//!
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
//! the author's permission): do not start a workload when little memory is free, and stop it
//! when system-wide free memory falls below a limit, because GPU memory is wired under
//! unified memory and a runaway workload can take the whole Mac down. This version is
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
//! stopped. It supervises any command; it contains nothing game-specific.
//!
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
//! stable interface, so an unreadable value is an error, never "assume enough memory".
use crate::cmdutil::run;
use std::process::{Child, Command};
use std::time::{Duration, Instant};
pub fn parse_free_percentage(output: &str) -> Option<u8> {
let line = output
.lines()
.find(|l| l.contains("System-wide memory free percentage"))?;
let digits: String = line
.split(':')
.nth(1)?
.trim()
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
let v: u8 = digits.parse().ok()?;
(v <= 100).then_some(v)
}
pub fn free_percentage() -> Option<u8> {
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Limits {
/// Refuse to start below this percent free.
pub min_start_free: u8,
/// Stop the child when free memory drops below this percent.
pub min_free: u8,
pub poll: Duration,
/// Time between SIGTERM and SIGKILL.
pub grace: Duration,
}
#[derive(Debug, PartialEq)]
pub enum Outcome {
/// The child ran to completion; `None` means it ended by a signal.
Exited(Option<i32>),
RefusedToStart {
free: u8,
need: u8,
},
StoppedLowMemory {
free: u8,
limit: u8,
},
/// Memory could not be read, so no guarantee can be given.
MemoryUnreadable,
SpawnFailed(String),
}
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
let _ = Command::new("/bin/kill")
.args(["-TERM", &child.id().to_string()])
.status();
let t0 = Instant::now();
while t0.elapsed() < grace {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
}
/// Run `program` under `limits`, reading memory through `read_free`.
pub fn supervise(
program: &str,
args: &[String],
limits: Limits,
read_free: &mut dyn FnMut() -> Option<u8>,
) -> Outcome {
match read_free() {
None => return Outcome::MemoryUnreadable,
Some(free) if free < limits.min_start_free => {
return Outcome::RefusedToStart {
free,
need: limits.min_start_free,
};
}
Some(_) => {}
}
let mut child = match Command::new(program).args(args).spawn() {
Ok(c) => c,
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
};
loop {
match child.try_wait() {
Ok(Some(status)) => return Outcome::Exited(status.code()),
Ok(None) => {}
Err(e) => return Outcome::SpawnFailed(e.to_string()),
}
match read_free() {
None => {
terminate(&mut child, limits.grace);
return Outcome::MemoryUnreadable;
}
Some(free) if free < limits.min_free => {
terminate(&mut child, limits.grace);
return Outcome::StoppedLowMemory {
free,
limit: limits.min_free,
};
}
Some(_) => {}
}
std::thread::sleep(limits.poll);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> Limits {
Limits {
min_start_free: 50,
min_free: 20,
poll: Duration::from_millis(20),
grace: Duration::from_millis(500),
}
}
#[test]
fn parses_memory_pressure_output() {
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
assert_eq!(parse_free_percentage(real), Some(71));
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 100%"),
Some(100)
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: 101%"),
None
);
assert_eq!(
parse_free_percentage("System-wide memory free percentage: x"),
None
);
assert_eq!(parse_free_percentage("nothing"), None);
}
#[test]
fn refuses_to_start_when_low() {
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
}
#[test]
fn unreadable_memory_is_an_error() {
assert_eq!(
supervise("/usr/bin/true", &[], limits(), &mut || None),
Outcome::MemoryUnreadable
);
}
#[test]
fn child_exit_code_is_reported() {
let out = supervise(
"/bin/sh",
&["-c".into(), "exit 7".into()],
limits(),
&mut || Some(90),
);
assert_eq!(out, Outcome::Exited(Some(7)));
}
#[test]
fn stops_child_when_memory_drops() {
let mut calls = 0;
let t0 = Instant::now();
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
calls += 1;
Some(if calls < 4 { 90 } else { 10 })
});
assert_eq!(
out,
Outcome::StoppedLowMemory {
free: 10,
limit: 20
}
);
assert!(
t0.elapsed() < Duration::from_secs(10),
"child was not stopped promptly"
);
}
#[test]
fn real_reading_is_available_on_macos() {
if cfg!(target_os = "macos") {
assert!(free_percentage().is_some());
}
}
}
+685
View File
@@ -0,0 +1,685 @@
//! Launch a Windows program through an installed CrossOver, supervise it, and write a
//! structured record of what happened.
//!
//! Interface used: `<CrossOver.app>/Contents/SharedSupport/CrossOver/bin/wine --bottle B EXE`
//! and `.../bin/wineserver -k`. These are **not documented by CodeWeavers** for macOS; they
//! exist in the installed build and answer `--help` (cxbottle, cxstart) as observed on build
//! 26.3.0.39832. Every record therefore carries the CrossOver build and a flag saying the
//! launcher interface is vendor-help-only. The graphics backend is selected through the
//! `CX_GRAPHICS_BACKEND` environment variable, which appears in third-party launch scripts and
//! is likewise undocumented; an unrecognised value was observed to be ignored silently, so a
//!
//! Stall detection and the wait for memory to settle after a stop follow the supervision
//! lessons in skakwy's <https://github.com/skakwy/victory-mac> (`mac/PROGRESS.md`,
//! `mac/run-victory.sh`, `crates/victory-core/src/notes.rs` at commit 22b3f8e45a59; his own
//! work, GPL-3.0, used with his permission): detect a hung run by absence of progress, stop a
//! bottle with `wineserver -k` and its prefix, and do not start the next run until memory has
//! been returned. Reimplemented here; none of his code is copied.
//!
//! A record names the backend *requested* and relies on the workload's own diagnostics
//! (adapter name, backend log lines) to show what actually ran.
use crate::frames;
use crate::json::Json;
use crate::memory;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone)]
pub struct RunConfig {
pub wine: PathBuf,
pub bottle: String,
pub backend: Option<String>,
pub program: String,
pub args: Vec<String>,
pub timeout: Duration,
pub limits: memory::Limits,
/// Text that must appear in stdout for a zero exit to count as a pass.
pub expect: Option<String>,
pub work_dir: PathBuf,
/// Stop the run when neither stdout nor stderr has grown for this long.
pub stall_timeout: Option<Duration>,
/// After a stop, wait at most this long for free memory to return to `min_start_free`.
pub settle_bound: Duration,
/// Free-memory reader; `memory::free_percentage` outside tests.
pub read_free: fn() -> Option<u8>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Class {
Passed,
FailedExit(i32),
MissingExpectedMarker,
TimedOut,
/// No output on stdout or stderr for the stall timeout.
Stalled,
StoppedLowMemory,
RefusedToStart,
/// The Windows loader did not accept the file (for example an ARM64 PE this build cannot run).
CannotExecute,
/// The workload reported that no graphics device could be created.
NoDevice,
MemoryUnreadable,
LaunchFailed,
}
impl Class {
pub fn name(&self) -> String {
match self {
Class::Passed => "passed".into(),
Class::FailedExit(c) => format!("failed_exit_{c}"),
Class::MissingExpectedMarker => "missing_expected_marker".into(),
Class::TimedOut => "timed_out".into(),
Class::Stalled => "stalled".into(),
Class::StoppedLowMemory => "stopped_low_memory".into(),
Class::RefusedToStart => "refused_to_start_low_memory".into(),
Class::CannotExecute => "cannot_execute".into(),
Class::NoDevice => "no_graphics_device".into(),
Class::MemoryUnreadable => "memory_unreadable".into(),
Class::LaunchFailed => "launch_failed".into(),
}
}
}
/// Classify a finished (or stopped) run from observable facts only.
pub fn classify(exit: Option<i32>, stdout: &str, stderr: &str, expect: Option<&str>) -> Class {
if stderr.contains("cannot execute") {
return Class::CannotExecute;
}
if stdout.contains("NO DEVICE") && exit == Some(2) {
return Class::NoDevice;
}
match exit {
Some(0) => match expect {
Some(m) if !stdout.contains(m) => Class::MissingExpectedMarker,
_ => Class::Passed,
},
Some(c) => Class::FailedExit(c),
None => Class::FailedExit(-1),
}
}
/// Known host-environment noise in CrossOver output, reported as diagnostics instead of
/// silently dropped. Returns (kind, line) for each recognised line.
pub fn diagnostics(text: &str) -> Vec<(&'static str, String)> {
let mut out = Vec::new();
for line in text.lines() {
if line.contains("LibClamAV Error") || line.contains("Can't open file or directory") {
out.push(("clamav-database-missing", line.to_string()));
} else if line.starts_with("warn:") && line.contains("DXVK") {
out.push(("dxvk-warning", line.to_string()));
}
}
out
}
/// Which graphics layer announced itself, judged from the workload's stdout and stderr.
pub fn detected_backend(output: &str) -> &'static str {
if output.contains("DXVK:") {
"dxvk"
} else if output.contains("DXMT") || output.contains("D3D_FEATURE_LEVEL_11_1\ninfo: Using") {
"dxmt"
} else if output.contains("adapter=AMD Compatibility Mode") {
"d3dmetal (inferred: Apple-reported adapter identity)"
} else if output.contains("adapter=Apple M") {
"wined3d (inferred: native adapter name, no layer banner)"
} else {
"unknown"
}
}
#[derive(Debug, Default, Clone)]
pub struct Samples {
pub peak_rss_kb: u64,
pub mean_cpu_percent_of_core: f64,
pub min_free_percent: Option<u8>,
pub samples: u32,
}
/// Sum RSS (KB) and CPU % of processes whose command line mentions the CrossOver bundle or the
/// bottle directory. Heuristic: processes not started from those paths are not counted.
fn sample_processes(needles: &[String]) -> (u64, f64) {
let Some(out) = crate::cmdutil::run("/bin/ps", &["-axo", "rss=,pcpu=,command="]) else {
return (0, 0.0);
};
let (mut rss, mut cpu) = (0u64, 0f64);
for l in out.lines() {
if !needles.iter().any(|n| l.contains(n.as_str())) {
continue;
}
let mut it = l.split_whitespace();
rss += it.next().and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
cpu += it.next().and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
}
(rss, cpu)
}
fn thermal() -> Json {
match crate::cmdutil::run("/usr/bin/pmset", &["-g", "therm"]) {
Some(t) => Json::Arr(
t.lines()
.map(|l| Json::str(l.trim()))
.filter(|j| *j != Json::str(""))
.collect(),
),
None => Json::Null,
}
}
pub struct RunRecord {
pub class: Class,
pub duration: Duration,
pub exit: Option<i32>,
pub stdout: String,
pub stderr: String,
pub samples: Samples,
pub json: Json,
}
pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
let t_wall = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let _ = std::fs::create_dir_all(&cfg.work_dir);
let out_path = cfg
.work_dir
.join(format!("stdout-{t_wall}-{}.txt", std::process::id()));
let err_path = cfg
.work_dir
.join(format!("stderr-{t_wall}-{}.txt", std::process::id()));
let mut settle: Option<(Duration, bool)> = None;
let thermal_before = thermal();
let free_start = (cfg.read_free)();
let mut result = RunRecord {
class: Class::LaunchFailed,
duration: Duration::ZERO,
exit: None,
stdout: String::new(),
stderr: String::new(),
samples: Samples::default(),
json: Json::Null,
};
match free_start {
None => result.class = Class::MemoryUnreadable,
Some(f) if f < cfg.limits.min_start_free => result.class = Class::RefusedToStart,
Some(_) => {
let files = std::fs::File::create(&out_path)
.and_then(|o| std::fs::File::create(&err_path).map(|e| (o, e)));
if let Ok((o, e)) = files {
let mut cmd = Command::new(&cfg.wine);
cmd.arg("--bottle")
.arg(&cfg.bottle)
.arg(&cfg.program)
.args(&cfg.args);
cmd.stdout(Stdio::from(o)).stderr(Stdio::from(e));
if let Some(b) = &cfg.backend {
cmd.env("CX_GRAPHICS_BACKEND", b);
}
let started = Instant::now();
if let Ok(mut child) = cmd.spawn() {
let bundle = cfg
.wine
.to_string_lossy()
.split("/Contents/")
.next()
.unwrap_or("")
.to_string();
let needles = vec![bundle, format!("Bottles/{}", cfg.bottle)];
let (mut cpu_sum, mut n) = (0f64, 0u32);
let mut stop: Option<Class> = None;
let mut last_len = 0u64;
let mut last_growth = Instant::now();
loop {
match child.try_wait() {
Ok(Some(st)) => {
result.exit = st.code();
break;
}
Ok(None) => {}
Err(_) => break,
}
let (rss, cpu) = sample_processes(&needles);
result.samples.peak_rss_kb = result.samples.peak_rss_kb.max(rss);
cpu_sum += cpu;
n += 1;
match (cfg.read_free)() {
Some(f) => {
let m = result.samples.min_free_percent.map_or(f, |x| x.min(f));
result.samples.min_free_percent = Some(m);
if f < cfg.limits.min_free {
stop = Some(Class::StoppedLowMemory);
}
}
None => stop = Some(Class::MemoryUnreadable),
}
let len = [&out_path, &err_path]
.iter()
.map(|p| std::fs::metadata(p).map_or(0, |m| m.len()))
.sum::<u64>();
if len != last_len {
last_len = len;
last_growth = Instant::now();
}
if stop.is_none() && started.elapsed() > cfg.timeout {
stop = Some(Class::TimedOut);
}
if stop.is_none()
&& cfg.stall_timeout.is_some_and(|d| last_growth.elapsed() > d)
{
stop = Some(Class::Stalled);
}
if stop.is_some() {
memory::terminate(&mut child, cfg.limits.grace);
stop_bottle(&cfg.wine, &cfg.bottle);
break;
}
std::thread::sleep(cfg.limits.poll);
}
result.duration = started.elapsed();
if stop.is_some() {
let t = Instant::now();
let need = cfg.limits.min_start_free;
let mut recovered = false;
loop {
if (cfg.read_free)().is_some_and(|f| f >= need) {
recovered = true;
break;
}
if t.elapsed() >= cfg.settle_bound {
break;
}
std::thread::sleep(cfg.limits.poll);
}
settle = Some((t.elapsed(), recovered));
}
result.samples.samples = n;
result.samples.mean_cpu_percent_of_core =
if n > 0 { cpu_sum / n as f64 } else { 0.0 };
result.stdout = std::fs::read_to_string(&out_path).unwrap_or_default();
result.stderr = std::fs::read_to_string(&err_path).unwrap_or_default();
result.class = stop.unwrap_or_else(|| {
classify(
result.exit,
&result.stdout,
&result.stderr,
cfg.expect.as_deref(),
)
});
}
}
}
}
let intervals: Vec<f64> = result
.stdout
.lines()
.filter_map(|l| l.strip_prefix("frame_ms "))
.filter_map(|v| v.trim().parse().ok())
.collect();
let frame_stats = frames::analyze(&intervals).ok().map(|s| s.to_json());
let combined = format!("{}\n{}", result.stdout, result.stderr);
let diags: Vec<Json> = diagnostics(&combined)
.into_iter()
.map(|(k, l)| Json::obj(vec![("kind", Json::str(k)), ("line", Json::str(l))]))
.collect();
let tail = |s: &str| -> Json {
let lines: Vec<&str> = s.lines().filter(|l| !l.starts_with("frame_ms ")).collect();
let keep = if lines.len() > 40 {
&lines[lines.len() - 40..]
} else {
&lines[..]
};
Json::Arr(keep.iter().map(|l| Json::str(*l)).collect())
};
result.json = Json::obj(vec![
("schema", Json::str("betterxen-hybrid-run/0")),
("unix_time", Json::Num(t_wall as f64)),
("crossover_build", Json::opt_str(crossover_build)),
(
"launcher_interface",
Json::str(
"CrossOver bin/wine --bottle (vendor --help only; not documented by CodeWeavers for macOS)",
),
),
("bottle", Json::str(cfg.bottle.clone())),
("backend_requested", Json::opt_str(cfg.backend.clone())),
("backend_variable_documented", Json::Bool(false)),
("backend_detected", Json::str(detected_backend(&combined))),
("program", Json::str(cfg.program.clone())),
(
"args",
Json::Arr(cfg.args.iter().map(|a| Json::str(a.clone())).collect()),
),
("classification", Json::str(result.class.name())),
(
"exit_code",
result.exit.map_or(Json::Null, |c| Json::Num(c as f64)),
),
(
"duration_ms",
Json::Num(result.duration.as_secs_f64() * 1000.0),
),
("timeout_s", Json::Num(cfg.timeout.as_secs_f64())),
(
"stall_timeout_s",
cfg.stall_timeout
.map_or(Json::Null, |d| Json::Num(d.as_secs_f64())),
),
(
"memory_settle_after_stop",
settle.map_or(Json::Null, |(d, ok)| {
Json::obj(vec![
("waited_ms", Json::Num(d.as_secs_f64() * 1000.0)),
("recovered_to_start_threshold", Json::Bool(ok)),
("bound_s", Json::Num(cfg.settle_bound.as_secs_f64())),
])
}),
),
(
"free_memory_percent_at_start",
free_start.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"min_free_memory_percent_during_run",
result
.samples
.min_free_percent
.map_or(Json::Null, |f| Json::Num(f as f64)),
),
(
"peak_crossover_rss_kb_sampled",
Json::Num(result.samples.peak_rss_kb as f64),
),
(
"mean_crossover_cpu_percent_of_one_core_sampled",
Json::Num(result.samples.mean_cpu_percent_of_core),
),
("process_samples", Json::Num(result.samples.samples as f64)),
(
"gpu_utilization",
Json::str("not collected: no unprivileged documented source on this host"),
),
("thermal_before", thermal_before),
("thermal_after", thermal()),
("diagnostics", Json::Arr(diags)),
("frame_stats", frame_stats.unwrap_or(Json::Null)),
("stdout_tail", tail(&result.stdout)),
("stderr_tail", tail(&result.stderr)),
]);
let _ = std::fs::remove_file(&out_path);
let _ = std::fs::remove_file(&err_path);
result
}
/// Prefix directory of a bottle. CrossOver documents `BottleDir` in its preferences; otherwise
/// the default location under Application Support is used.
pub fn bottle_prefix(bottle: &str) -> PathBuf {
let base = crate::crossover::preference("BottleDir")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(std::env::var("HOME").unwrap_or_default())
.join("Library/Application Support/CrossOver/Bottles")
});
base.join(bottle)
}
/// Stop every process of one bottle with `wineserver -k`, selecting the bottle through
/// `WINEPREFIX`. Setting `CX_BOTTLE` instead was tried first and observed NOT to select the
/// bottle: the Windows process kept running after the supervisor reported it stopped.
pub fn stop_bottle(wine: &Path, bottle: &str) {
if let Some(dir) = wine.parent() {
let _ = Command::new(dir.join("wineserver"))
.arg("-k")
.env("WINEPREFIX", bottle_prefix(bottle))
.status();
}
}
pub fn wine_path(app: &Path) -> PathBuf {
app.join("Contents/SharedSupport/CrossOver/bin/wine")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_from_observed_facts() {
assert_eq!(classify(Some(0), "PASS", "", Some("PASS")), Class::Passed);
assert_eq!(
classify(Some(0), "ok", "", Some("PASS")),
Class::MissingExpectedMarker
);
assert_eq!(classify(Some(0), "", "", None), Class::Passed);
assert_eq!(classify(Some(1), "FAIL", "", None), Class::FailedExit(1));
assert_eq!(
classify(Some(2), "NO DEVICE hr=0x1", "", None),
Class::NoDevice
);
assert_eq!(classify(Some(2), "other", "", None), Class::FailedExit(2));
assert_eq!(
classify(
Some(1),
"",
"winewrapper.exe:error: cannot execute L\"a.exe\"",
None
),
Class::CannotExecute
);
}
#[test]
fn recognises_noise_and_backends() {
let d = diagnostics(
"LibClamAV Error: x\nERROR: Can't open file or directory\nwarn: DXVK: No state cache\nfine",
);
assert_eq!(d.len(), 3);
assert_eq!(d[0].0, "clamav-database-missing");
assert!(detected_backend("info: DXVK: cxaddon\nadapter=Apple M4").starts_with("dxvk"));
assert!(detected_backend("adapter=AMD Compatibility Mode").starts_with("d3dmetal"));
assert_eq!(detected_backend("nothing"), "unknown");
}
fn stub(dir: &Path, body: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir).unwrap();
let p = dir.join("wine");
std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
p
}
fn cfg(wine: PathBuf, timeout_ms: u64, tag: &str) -> RunConfig {
RunConfig {
wine,
bottle: "t".into(),
backend: None,
program: "x.exe".into(),
args: vec![],
timeout: Duration::from_millis(timeout_ms),
limits: memory::Limits {
min_start_free: 0,
min_free: 0,
poll: Duration::from_millis(30),
grace: Duration::from_millis(500),
},
expect: Some("PASS".into()),
work_dir: std::env::temp_dir().join(format!("bxrun-{tag}-{}", std::process::id())),
stall_timeout: None,
settle_bound: Duration::from_millis(200),
read_free: memory::free_percentage,
}
}
// These use a stub standing in for the launcher: they prove the supervision and record
// logic, not anything about CrossOver.
#[test]
fn stub_run_records_pass_frames_and_env() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub1-{}", std::process::id()));
let w = stub(
&dir,
"echo \"backend=$CX_GRAPHICS_BACKEND\"; echo 'frame_ms 10'; echo 'frame_ms 20'; echo PASS",
);
let mut c = cfg(w, 10_000, "a");
c.backend = Some("dxmt".into());
let r = execute(&c, Some("test".into()));
assert_eq!(r.class, Class::Passed);
let j = r.json.render();
assert!(j.contains("\"frames\": 2"), "{j}");
assert!(j.contains("backend=dxmt"), "{j}");
assert!(j.contains("\"backend_requested\": \"dxmt\""));
assert!(
!j.contains("frame_ms 10"),
"frame lines belong in frame_stats, not the tail"
);
}
#[test]
fn stub_run_times_out_and_is_stopped() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub2-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let t0 = Instant::now();
let r = execute(&cfg(w, 300, "b"), None);
assert_eq!(r.class, Class::TimedOut);
assert!(t0.elapsed() < Duration::from_secs(10));
}
#[test]
fn stub_failure_is_classified_with_exit_code() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stub3-{}", std::process::id()));
let w = stub(&dir, "echo FAIL; exit 3");
assert_eq!(
execute(&cfg(w, 10_000, "c"), None).class,
Class::FailedExit(3)
);
}
#[test]
fn silent_workload_is_stopped_as_stalled_before_the_timeout() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall1-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 20_000, "d");
c.stall_timeout = Some(Duration::from_millis(300));
let t0 = Instant::now();
let r = execute(&c, None);
assert_eq!(r.class, Class::Stalled);
assert!(
t0.elapsed() < Duration::from_secs(5),
"stall must fire long before the 20 s timeout"
);
assert!(r.json.render().contains("\"classification\": \"stalled\""));
}
#[test]
fn workload_that_keeps_printing_is_not_stalled() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall2-{}", std::process::id()));
// Prints every 0.1 s for about 1.2 s: longer than the 0.5 s stall timeout in total.
let w = stub(
&dir,
"i=0; while [ $i -lt 12 ]; do echo tick; i=$((i+1)); sleep 0.1; done; echo PASS",
);
let mut c = cfg(w, 20_000, "e");
c.stall_timeout = Some(Duration::from_millis(500));
assert_eq!(execute(&c, None).class, Class::Passed);
}
static FREE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(90);
fn fake_free() -> Option<u8> {
Some(FREE.load(std::sync::atomic::Ordering::SeqCst))
}
// One test owns the shared `FREE` value, so it does not race with the others.
#[test]
fn after_a_stop_the_run_waits_for_memory_to_return() {
use std::sync::atomic::Ordering::SeqCst;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-settle-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 300, "f");
c.read_free = fake_free;
c.limits.min_start_free = 50;
c.limits.min_free = 0; // only the timeout stops the run
c.settle_bound = Duration::from_secs(5);
// Memory drops 100 ms in and returns 900 ms in; the timeout stop happens at about 300 ms.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
std::thread::sleep(Duration::from_millis(800));
FREE.store(90, SeqCst);
});
let r = execute(&c, None);
h.join().unwrap();
assert_eq!(r.class, Class::TimedOut);
let j = r.json.render();
assert!(j.contains("\"recovered_to_start_threshold\": true"), "{j}");
assert!(r.duration >= Duration::from_millis(300));
// Memory never returns: the wait gives up at the bound and says so.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
});
c.settle_bound = Duration::from_millis(400);
let t0 = Instant::now();
let r = execute(&c, None);
h.join().unwrap();
assert!(t0.elapsed() < Duration::from_secs(5));
assert!(
r.json
.render()
.contains("\"recovered_to_start_threshold\": false")
);
FREE.store(90, SeqCst);
}
#[test]
fn stopping_a_bottle_selects_it_through_wineprefix() {
use std::os::unix::fs::PermissionsExt;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stop-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let log = dir.join("wineserver.log");
let ws = dir.join("wineserver");
std::fs::write(
&ws,
format!(
"#!/bin/sh\necho \"args=$* WINEPREFIX=$WINEPREFIX\" > '{}'\n",
log.display()
),
)
.unwrap();
std::fs::set_permissions(&ws, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_bottle(&dir.join("wine"), "my-bottle");
let got = std::fs::read_to_string(&log).unwrap();
assert!(got.contains("args=-k"), "{got}");
assert!(
got.contains("Bottles/my-bottle") || got.contains("/my-bottle"),
"{got}"
);
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Probe Windows cross-compilers for original test programs (issue #364).
//!
//! Reports what is installed and what each compiler targets; it does not install anything.
use crate::cmdutil::run;
use crate::json::Json;
/// (name, kind). Order is the discovery order only, not a preference.
pub const CANDIDATES: &[&str] = &[
"aarch64-w64-mingw32-clang",
"x86_64-w64-mingw32-clang",
"x86_64-w64-mingw32-gcc",
"i686-w64-mingw32-gcc",
];
#[derive(Debug, Clone, PartialEq)]
pub struct Compiler {
pub name: String,
pub path: String,
pub version_line: Option<String>,
pub target_machine: Option<String>,
}
pub fn probe(search_path: &str) -> Vec<Compiler> {
CANDIDATES
.iter()
.filter_map(|name| {
let path = search_path
.split(':')
.map(|d| std::path::Path::new(d).join(name))
.find(|p| p.is_file())?;
let p = path.to_str()?.to_string();
Some(Compiler {
name: name.to_string(),
version_line: run(&p, &["--version"])
.and_then(|s| s.lines().next().map(String::from)),
target_machine: run(&p, &["-dumpmachine"]),
path: p,
})
})
.collect()
}
impl Compiler {
pub fn to_json(&self) -> Json {
Json::obj(vec![
("name", Json::str(self.name.clone())),
("path", Json::str(self.path.clone())),
("version", Json::opt_str(self.version_line.clone())),
("target_machine", Json::opt_str(self.target_machine.clone())),
])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_path_finds_nothing() {
assert!(probe("").is_empty());
assert!(probe("/nonexistent-dir").is_empty());
}
#[test]
fn finds_a_stub_compiler_and_reports_its_output() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let f = dir.join("x86_64-w64-mingw32-gcc");
std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap();
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
let found = probe(dir.to_str().unwrap());
assert_eq!(found.len(), 1);
assert_eq!(
found[0].target_machine.as_deref(),
Some("x86_64-w64-mingw32")
);
assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+4 -2
View File
@@ -14,8 +14,9 @@
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! Report, comparison and percentile tests run in ordinary workspace tests
//! through `tests/dbt_benchmark_report.rs`. The benchmark target itself disables
//! Cargo's test harness. To run its tests directly, 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.
@@ -982,6 +983,7 @@ mod tests {
blocks_compiled: 626,
cache_hits: 0,
cache_misses: 626,
blocks_invalidated: 0,
native_bytes_emitted: 245_168,
dbt_dispatches: 626,
instructions_executed: 10_002,
+33 -10
View File
@@ -633,15 +633,22 @@ impl Arm64Assembler {
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
}
/// 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.
/// Load a full 64-bit constant into Xd with the fewest wide moves.
/// A 32-bit MOVN leaves one low halfword set to 0xFFFF and zero-extends
/// the result into Xd. For other values, select a 64-bit MOVZ or MOVN
/// background and use MOVK for the remaining halfwords.
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();
// With only the top two halfwords zero, a 32-bit MOVN saves one
// instruction when either of the lower halfwords is all ones.
if zeros == 2 && ones != 0 && val >> 32 == 0 {
let index = usize::from(halves[1] != u16::MAX);
let imm16 = u32::from(!halves[index]);
self.emit(0x1280_0000 | ((index as u32) << 21) | (imm16 << 5) | u32::from(xd & 0x1f));
return;
}
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).
@@ -883,12 +890,14 @@ mod tests {
}
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
const IMMEDIATE_EDGES: [u64; 16] = [
const IMMEDIATE_EDGES: [u64; 18] = [
0,
1,
0xffff,
0x1_0000,
0x8000_0000,
0xffff_1234,
0x1234_ffff,
0xffff_ffff,
0x1_0000_0000,
0x1234_0000_0000_0000,
@@ -904,10 +913,13 @@ mod tests {
#[test]
fn immediate_sequences_match_llvm_encodings() {
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
// A64 words from llvm-mc and Apple Clang's integrated assembler.
let cases: &[(u64, &[u32])] = &[
(0, &[0xd2800000]), // movz x0, #0
(u64::MAX, &[0x92800000]), // movn x0, #0
(0xffff_1234, &[0x129db960]), // movn w0, #0xedcb
(0x1234_ffff, &[0x12bdb960]), // movn w0, #0xedcb, lsl #16
(0xffff_ffff, &[0x12800000]), // movn w0, #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
@@ -930,9 +942,16 @@ mod tests {
);
}
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
/// A 32-bit MOVN can write a zero-extended value if its low word's
/// complement fits in a single halfword. Otherwise count the halfwords
/// that differ from either 64-bit initializer's background.
fn shortest_wide_move(value: u64) -> usize {
if let Ok(low) = u32::try_from(value) {
let complement = !low;
if complement <= u32::from(u16::MAX) || complement.trailing_zeros() >= 16 {
return 1;
}
}
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();
@@ -964,9 +983,13 @@ mod tests {
for value in values {
for register in [X0, X9] {
let mut asm = Arm64Assembler::new();
// Seed the destination so a W-register load must clear the high bits.
asm.movn_64(register, 0, 0);
// Assembler offsets count 32-bit instruction words.
let start = asm.current_offset();
asm.load_imm_64(register, value);
assert_eq!(
asm.instructions().len(),
asm.current_offset() - start,
shortest_wide_move(value),
"{value:#x}"
);
+278 -17
View File
@@ -15,7 +15,7 @@ use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment, decode};
use crate::x86_exec;
use crate::x86_table::{FORMS, Op};
use std::collections::HashMap;
use std::{collections::HashMap, sync::Arc};
const MAX_BLOCK_INSTRUCTIONS: usize = 16;
@@ -29,6 +29,9 @@ pub struct DbtMetrics {
pub blocks_compiled: usize,
pub cache_hits: usize,
pub cache_misses: usize,
/// Cached blocks discarded because their guest bytes or executable mappings
/// changed. Each also counts as a cache miss.
pub blocks_invalidated: usize,
pub native_bytes_emitted: usize,
pub dbt_dispatches: usize,
pub instructions_executed: usize,
@@ -37,11 +40,42 @@ pub struct DbtMetrics {
pub service_calls: usize,
}
/// A translated block and its executable-memory generation.
///
/// Guest stores into executable memory (Intel SDM Vol. 3A 11.6), executable
/// mapping changes and another address space invalidate the retained token.
/// An unchanged token takes a constant-time check. After a generation or address
/// space change, bytes and execute permissions are revalidated once before an
/// identical translation may be reused in that generation.
/// Validation occurs at dispatch boundaries: a store into the currently running
/// block's later instructions still needs a separate dispatch-boundary design.
struct CachedBlock {
code: *const u8,
generation: Arc<()>,
start: u64,
source: Box<[u8]>,
}
impl CachedBlock {
fn is_current(&mut self, memory: &GuestMemory) -> bool {
if memory.code_is_current(&self.generation) {
return true;
}
if !self.source.iter().enumerate().all(|(offset, &byte)| {
matches!(memory.fetch_instruction_byte(self.start.wrapping_add(offset as u64)), Ok(current) if current == byte)
}) {
return false;
}
self.generation = memory.code_generation();
true
}
}
/// Dynamic Binary Translator and native execution runtime.
pub struct DbtEngine {
jit: JitMemory,
block_cache: HashMap<u64, *const u8>,
limited_block_cache: HashMap<(u64, usize), *const u8>,
block_cache: HashMap<u64, CachedBlock>,
limited_block_cache: HashMap<(u64, usize), CachedBlock>,
assembler: Arm64Assembler,
/// Decoded instructions that emitted helper calls point into.
decoded_blocks: Vec<Box<[Insn]>>,
@@ -245,26 +279,34 @@ impl DbtEngine {
block_limit: usize,
) -> Result<*const u8, ExitReason> {
if block_limit == MAX_BLOCK_INSTRUCTIONS {
if let Some(&fn_ptr) = self.block_cache.get(&rip) {
self.metrics.cache_hits += 1;
return Ok(fn_ptr);
if let Some(cached) = self.block_cache.get_mut(&rip) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
}
self.metrics.blocks_invalidated += 1;
}
self.metrics.cache_misses += 1;
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
self.block_cache.insert(rip, compiled_ptr);
return Ok(compiled_ptr);
let compiled = self.compile_block(rip, memory, block_limit)?;
let code = compiled.code;
self.block_cache.insert(rip, compiled);
return Ok(code);
}
// Keep budget-limited blocks separate so they cannot shorten a later run.
let key = (rip, block_limit);
if let Some(&fn_ptr) = self.limited_block_cache.get(&key) {
self.metrics.cache_hits += 1;
return Ok(fn_ptr);
if let Some(cached) = self.limited_block_cache.get_mut(&key) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
}
self.metrics.blocks_invalidated += 1;
}
self.metrics.cache_misses += 1;
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
self.limited_block_cache.insert(key, compiled_ptr);
Ok(compiled_ptr)
let compiled = self.compile_block(rip, memory, block_limit)?;
let code = compiled.code;
self.limited_block_cache.insert(key, compiled);
Ok(code)
}
fn compile_block(
@@ -272,7 +314,7 @@ impl DbtEngine {
start_rip: u64,
memory: &GuestMemory,
block_limit: usize,
) -> Result<*const u8, ExitReason> {
) -> Result<CachedBlock, ExitReason> {
// Decode the whole block first: lowering needs to know whether a later
// instruction observes the flags an earlier one produces.
let mut decoded = Vec::with_capacity(block_limit);
@@ -351,8 +393,17 @@ impl DbtEngine {
.map_err(|_| ExitReason::JitCacheExhausted)?;
self.metrics.blocks_compiled += 1;
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
let source = (0..rip.wrapping_sub(start_rip))
.map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset)))
.collect::<Result<Box<[u8]>, _>>()
.map_err(ExitReason::MemoryFault)?;
self.decoded_blocks.push(insns);
Ok(emitted)
Ok(CachedBlock {
code: emitted,
generation: memory.code_generation(),
start: start_rip,
source,
})
}
}
@@ -1569,6 +1620,216 @@ mod tests {
)
}
/// `mov eax, imm32; hlt`, with the immediate at `ENTRY + 1`.
fn mov_eax(imm: u8) -> [u8; 6] {
[0xB8, imm, 0x00, 0x00, 0x00, 0xF4]
}
fn writable_fixture(code: &[u8]) -> (DbtEngine, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
ENTRY,
code.len(),
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.unwrap();
(DbtEngine::new(64 * 1024).unwrap(), memory)
}
fn rax_after_run(engine: &mut DbtEngine, memory: &mut GuestMemory, limit: usize) -> u64 {
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, memory, limit);
assert_eq!(result.exit_reason, ExitReason::Halt);
cpu.get(Register::Rax)
}
#[test]
fn unchanged_code_stays_cached() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(engine.metrics.blocks_compiled, 1);
assert_eq!(engine.metrics.cache_hits, 1);
assert_eq!(engine.metrics.blocks_invalidated, 0);
}
#[test]
fn data_writes_and_allocations_do_not_invalidate_executable_code() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
memory
.map_region(ENTRY + 0x1000, 8, MemoryPermissions::READ_WRITE)
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
for value in 0..64 {
memory.write_u64(ENTRY + 0x1000, value).unwrap();
let allocation = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE)
.unwrap();
assert!(memory.release_virtual_allocation(allocation));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
}
assert_eq!(engine.metrics.blocks_compiled, 1);
assert_eq!(engine.metrics.cache_hits, 64);
assert_eq!(engine.metrics.blocks_invalidated, 0);
}
#[test]
fn cloned_address_spaces_diverge_when_executable_code_changes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
let mut cloned = memory.clone();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
memory.write_u8(ENTRY + 1, 7).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 7);
// A deep clone shares the proven identical executable snapshot. The
// write in the original space must still force retranslation there.
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.cache_hits, 2);
}
#[test]
fn executable_bypass_writes_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
ENTRY,
8,
MemoryPermissions::READ_EXECUTE,
&[0xB8, 1, 0, 0, 0, 0xF4, 0, 0],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert!(memory.write_u32(ENTRY + 1, 9).is_err());
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(engine.metrics.blocks_invalidated, 0);
memory
.write_u64_bypass(ENTRY, u64::from_le_bytes([0xB8, 2, 0, 0, 0, 0xF4, 0, 0]))
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
memory.write_u32_bypass(ENTRY + 1, 3).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 3);
assert_eq!(engine.metrics.blocks_invalidated, 2);
}
#[test]
fn executable_writes_crossing_regions_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, 2, MemoryPermissions::READ_WRITE_EXECUTE, &[0xB8, 1])
.unwrap();
memory
.map_region_with_data(
ENTRY + 2,
4,
MemoryPermissions::READ_WRITE_EXECUTE,
&[0, 0, 0, 0xF4],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
memory.write_u32(ENTRY + 1, 9).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 9);
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn remapped_non_executable_memory_cannot_reuse_a_translation() {
let mut memory = GuestMemory::new();
let base = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE_EXECUTE)
.unwrap();
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let mut cpu = CpuState::new(base, 0);
assert_eq!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::Halt
);
assert!(memory.release_virtual_allocation(base));
assert_eq!(
memory.map_virtual_allocation(base, 4096, MemoryPermissions::READ_WRITE),
Ok(base)
);
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut cpu = CpuState::new(base, 0);
assert!(matches!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::MemoryFault(_)
));
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn repeated_code_rewrites_report_bounded_jit_cache_exhaustion() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
for value in 0..16_384u32 {
memory.write_u32(ENTRY + 1, value).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 16);
if result.exit_reason == ExitReason::JitCacheExhausted {
return;
}
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(cpu.get(Register::Rax), u64::from(value));
}
panic!("rewritten blocks unexpectedly avoided the bounded JIT capacity");
}
#[test]
fn rewritten_code_is_translated_again() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
memory.write_bytes(ENTRY + 1, &[2]).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.blocks_invalidated, 1);
// The new translation is cached in turn.
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
assert_eq!(engine.metrics.blocks_compiled, 2);
}
#[test]
fn rewriting_the_last_byte_of_a_block_is_detected() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
// HLT becomes NOP, so the block now runs off the end of the mapping.
memory.write_bytes(ENTRY + 5, &[0x90]).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 16);
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn budget_limited_block_is_checked_against_current_bytes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
for expected in [1, 3] {
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(cpu.get(Register::Rax), expected);
memory.write_bytes(ENTRY + 1, &[3]).unwrap();
}
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn another_address_space_does_not_reuse_a_block() {
let (mut engine, mut first) = writable_fixture(&mov_eax(1));
let (_, mut second) = writable_fixture(&mov_eax(7));
assert_eq!(rax_after_run(&mut engine, &mut first, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut second, 16), 7);
let mut unmapped = GuestMemory::new();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut unmapped, 16);
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
}
#[test]
fn cached_block_obeys_remaining_budget() {
let code = [
+57 -3
View File
@@ -5,7 +5,7 @@
//! Provides isolated, page-aligned guest virtual memory with permission checking
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
use std::{fmt, ops::Range};
use std::{fmt, ops::Range, sync::Arc};
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
@@ -119,8 +119,13 @@ impl MappedRegion {
}
/// Guest virtual memory address space.
#[derive(Default, Clone)]
#[derive(Default)]
pub struct GuestMemory {
// A retained token identifies a validated executable snapshot. Independent
// address spaces get distinct tokens. A deep clone may share its identical
// snapshot; an executable mutation detaches only the changed address space.
// Cached translations retain tokens, preventing allocator-address reuse.
executable_generation: Arc<()>,
regions: Vec<MappedRegion>,
private_heaps: std::collections::BTreeSet<u64>,
private_heap_serial: u64,
@@ -130,7 +135,32 @@ pub struct GuestMemory {
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
}
impl Clone for GuestMemory {
fn clone(&self) -> Self {
Self {
executable_generation: Arc::clone(&self.executable_generation),
regions: self.regions.clone(),
private_heaps: self.private_heaps.clone(),
private_heap_serial: self.private_heap_serial,
crt_errno: self.crt_errno.clone(),
callback_frames: self.callback_frames.clone(),
}
}
}
impl GuestMemory {
pub(crate) fn code_generation(&self) -> Arc<()> {
Arc::clone(&self.executable_generation)
}
pub(crate) fn code_is_current(&self, generation: &Arc<()>) -> bool {
Arc::ptr_eq(&self.executable_generation, generation)
}
fn invalidate_executable_code(&mut self) {
self.executable_generation = Arc::new(());
}
/// Create a new empty guest address space.
pub fn new() -> Self {
Self::default()
@@ -197,6 +227,9 @@ impl GuestMemory {
allocation,
});
self.regions.sort_by_key(|r| r.base);
if permissions.execute && size != 0 {
self.invalidate_executable_code();
}
Ok(())
}
@@ -256,8 +289,14 @@ impl GuestMemory {
if !self.private_heaps.remove(&heap) {
return false;
}
let executable = self.regions.iter().any(|region| {
region.allocation == AllocationKind::Heap(heap) && region.permissions.execute
});
self.regions
.retain(|region| region.allocation != AllocationKind::Heap(heap));
if executable {
self.invalidate_executable_code();
}
true
}
@@ -377,10 +416,14 @@ impl GuestMemory {
if size < previous {
region.data.shrink_to_fit();
}
let executable = region.permissions.execute;
if destination != base {
region.base = destination;
self.regions.sort_by_key(|region| region.base);
}
if executable && (size != previous || destination != base) {
self.invalidate_executable_code();
}
Ok(destination)
}
@@ -420,7 +463,10 @@ impl GuestMemory {
else {
return false;
};
self.regions.remove(index);
let removed = self.regions.remove(index);
if removed.permissions.execute && !removed.data.is_empty() {
self.invalidate_executable_code();
}
true
}
@@ -510,11 +556,16 @@ impl GuestMemory {
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
let mut executable = false;
for (index, offset, take) in self.resolve(address, src.len(), required)? {
executable |= take != 0 && self.regions[index].permissions.execute;
self.regions[index].data[offset..offset + take]
.copy_from_slice(&src[done..done + take]);
done += take;
}
if executable {
self.invalidate_executable_code();
}
Ok(())
}
@@ -524,6 +575,9 @@ impl GuestMemory {
&& self.regions[index].permissions.write
{
self.regions[index].data[range].copy_from_slice(src);
if !src.is_empty() && self.regions[index].permissions.execute {
self.invalidate_executable_code();
}
return Ok(());
}
self.write_checked(address, src, Some("write"))
+2 -3
View File
@@ -5723,10 +5723,9 @@ fn interpreter_executes_modified_code_after_a_jump() {
assert_eq!(self_modified_result(Engine::Interpreter), wanted);
}
/// Known defect: the DBT keeps running the block it translated before the store.
/// The DBT must not keep running the block it translated before the store (#84).
#[test]
#[ignore = "known defect (#155): the DBT keeps translated blocks after the guest rewrites their code"]
fn defect_dbt_executes_modified_code_after_a_jump() {
fn dbt_executes_modified_code_after_a_jump() {
for engine in [Engine::Dbt, Engine::DbtStepped] {
let wanted = (1, 2, ExitReason::Halt);
assert_eq!(self_modified_result(engine), wanted, "{engine:?}");
@@ -0,0 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Run the benchmark's report, comparison and percentile tests in normal CI.
//! Timing runs remain confined to the standalone benchmark entry point.
#[allow(dead_code)]
#[path = "../benches/dbt_bench.rs"]
mod benchmark;
+1
View File
@@ -33,6 +33,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
"std",
"MTLAllocation",
"MTLArgument",
"MTLBlitCommandEncoder",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
+513 -41
View File
@@ -11,8 +11,9 @@ use std::ptr::NonNull;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::ProtocolObject;
use objc2_metal::{
MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize, MTLStorageMode,
MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder,
MTLCommandQueue, MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLResourceOptions, MTLSize,
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{SamplerError, TextureMetadata};
@@ -100,6 +101,9 @@ impl Rgba8TextureDesc {
pub struct MetalRgba8Texture {
texture: Retained<ProtocolObject<dyn MTLTexture>>,
desc: Rgba8TextureDesc,
/// Shared storage, which `replaceRegion` may write. Private textures are
/// filled only through `upload_staged`.
cpu_writable: bool,
}
impl MetalRgba8Texture {
@@ -108,6 +112,19 @@ impl MetalRgba8Texture {
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
) -> Result<Self, MetalError> {
Self::allocate_with_storage(device, desc, MTLStorageMode::Shared)
}
fn allocate_with_storage(
device: &ProtocolObject<dyn MTLDevice>,
desc: Rgba8TextureDesc,
storage: MTLStorageMode,
) -> Result<Self, MetalError> {
let options = if storage == MTLStorageMode::Private {
MTLResourceOptions::StorageModePrivate
} else {
MTLResourceOptions::StorageModeShared
};
autoreleasepool(|_| {
// SAFETY: Validated non-zero dimensions within MAX_TEXTURE_PIXELS and RGBA8Unorm format.
let descriptor = unsafe {
@@ -124,8 +141,8 @@ impl MetalRgba8Texture {
descriptor.setMipmapLevelCount(desc.mips as usize);
}
}
descriptor.setStorageMode(MTLStorageMode::Shared);
descriptor.setResourceOptions(MTLResourceOptions::StorageModeShared);
descriptor.setStorageMode(storage);
descriptor.setResourceOptions(options);
descriptor.setUsage(MTLTextureUsage::ShaderRead);
let texture = device
@@ -137,51 +154,25 @@ impl MetalRgba8Texture {
)
})?;
Ok(Self { texture, desc })
Ok(Self {
texture,
desc,
cpu_writable: storage == MTLStorageMode::Shared,
})
})
}
/// Upload a single validated mip level into this texture.
///
/// Only Shared-storage textures from `allocate` or `upload` accept CPU writes.
pub fn upload_mip(&self, mip: &Rgba8MipLevel<'_>) -> Result<(), MetalError> {
let (expected_w, expected_h) = self.desc.mip_extent(mip.level)?;
if mip.width != expected_w || mip.height != expected_h {
if !self.cpu_writable {
return Err(MetalError::new(
"mip dimensions",
format!(
"mip level {} expected {}x{}, got {}x{}",
mip.level, expected_w, expected_h, mip.width, mip.height
),
));
}
let tight_pitch = mip
.width
.checked_mul(RGBA8_TEXEL_BYTES)
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
if mip.row_pitch < tight_pitch {
return Err(MetalError::new(
"row pitch",
format!(
"row pitch {} smaller than tight pitch {}",
mip.row_pitch, tight_pitch
),
));
}
let min_bytes = mip
.row_pitch
.checked_mul(mip.height)
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
if mip.bytes.len() < min_bytes {
return Err(MetalError::new(
"mip buffer bounds",
format!(
"buffer length {} is less than required {}",
mip.bytes.len(),
min_bytes
),
"texture storage",
"a Private-storage texture is filled only by upload_staged",
));
}
validate_mip(&self.desc, mip)?;
autoreleasepool(|_| {
let region = MTLRegion {
@@ -227,6 +218,148 @@ impl MetalRgba8Texture {
Ok(texture)
}
/// Allocate a Private-storage RGBA8 texture and fill every mip level through
/// a reused Shared staging buffer that never exceeds `budget`.
///
/// The plan from [`plan_staged_upload`] is built, and every input checked,
/// before any Metal object is created. Each submission copies its rows into
/// the staging buffer, blits them into the texture and waits until the
/// command buffer has completed. Only a `Completed` status lets the buffer be
/// reused; any other status is returned as an error.
pub fn upload_staged(
device: &ProtocolObject<dyn MTLDevice>,
queue: &ProtocolObject<dyn MTLCommandQueue>,
desc: Rgba8TextureDesc,
mips: &[Rgba8MipLevel<'_>],
budget: StagingBudget,
) -> Result<(Self, StagedUploadReport), MetalError> {
let plan = plan_staged_upload(&desc, mips, budget)?;
let staging_len = plan.iter().map(|s| s.staging_bytes).max().unwrap_or(0);
let texture = Self::allocate_with_storage(device, desc, MTLStorageMode::Private)?;
let staging = device
.newBufferWithLength_options(staging_len, MTLResourceOptions::StorageModeShared)
.ok_or_else(|| MetalError::new("newBufferWithLength", "staging allocation failed"))?;
let mut copied = 0;
for submission in &plan {
for copy in &submission.copies {
let mip = mips
.iter()
.find(|mip| mip.level == copy.level)
.ok_or_else(|| MetalError::new("staged upload", "planned level missing"))?;
let tight = mip.width * RGBA8_TEXEL_BYTES;
for row in 0..copy.rows {
let src = &mip.bytes[(copy.first_row + row) * mip.row_pitch..][..tight];
let offset = copy.staging_offset + row * tight;
// SAFETY: The plan keeps offset + tight within staging_len, the
// buffer is Shared and CPU-visible, and the previous submission
// has completed, so the GPU no longer reads these bytes.
unsafe {
let dst = staging.contents().cast::<u8>().as_ptr().add(offset);
std::ptr::copy_nonoverlapping(src.as_ptr(), dst, tight);
}
}
copied += copy.rows * tight;
}
autoreleasepool(|_| texture.encode_staged(queue, &staging, submission))?;
}
let report = StagedUploadReport {
submissions: plan.len(),
peak_staging_bytes: staging_len,
bytes_copied: copied,
};
Ok((texture, report))
}
fn encode_staged(
&self,
queue: &ProtocolObject<dyn MTLCommandQueue>,
staging: &ProtocolObject<dyn MTLBuffer>,
submission: &StagedSubmission,
) -> Result<(), MetalError> {
let command = queue
.commandBuffer()
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
let blit = command
.blitCommandEncoder()
.ok_or_else(|| MetalError::new("blitCommandEncoder", "blit encoder creation failed"))?;
for copy in &submission.copies {
let (width, _) = self.desc.mip_extent(copy.level)?;
let pitch = width * RGBA8_TEXEL_BYTES;
// SAFETY: The plan validated the level, the row range within the mip and
// the staging range within the buffer. The command buffer retains both
// resources, and the caller waits for completion before reusing staging.
unsafe {
blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin(
staging,
copy.staging_offset,
pitch,
pitch * copy.rows,
MTLSize { width, height: copy.rows, depth: 1 },
&self.texture,
0,
copy.level as usize,
MTLOrigin { x: 0, y: copy.first_row, z: 0 },
);
}
}
blit.endEncoding();
command.commit();
command.waitUntilCompleted();
check_completed(&command)
}
/// Copy one mip level back into tightly packed RGBA8 bytes through a blit.
///
/// Works for Shared and Private textures and shares no code with the upload
/// paths, so tests can compare its output with independently built pixels.
pub fn read_back(
&self,
device: &ProtocolObject<dyn MTLDevice>,
queue: &ProtocolObject<dyn MTLCommandQueue>,
level: u32,
) -> Result<Vec<u8>, MetalError> {
let (width, height) = self.desc.mip_extent(level)?;
let pitch = width * RGBA8_TEXEL_BYTES;
let len = pitch * height;
autoreleasepool(|_| {
let buffer = device
.newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
.ok_or_else(|| {
MetalError::new("newBufferWithLength", "readback allocation failed")
})?;
let command = queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "command buffer creation failed")
})?;
let blit = command.blitCommandEncoder().ok_or_else(|| {
MetalError::new("blitCommandEncoder", "blit encoder creation failed")
})?;
// SAFETY: The level is in range, the source region is the whole mip and
// the destination buffer holds exactly pitch * height bytes.
unsafe {
blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage(
&self.texture,
0,
level as usize,
MTLOrigin { x: 0, y: 0, z: 0 },
MTLSize { width, height, depth: 1 },
&buffer,
0,
pitch,
len,
);
}
blit.endEncoding();
command.commit();
command.waitUntilCompleted();
check_completed(&command)?;
// SAFETY: The command buffer completed, so the Shared buffer holds len
// initialized bytes and the GPU no longer writes it.
let bytes =
unsafe { std::slice::from_raw_parts(buffer.contents().cast::<u8>().as_ptr(), len) };
Ok(bytes.to_vec())
})
}
/// Access the underlying native Metal texture protocol object.
#[inline]
pub fn raw(&self) -> &ProtocolObject<dyn MTLTexture> {
@@ -240,6 +373,198 @@ impl MetalRgba8Texture {
}
}
/// Upper bound on the staging bytes one staged upload holds at a time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagingBudget {
max_bytes: usize,
}
impl StagingBudget {
/// A budget of `max_bytes`, which must be a non-zero multiple of the RGBA8
/// texel size so every staged row starts on a texel boundary.
pub fn new(max_bytes: usize) -> Result<Self, MetalError> {
if max_bytes == 0 || !max_bytes.is_multiple_of(RGBA8_TEXEL_BYTES) {
return Err(MetalError::new(
"staging budget",
format!("budget {max_bytes} must be a non-zero multiple of {RGBA8_TEXEL_BYTES}"),
));
}
Ok(Self { max_bytes })
}
/// The largest staging allocation this budget allows.
#[must_use]
pub fn max_bytes(&self) -> usize {
self.max_bytes
}
}
/// One blit of whole rows of one mip level from the staging buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagedCopy {
pub level: u32,
pub first_row: usize,
pub rows: usize,
/// Byte offset of the first row in the staging buffer. Rows are packed tightly.
pub staging_offset: usize,
}
/// The copies that share one staging fill and one command buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StagedSubmission {
pub copies: Vec<StagedCopy>,
/// Staging bytes this submission uses, never more than the budget.
pub staging_bytes: usize,
}
/// What a staged upload did, measured from the executed plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StagedUploadReport {
/// Command buffers committed and completed.
pub submissions: usize,
/// Size of the one staging buffer, the most staging memory held at once.
pub peak_staging_bytes: usize,
/// Texel bytes copied into the texture.
pub bytes_copied: usize,
}
/// Split a full RGBA8 upload into budget-sized submissions of whole rows.
///
/// Every level `0..desc.mips` must appear exactly once, because a Private
/// texture has no defined contents for a level nobody writes. Each mip is
/// checked like [`MetalRgba8Texture::upload_mip`] checks it. The budget must hold
/// at least one row of the widest level. Rows are packed in level order, and a
/// submission closes when the next row would exceed the budget.
pub fn plan_staged_upload(
desc: &Rgba8TextureDesc,
mips: &[Rgba8MipLevel<'_>],
budget: StagingBudget,
) -> Result<Vec<StagedSubmission>, MetalError> {
let mut by_level: Vec<Option<&Rgba8MipLevel<'_>>> = vec![None; desc.mips as usize];
for mip in mips {
validate_mip(desc, mip)?;
let slot = &mut by_level[mip.level as usize];
if slot.is_some() {
return Err(MetalError::new(
"staged upload",
format!("mip level {} appears more than once", mip.level),
));
}
*slot = Some(mip);
}
let mut plan = Vec::new();
let mut current = StagedSubmission {
copies: Vec::new(),
staging_bytes: 0,
};
for (level, mip) in by_level.iter().enumerate() {
let mip = mip.ok_or_else(|| {
MetalError::new("staged upload", format!("mip level {level} is missing"))
})?;
let pitch = mip.width * RGBA8_TEXEL_BYTES;
if pitch > budget.max_bytes {
return Err(MetalError::new(
"staging budget",
format!(
"budget {} is smaller than one {pitch}-byte row of mip level {level}",
budget.max_bytes
),
));
}
let mut row = 0;
while row < mip.height {
let fit = (budget.max_bytes - current.staging_bytes) / pitch;
if fit == 0 {
// Unreachable after the row check above, but an empty submission
// that cannot take one row must never loop.
if current.copies.is_empty() {
return Err(MetalError::new(
"staging budget",
"a row does not fit an empty staging buffer",
));
}
plan.push(std::mem::replace(
&mut current,
StagedSubmission {
copies: Vec::new(),
staging_bytes: 0,
},
));
continue;
}
let rows = fit.min(mip.height - row);
current.copies.push(StagedCopy {
level: mip.level,
first_row: row,
rows,
staging_offset: current.staging_bytes,
});
current.staging_bytes += rows * pitch;
row += rows;
}
}
if !current.copies.is_empty() {
plan.push(current);
}
Ok(plan)
}
fn check_completed(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
let status = command.status();
if status != MTLCommandBufferStatus::Completed {
let detail = command.error().map_or_else(
|| format!("unexpected command status {status:?}"),
|error| error.localizedDescription().to_string(),
);
return Err(MetalError::new("waitUntilCompleted", detail));
}
Ok(())
}
/// Check one mip level against the texture description and return its tight row pitch.
fn validate_mip(desc: &Rgba8TextureDesc, mip: &Rgba8MipLevel<'_>) -> Result<usize, MetalError> {
let (expected_w, expected_h) = desc.mip_extent(mip.level)?;
if mip.width != expected_w || mip.height != expected_h {
return Err(MetalError::new(
"mip dimensions",
format!(
"mip level {} expected {}x{}, got {}x{}",
mip.level, expected_w, expected_h, mip.width, mip.height
),
));
}
let tight_pitch = mip
.width
.checked_mul(RGBA8_TEXEL_BYTES)
.ok_or_else(|| MetalError::new("row pitch", "row pitch overflow"))?;
if mip.row_pitch < tight_pitch {
return Err(MetalError::new(
"row pitch",
format!(
"row pitch {} smaller than tight pitch {}",
mip.row_pitch, tight_pitch
),
));
}
let min_bytes = mip
.row_pitch
.checked_mul(mip.height)
.ok_or_else(|| MetalError::new("mip bytes", "byte length calculation overflow"))?;
if mip.bytes.len() < min_bytes {
return Err(MetalError::new(
"mip buffer bounds",
format!(
"buffer length {} is less than required {}",
mip.bytes.len(),
min_bytes
),
));
}
Ok(tight_pitch)
}
/// Resource binding indices and lifetime conventions for sampling pipelines.
///
/// In the Xenora fixture ABI and translated shader conventions:
@@ -328,3 +653,150 @@ impl BoundSampledTexture {
self.sampler_slot
}
}
#[cfg(test)]
mod tests {
use super::*;
fn copy(level: u32, first_row: usize, rows: usize, staging_offset: usize) -> StagedCopy {
StagedCopy {
level,
first_row,
rows,
staging_offset,
}
}
fn levels<'a>(desc: &Rgba8TextureDesc, bytes: &'a [u8]) -> Vec<Rgba8MipLevel<'a>> {
(0..desc.mips)
.map(|level| {
let (w, h) = desc.mip_extent(level).unwrap();
Rgba8MipLevel::new_packed(level, w, h, &bytes[..w * h * RGBA8_TEXEL_BYTES])
})
.collect()
}
fn plan(desc: Rgba8TextureDesc, budget: usize) -> Vec<StagedSubmission> {
let bytes = vec![0; desc.width * desc.height * RGBA8_TEXEL_BYTES];
plan_staged_upload(
&desc,
&levels(&desc, &bytes),
StagingBudget::new(budget).unwrap(),
)
.unwrap()
}
fn error(desc: Rgba8TextureDesc, mips: &[Rgba8MipLevel<'_>], budget: usize) -> String {
plan_staged_upload(&desc, mips, StagingBudget::new(budget).unwrap())
.unwrap_err()
.to_string()
}
#[test]
fn budget_must_be_a_non_zero_texel_multiple() {
assert!(StagingBudget::new(0).is_err());
assert!(StagingBudget::new(6).is_err());
assert_eq!(StagingBudget::new(8).unwrap().max_bytes(), 8);
}
#[test]
fn rows_split_into_budget_sized_submissions() {
// 8 texels × 4 bytes = 32 bytes per row; a 64-byte budget holds two rows.
let desc = Rgba8TextureDesc::new(8, 4, 1).unwrap();
let plan = plan(desc, 64);
assert_eq!(plan.len(), 2);
assert_eq!(plan[0].copies, [copy(0, 0, 2, 0)]);
assert_eq!(plan[1].copies, [copy(0, 2, 2, 0)]);
assert!(plan.iter().all(|s| s.staging_bytes == 64));
}
#[test]
fn one_submission_packs_every_level_when_it_fits() {
// Levels 8×4, 4×2, 2×1: 128 + 32 + 8 = 168 bytes.
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
let plan = plan(desc, 168);
assert_eq!(plan.len(), 1);
assert_eq!(
plan[0].copies,
[copy(0, 0, 4, 0), copy(1, 0, 2, 128), copy(2, 0, 1, 160)]
);
assert_eq!(plan[0].staging_bytes, 168);
}
#[test]
fn a_submission_closes_when_the_next_row_does_not_fit() {
// A 40-byte budget holds one 32-byte row of level 0, then two 16-byte rows of
// level 1 and the single 8-byte row of level 2 together.
let desc = Rgba8TextureDesc::new(8, 4, 3).unwrap();
let plan = plan(desc, 40);
assert_eq!(plan.len(), 5);
for (row, submission) in plan[..4].iter().enumerate() {
assert_eq!(submission.copies, [copy(0, row, 1, 0)]);
assert_eq!(submission.staging_bytes, 32);
}
assert_eq!(plan[4].copies, [copy(1, 0, 2, 0), copy(2, 0, 1, 32)]);
assert_eq!(plan[4].staging_bytes, 40);
}
#[test]
fn every_row_is_planned_once_within_budget() {
for (w, h, mips) in [(1, 1, 1), (37, 19, 6), (64, 3, 7), (5, 128, 8)] {
let desc = Rgba8TextureDesc::new(w, h, mips).unwrap();
let widest = w * RGBA8_TEXEL_BYTES;
for budget in [
widest,
widest + 4,
3 * widest,
w * h * RGBA8_TEXEL_BYTES * 2,
] {
let mut next_row = vec![0; mips as usize];
for submission in plan(desc, budget) {
assert!(submission.staging_bytes <= budget);
let mut offset = 0;
for c in &submission.copies {
let (mw, _) = desc.mip_extent(c.level).unwrap();
assert_eq!(c.first_row, next_row[c.level as usize]);
assert_eq!(c.staging_offset, offset);
assert!(c.rows > 0);
offset += c.rows * mw * RGBA8_TEXEL_BYTES;
next_row[c.level as usize] += c.rows;
}
assert_eq!(offset, submission.staging_bytes);
}
for level in 0..mips {
assert_eq!(next_row[level as usize], desc.mip_extent(level).unwrap().1);
}
}
}
}
#[test]
fn rejects_partial_and_malformed_uploads_before_planning() {
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
let bytes = vec![0; 8 * 4 * RGBA8_TEXEL_BYTES];
let mips = levels(&desc, &bytes);
let missing = error(desc, &mips[..1], 1024);
assert!(missing.contains("mip level 1 is missing"), "{missing}");
let duplicate = error(desc, &[mips[0], mips[1], mips[1]], 1024);
assert!(duplicate.contains("more than once"), "{duplicate}");
let out_of_range = Rgba8MipLevel::new_packed(2, 2, 1, &bytes[..8]);
let range = error(desc, &[mips[0], mips[1], out_of_range], 1024);
assert!(range.contains("out of bounds"), "{range}");
let wrong_size = Rgba8MipLevel::new_packed(1, 4, 1, &bytes[..16]);
assert!(error(desc, &[mips[0], wrong_size], 1024).contains("expected 4x2"));
let mut short_pitch = mips[0];
short_pitch.row_pitch = 28;
assert!(error(desc, &[short_pitch, mips[1]], 1024).contains("row pitch"));
let short_bytes = Rgba8MipLevel::new_packed(0, 8, 4, &bytes[..127]);
assert!(error(desc, &[short_bytes, mips[1]], 1024).contains("buffer length"));
let small = error(desc, &mips, 28);
assert!(small.contains("smaller than one 32-byte row"), "{small}");
}
}
+161
View File
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_metal::texture_pipeline::{Rgba8TextureDesc, StagingBudget, plan_staged_upload};
use xenora_metal::{MetalRgba8Texture, Rgba8MipLevel};
use xenora_texture::{Bc1Upload, Bc1UploadDesc, TiledBc1};
use super::context;
@@ -133,3 +135,162 @@ fn samples_pitched_bc1_upload_across_mips_and_layers() {
);
println!("checked 33 RGBA8 texels from pitched BC1 subresources");
}
/// Texel bytes chosen so neighbouring texels, rows and levels all differ, built
/// without any Xenora code so the readback has an independent expectation.
fn pattern_texel(level: u32, x: usize, y: usize) -> [u8; 4] {
let level = level as usize;
[
(x * 7 + level * 50) as u8,
(y * 13 + level) as u8,
((x ^ y) * 3) as u8,
(255 - level * 9) as u8,
]
}
fn tight_pattern(level: u32, width: usize, height: usize) -> Vec<u8> {
(0..height)
.flat_map(|y| (0..width).flat_map(move |x| pattern_texel(level, x, y)))
.collect()
}
/// Each row padded by `pad` bytes of 0xEE, which must never reach the texture.
fn padded_pattern(level: u32, width: usize, height: usize, pad: usize) -> Vec<u8> {
let tight = tight_pattern(level, width, height);
tight
.chunks(width * 4)
.flat_map(|row| row.iter().copied().chain(std::iter::repeat_n(0xEE, pad)))
.collect()
}
fn padded_levels(desc: Rgba8TextureDesc, pad: usize) -> Vec<(usize, usize, Vec<u8>)> {
(0..desc.mips)
.map(|level| {
let (w, h) = desc.mip_extent(level).unwrap();
(w, h, padded_pattern(level, w, h, pad))
})
.collect()
}
fn mip_views(levels: &[(usize, usize, Vec<u8>)], pad: usize) -> Vec<Rgba8MipLevel<'_>> {
levels
.iter()
.enumerate()
.map(|(level, (w, h, bytes))| Rgba8MipLevel {
level: level as u32,
width: *w,
height: *h,
row_pitch: w * 4 + pad,
bytes,
})
.collect()
}
#[test]
fn staged_upload_matches_the_source_under_every_budget() {
let gpu = context();
// 37×19 has six levels, down to 1×1, and odd sizes at every level.
let desc = Rgba8TextureDesc::new(37, 19, 6).unwrap();
let pad = 12;
let levels = padded_levels(desc, pad);
let mips = mip_views(&levels, pad);
let total: usize = levels.iter().map(|(w, h, _)| w * h * 4).sum();
let widest_row = 37 * 4;
// One submission, several bands, a single row per band, and a budget that
// leaves a remainder at every level.
for budget in [total, 3 * widest_row, widest_row, widest_row + 4] {
let budget = StagingBudget::new(budget).unwrap();
let plan = plan_staged_upload(&desc, &mips, budget).unwrap();
let (texture, report) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget)
.unwrap();
assert_eq!(report.submissions, plan.len());
assert!(report.peak_staging_bytes <= budget.max_bytes());
assert_eq!(report.bytes_copied, total);
if budget.max_bytes() == total {
assert_eq!(report.submissions, 1);
} else {
assert!(report.submissions > 1);
}
for level in 0..desc.mips {
let (w, h) = desc.mip_extent(level).unwrap();
let actual = texture.read_back(gpu.device(), gpu.queue(), level).unwrap();
assert_eq!(
actual,
tight_pattern(level, w, h),
"budget {} level {level}",
budget.max_bytes()
);
}
}
}
#[test]
fn staged_and_direct_uploads_produce_the_same_texels() {
let gpu = context();
let desc = Rgba8TextureDesc::new(16, 9, 5).unwrap();
let levels = padded_levels(desc, 0);
let mips = mip_views(&levels, 0);
let direct = MetalRgba8Texture::upload(gpu.device(), desc, &mips).unwrap();
let budget = StagingBudget::new(16 * 4 * 2).unwrap();
let (staged, _) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
for level in 0..desc.mips {
let (w, h) = desc.mip_extent(level).unwrap();
let expected = tight_pattern(level, w, h);
assert_eq!(
direct.read_back(gpu.device(), gpu.queue(), level).unwrap(),
expected
);
assert_eq!(
staged.read_back(gpu.device(), gpu.queue(), level).unwrap(),
expected
);
}
}
#[test]
fn staged_upload_handles_a_single_texel() {
let gpu = context();
let desc = Rgba8TextureDesc::new(1, 1, 1).unwrap();
let texel = pattern_texel(0, 0, 0);
let mips = [Rgba8MipLevel::new_packed(0, 1, 1, &texel)];
let budget = StagingBudget::new(4).unwrap();
let (texture, report) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
assert_eq!((report.submissions, report.peak_staging_bytes), (1, 4));
assert_eq!(
texture.read_back(gpu.device(), gpu.queue(), 0).unwrap(),
texel
);
}
#[test]
fn staged_upload_rejects_bad_input_before_touching_the_gpu() {
let gpu = context();
let desc = Rgba8TextureDesc::new(8, 4, 2).unwrap();
let levels = padded_levels(desc, 0);
let mips = mip_views(&levels, 0);
let small = StagingBudget::new(28).unwrap();
let error = MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, small)
.unwrap_err();
assert!(!error.is_capability_unavailable());
assert!(
error.to_string().contains("smaller than one 32-byte row"),
"{error}"
);
let budget = StagingBudget::new(1024).unwrap();
let missing =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips[..1], budget)
.unwrap_err();
assert!(
missing.to_string().contains("mip level 1 is missing"),
"{missing}"
);
// A Private texture refuses CPU writes instead of failing inside Metal.
let (texture, _) =
MetalRgba8Texture::upload_staged(gpu.device(), gpu.queue(), desc, &mips, budget).unwrap();
let refused = texture.upload_mip(&mips[0]).unwrap_err();
assert!(refused.to_string().contains("Private-storage"), "{refused}");
}
+54
View File
@@ -0,0 +1,54 @@
[package]
name = "victory-shader"
description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders. Vendored from skakwy/victory-mac; see UPSTREAM.md."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
publish = false
[dependencies]
thiserror = "2.0.21"
zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] }
[features]
# Host D3D12 pipeline checks (`emit::host`); Windows targets only.
host = ["dep:windows"]
# Debugging switches (emitted-module dumps and the like).
diagnostics = []
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_System_LibraryLoader"] }
windows = { version = "0.62.2", optional = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[target.'cfg(windows)'.dev-dependencies]
windows = { version = "0.62.2", features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D12",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
] }
[lints.rust]
unsafe_op_in_unsafe_fn = "deny"
unused_must_use = "deny"
[lints.clippy]
all = { level = "warn", priority = -1 }
# Same allowances as the upstream workspace (victory-mac Cargo.toml [workspace.lints.clippy]).
type_complexity = "allow"
needless_range_loop = "allow"
chunks_exact_to_as_chunks = "allow"
sliced_string_as_bytes = "allow"
collapsible_match = "allow"
manual_clamp = "allow"
implicit_saturating_sub = "allow"
min_max = "allow"
undocumented_unsafe_blocks = "allow"
+26
View File
@@ -0,0 +1,26 @@
# Upstream provenance: victory-shader
| | |
| --- | --- |
| Source | <https://github.com/skakwy/victory-mac>, directory `crates/victory-shader/` (Cargo.toml and `src/`) |
| Repository head when copied | `22b3f8e45a59` (2026-11-25); the directory's last change is commit `559357432b41` |
| Licence | GPL-3.0 (repository `LICENSE`); workspace manifest declares `GPL-3.0-or-later`, the same as BetterXen. No file in the crate carries a different licence |
| Third-party notice kept in place | `src/gfx10/opcodes.rs`: opcode names generated from Mesa's `aco_opcodes.py` (tag mesa-22.3.0), MIT, Copyright (c) 2018 Valve Corporation; the notice is in the file header |
| Authorization | skakwy and the VIctory-macOS maintainer authorize reuse of their contributions (relayed by the BetterXen maintainer). Other authors' lines are used under the repository's GPL-3.0 |
| Authors (commits touching this directory, from `git shortlog`) | Marvis (33), skakwy (12), fxceless (11), r4. (6), Duff (4), 9hvn9yt2vk-netizen (3), tedin7 (3), DexNom (2), Luiz Neves (2), Saitken91 (2), others; some commits are credited to an AI assistant |
| What it is | Xbox Series shader containers (DXBC with Xbox additions) and precompiled GFX10 (RDNA 2) machine code translated to PC DXIL (SM 6.6): GFX10 decoder and SP3 printer, control-flow structurizer, IR, register spilling, wave emulation, fp64 by integer operations, an own LLVM 3.7 bitcode writer and container signing |
| Upstream commit-level history | Not carried; see the upstream repository. This directory is a snapshot, so later upstream fixes must be merged by comparing with the pinned commit |
## Modifications made by BetterXen
Changes to upstream files (19 lines, nothing functional) and files BetterXen added (marked `BetterXen addition`, GPL-3.0-or-later): `src/emit/betterxen.rs` (a public `translate_native` for raw compute programs, same stages as `translate`) and `src/emit/betterxen_tests.rs` (BetterXen gfx1030 fixtures through the recompiler, and on the GPU under CrossOver). Two lines in `src/emit/mod.rs` declare them. Validation record: `docs/research/victory-shader-integration.md`.
### Edits to upstream files
- `Cargo.toml` rewritten: workspace-inherited dependency versions replaced by explicit ones (`thiserror` 2.0.21, `zlib-rs` 0.6.8, `windows` 0.62.2, `windows-sys` 0.61.2), same features and lint allowances as upstream's workspace.
- `src/lib.rs`: `#[rustfmt::skip]` on each `mod` so the vendored files stay byte-comparable with upstream.
- `src/emit/mod.rs`, `src/emit/f64.rs`, `src/emit/lower.rs`: `#[allow(...)]` attributes only, so the crate passes `clippy -D warnings` here. They silence imports and variables used only by Windows-only tests, an unused trait method, a test constant that looks like pi, and two dead duplicate match arms in `lower.rs` that exist upstream (an earlier arm already handles `v_cvt_f32_f64` and `v_permlanex16_b32`).
## Not carried
The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. The shader inputs the upstream project was built for are not included; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record).
+696
View File
@@ -0,0 +1,696 @@
//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and
//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the
//! instruction returns for one ray and one node. The emitter lowers the
//! instruction to the same arithmetic in the same order
//! (`emit/intersect.rs`), so its code can be compared against this dword
//! for dword.
//!
//! The instruction tests one ray against one 64-byte node of a bounding
//! volume hierarchy and returns four dwords. Traversal (the stack, instance
//! transforms, culling, the hit distance `numerator / denominator`) is the
//! program's own code.
//!
//! # Node pointers
//!
//! A node pointer's low three bits are the node's kind, the rest its byte
//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the
//! base address of the descriptor (40 bits in dword 0 and the low byte of
//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer;
//! the 64-bit form a 64-bit one, with which a program uses one descriptor
//! with base 0 for every structure and adds `address >> 3` itself.
//!
//! | kind | node |
//! |---|---|
//! | 0-3 | triangle 0-3 of a triangle node |
//! | 4 | box node, 16-bit floats (64 bytes) |
//! | 5 | box node, 32-bit floats (128 bytes) |
//! | 6 | instance: not read by the instruction |
//! | 7 | procedural primitive: not read by the instruction |
//!
//! # Box nodes
//!
//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four
//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16
//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes
//! 112-127 are not read). The result is the pointers of the children whose
//! box the ray enters before its extent, nearest entry first when the
//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest.
//!
//! # Triangle nodes
//!
//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte
//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that
//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an
//! input triangle's second vertex at the former, its third at the latter
//! and its first at the remaining one, so I and J are the weights of the
//! input triangle's second and third vertices). Triangle `k` of the node
//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that
//! keeps fewer triangles in a node uses the bytes of the unused vertices
//! for its own data.
//!
//! With the descriptor's triangle return mode set (bit 120) the result is
//! the hit distance's numerator, its denominator, and the numerators of I
//! and J over the same denominator, as floats. The denominator is positive
//! for a triangle whose vertices run clockwise seen from the ray's origin
//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0.
//! The ray's extent is not tested for triangles.
//!
//! # Where this comes from
//!
//! The node formats, the descriptor bits and the tests are those of the
//! public software emulation of this instruction in the open-source Vulkan
//! driver for this GPU family (box test and sorting network as there; the
//! triangle test is the watertight one it uses, Woop, Benthin and Wald,
//! JCGT 2013), and agree with what the title's own structure
//! builder writes and its trace programs read. Not known from either: how
//! the console rounds, which of two boxes entered at the same distance it
//! returns first, and what it returns for a ray exactly through an edge
//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here:
//! a triangle miss; the title's programs do not read it).
/// The result dword for a box the ray misses, or a child that is not there.
pub const NONE: u32 = 0xffff_ffff;
/// The node's vertices that make triangle 0-3, by the triangle's own
/// vertex numbers 0-2.
pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]];
/// Descriptor dword 1: boxes are returned nearest first.
pub const BOX_SORT: u32 = 1 << 31;
/// Descriptor dword 3: triangles return the numerators of I and J (clear:
/// a triangle id and a hit status, which nothing here produces).
pub const RETURN_BARYCENTRICS: u32 = 1 << 24;
/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing
/// structure.
pub const DESCRIPTOR_TYPE: u32 = 8;
/// The ray as the instruction takes it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ray {
pub extent: f32,
pub origin: [f32; 3],
pub direction: [f32; 3],
/// What the program computed as `1 / direction`.
pub inverse: [f32; 3],
}
impl Ray {
/// A ray with the inverse direction a program computes by division.
pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self {
Self {
extent,
origin,
direction,
inverse: direction.map(|d| 1.0 / d),
}
}
}
/// The kind of the node a pointer names.
pub fn kind(pointer: u64) -> u32 {
(pointer & 7) as u32
}
/// The byte address of the node `pointer` names, for a descriptor whose
/// first two dwords are `word0` and `word1`.
pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 {
let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8;
base.wrapping_add((pointer >> 3) << 6)
}
/// What the instruction returns for the node at `words` (its first 28
/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer
/// of this `kind`, with box sorting as `sort` says and the triangle return
/// mode set.
pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] {
match kind & 7 {
4 => boxes(&children(words), &boxes16(words), ray, sort),
5 => boxes(&children(words), &boxes32(words), ray, sort),
k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits),
_ => MISS.map(f32::to_bits),
}
}
/// A box node's four child pointers.
pub fn children(words: &[u32; 28]) -> [u32; 4] {
[words[0], words[1], words[2], words[3]]
}
/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z.
pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] {
std::array::from_fn(|b| {
std::array::from_fn(|k| {
let half = 6 * b + k;
half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16)
})
})
}
/// The four boxes of a 32-bit box node.
pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] {
std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k])))
}
/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest
/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432,
/// 0x042).
pub fn vertex_map(k: u32) -> u32 {
let v = TRIANGLE_VERTICES[(k & 3) as usize];
v[0] | v[1] << 4 | v[2] << 8
}
/// The vertices of triangle `k` (0-3) of a triangle node, the first being
/// the one neither barycentric weighs, then I's, then J's.
pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] {
let id = words[15] >> (8 * k);
let (i, j) = (id & 3, id >> 2 & 3);
// An id naming one vertex twice, or a vertex 3, is malformed; it reads
// what this arithmetic lands on (a vertex of the node), as the emitted
// code does.
let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3;
[first, i, j].map(|n| {
let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize;
std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c]))
})
}
/// The box test: child pointers of the boxes the ray enters, `NONE` for
/// the others; sorted by entry distance when `sort`, in child order
/// otherwise.
pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] {
// An infinite inverse (a direction component of 0) would turn an
// origin exactly on a box's face into a NaN. (Maximum then minimum, as
// the emitted code: a NaN becomes the lower bound, where `clamp` would
// keep it.)
#[allow(clippy::manual_clamp)]
let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX));
let mut ids = [NONE; 4];
let mut distances = [f32::INFINITY; 4];
for (n, b) in boxes.iter().enumerate() {
let (mut near, mut far) = ([0f32; 3], [0f32; 3]);
for a in 0..3 {
let low = (b[a] - ray.origin[a]) * inverse[a];
let high = (b[3 + a] - ray.origin[a]) * inverse[a];
near[a] = low.min(high);
far[a] = low.max(high);
}
let enter = near[0].max(near[1]).max(near[2]);
let leave = far[0].min(far[1]).min(far[2]);
// A box whose minimum x is NaN is switched off.
if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
ids[n] = children[n];
distances[n] = enter;
}
}
if sort {
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
if distances[b] < distances[a] {
distances.swap(a, b);
ids.swap(a, b);
}
}
}
ids
}
/// What a triangle the ray misses returns.
pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
/// The triangle test: the hit distance's numerator, the denominator, and
/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
/// Watertight: the vertices are sheared so the ray runs along its largest
/// axis, and the signs of the three edge functions decide, so a ray
/// between two triangles that share an edge cannot miss both. Any NaN
/// misses, and so does a triangle seen edge-on.
pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
let d = ray.direction;
let size = d.map(f32::abs);
// The largest axis, and the other two in an order that keeps the
// triangle's winding.
let kz = if size[0] >= size[1] {
if size[0] >= size[2] { 0 } else { 2 }
} else if size[1] >= size[2] {
1
} else {
2
};
let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
if d[kz] < 0.0 {
std::mem::swap(&mut kx, &mut ky);
}
let sz = ray.inverse[kz];
let (sx, sy) = (d[kx] * sz, d[ky] * sz);
let sheared = |v: &[f32; 3]| {
let r = [
v[0] - ray.origin[0],
v[1] - ray.origin[1],
v[2] - ray.origin[2],
];
(r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
};
let (ax, ay, az) = sheared(&p[0]);
let (bx, by, bz) = sheared(&p[1]);
let (cx, cy, cz) = sheared(&p[2]);
let u = cx * by - cy * bx;
let v = ax * cy - ay * cx;
let w = bx * ay - by * ax;
let behind = u < 0.0 || v < 0.0 || w < 0.0;
let before = u > 0.0 || v > 0.0 || w > 0.0;
let det = u + (v + w);
let t = (u * az + v * bz) + w * cz;
let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
if !(behind && before) && ahead {
[t, det, v, w]
} else {
MISS
}
}
/// A 16-bit float as a 32-bit one (exact).
pub fn half_to_f32(h: u16) -> f32 {
let sign = u32::from(h >> 15) << 31;
let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
let bits = match exponent {
0 if mantissa == 0 => sign,
0 => {
// Subnormal: normalise.
let shift = mantissa.leading_zeros() - 21;
sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
}
0x1f => sign | 0xff << 23 | mantissa << 13,
e => sign | (e + 112) << 23 | mantissa << 13,
};
f32::from_bits(bits)
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
/// The smallest 16-bit float not below `x` (`up`) or not above it.
pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
let mut best: Option<u16> = None;
for h in 0..=0xffffu16 {
let f = half_to_f32(h);
if f.is_nan() || if up { f < x } else { f > x } {
continue;
}
best = match best {
Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
_ => Some(h),
};
}
best.expect("a half")
}
/// A 32-bit box node.
pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
let mut w = [0u32; 28];
w[..4].copy_from_slice(&children);
for (b, bx) in boxes.iter().enumerate() {
for (k, x) in bx.iter().enumerate() {
w[4 + 6 * b + k] = x.to_bits();
}
}
w
}
/// A 16-bit box node holding `boxes` rounded outward.
pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
let mut w = [0u32; 28];
w[..4].copy_from_slice(&children);
for (b, bx) in boxes.iter().enumerate() {
for (k, x) in bx.iter().enumerate() {
let half = 6 * b + k;
let h = if x.is_nan() {
0x7e00
} else {
f32_to_half(*x, k >= 3)
};
w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
}
}
w
}
/// A triangle node: up to five vertices, and the dword at byte 60.
pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
let mut w = [0u32; 28];
for (n, v) in vertices.iter().enumerate() {
for (c, x) in v.iter().enumerate() {
w[3 * n + c] = x.to_bits();
}
}
w[15] = id;
w
}
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
std::array::from_fn(|k| b[k] + by[k % 3])
}
const OFF: [f32; 6] = [f32::NAN; 6];
#[test]
fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
// The 64-bit form as the title uses it: base 0, the structure's
// address folded into the pointer.
let structure = 0x12_3456_7800u64;
let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
assert_eq!(kind(pointer), 5);
assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
// The 32-bit form: the base in the descriptor.
let word0 = (structure >> 8) as u32;
let word1 = (structure >> 40) as u32 | BOX_SORT;
assert_eq!(
node_address(word0, word1, 0x1000 >> 3 | 4),
structure + 0x1000
);
// A base past 4 GiB of 256-byte units.
assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
}
#[test]
fn halves_convert_exactly() {
assert_eq!(half_to_f32(0x3c00), 1.0);
assert_eq!(half_to_f32(0xc000), -2.0);
assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
assert_eq!(half_to_f32(0x7bff), 65504.0);
assert!(half_to_f32(0x7e00).is_nan());
assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
// Outward rounding of the test helper.
assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
}
#[test]
fn boxes_are_returned_nearest_first_and_misses_last() {
let children = [0x105, 0x20c, 0x304, 0x400];
// Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
let node = box32(
children,
[
moved(UNIT, [30.0, 0.0, 0.0]),
moved(UNIT, [10.0, 0.0, 0.0]),
moved(UNIT, [10.0, 5.0, 0.0]),
moved(UNIT, [20.0, 0.0, 0.0]),
],
);
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
// Without sorting: child order, the miss in its place.
assert_eq!(
intersect(&node, 5, &ray, false),
[0x105, 0x20c, NONE, 0x400]
);
// The extent cuts the far ones off (entered at 9, 19, 29).
let short = Ray {
extent: 19.5,
..ray
};
assert_eq!(
intersect(&node, 5, &short, true),
[0x20c, 0x400, NONE, NONE]
);
// An entry exactly at the extent is no hit.
let exact = Ray {
extent: 19.0,
..ray
};
assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
// Backwards: nothing.
let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
}
#[test]
fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
let node = box32(
[8, 16, NONE, NONE],
[UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
);
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
// Box 0 is entered at -1 (behind the origin), box 1 at 2.
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
// Even with a tiny extent the box around the origin is a hit.
let tiny = Ray {
extent: 1e-6,
..ray
};
assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
}
#[test]
fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
// Direction components of 0: the inverse is infinite.
let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert!(ray.inverse[1].is_infinite());
// The origin lies in the plane of the box's -y face: (-1 - -1) x inf
// would be a NaN; with the inverse held finite it is 0, and the ray
// running along the face is inside.
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
// Along the +y face it is outside: the face's plane is left at 0
// and the box is entered at 4 (as the public emulation has it).
let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
// -0 gives -infinity.
let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
}
#[test]
fn a_box_switched_off_and_a_missing_child_return_none() {
let node = box32(
[8, NONE, 24, 32],
[UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
);
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
// Child 1 is hit but is not there: its pointer is what "none" is.
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
}
#[test]
fn equal_distances_keep_child_order() {
let node = box32([8, 16, 24, 32], [UNIT; 4]);
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
}
#[test]
fn half_float_boxes_test_like_their_widened_values() {
let boxes = [
moved(UNIT, [30.0, 0.1, 0.0]),
moved(UNIT, [10.0, 0.0, 0.3]),
moved(UNIT, [10.0, 5.0, 0.0]),
moved(UNIT, [20.7, 0.0, 0.0]),
];
let children = [0x105, 0x20c, 0x304, 0x400];
let node = box16(children, boxes);
let wide = boxes16(&node);
for (w, b) in wide.iter().zip(&boxes) {
for k in 0..3 {
assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
}
}
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
assert_eq!(
intersect(&node, 4, &ray, true),
intersect(&box32(children, wide), 5, &ray, true)
);
}
/// The hit a result describes: distance, I, J, front face.
fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
let [t, det, i, j] = r.map(f32::from_bits);
(t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
}
/// Clockwise seen from the origin looking down +z in a left-handed
/// system (x right, y up): the front face.
const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
#[test]
fn a_triangle_returns_distance_and_weights_over_one_denominator() {
let node = triangles(&TRIANGLE, 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert_eq!(t, 5.0);
// (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
assert_eq!((i, j), (0.25, 0.25));
assert!(front);
// Near vertex 1: I near 1.
let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert!(i > 0.85 && j < 0.1, "{i} {j}");
// From behind: the same weights, the back face.
let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
// An unnormalised direction: the distance is in its units.
let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
}
#[test]
fn a_triangle_is_missed_beside_behind_and_edge_on() {
let node = triangles(&TRIANGLE, 9);
let miss = MISS.map(f32::to_bits);
// Beside it.
let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// It lies behind the origin.
let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// In its plane.
let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
assert_eq!(intersect(&node, 0, &ray, true), miss);
// A triangle with no area.
let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&flat, 0, &ray, true), miss);
// A vertex that is not a number, a direction of zero.
let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
assert_eq!(intersect(&nan, 0, &ray, true), miss);
let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
assert_eq!(intersect(&node, 0, &still, true), miss);
// The extent is the program's to test: a far triangle is a hit.
let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
assert!(hit(intersect(&node, 0, &short, true)).is_some());
}
#[test]
fn a_ray_through_a_shared_edge_misses_neither_triangle() {
// Two triangles of a quad sharing the diagonal, wound alike.
let quad = [
[-1.0, -1.0, 4.0],
[-1.0, 1.0, 4.0],
[1.0, 1.0, 4.0],
[1.0, -1.0, 4.0],
];
let first = triangles(&[quad[0], quad[1], quad[2]], 9);
let second = triangles(&[quad[0], quad[2], quad[3]], 9);
// A fan of rays crossing the diagonal, some exactly on it.
for n in -40..=40 {
let x = n as f32 / 64.0;
for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
// Aim at (ox, oy, 4).
let s = 4.0 / d[2];
let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
let a = hit(intersect(&first, 0, &ray, true));
let b = hit(intersect(&second, 0, &ray, true));
assert!(
a.is_some() || b.is_some(),
"a hole at {ox} {oy} along {d:?}"
);
for h in [a, b].into_iter().flatten() {
assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
}
}
}
}
}
#[test]
fn the_id_dword_says_which_vertices_the_weights_belong_to() {
// What the title's builder does with an input triangle (a, b, c)
// and an id byte: a at the vertex neither field names, b at I's,
// c at J's.
let [a, b, c] = TRIANGLE;
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
let mut stored = [[0f32; 3]; 3];
stored[(3 - i - j) as usize] = a;
stored[i as usize] = b;
stored[j as usize] = c;
let node = triangles(&stored, i | j << 2);
assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
}
// The higher bits of the byte (opaque and the like) change nothing.
let node = triangles(&[a, b, c], 9 | 0x80);
assert_eq!(intersect(&node, 0, &ray, true), plain);
}
#[test]
fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
let [a, b, c] = TRIANGLE;
let far = [50.0, 50.0, 50.0];
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
for k in 1..4u32 {
// Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
let mut vertices = [far; 5];
let at = TRIANGLE_VERTICES[k as usize];
vertices[at[0] as usize] = a;
vertices[at[1] as usize] = b;
vertices[at[2] as usize] = c;
// Triangle 0's byte would be malformed here; only byte k counts.
let node = triangles(&vertices, 9 << (8 * k));
assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
}
// A pair as the title's builder stores it: the second triangle's
// own vertex at node vertex 3, named by I.
let d = [2.0, 2.0, 5.0];
// Input triangles (a, b, c) and (a, d, b): they share a and b.
let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
// Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
let got = triangle_vertices(&node, 1);
assert_eq!(got, [b, d, c]);
}
#[test]
fn instances_and_procedural_nodes_return_a_triangle_miss() {
let node = triangles(&TRIANGLE, 9);
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
for k in [6, 7] {
assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
}
}
#[test]
fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
// The same triangle and ray turned so the ray's largest axis is each
// of the three, forwards and backwards. Both turns are rotations,
// so the facing stays.
let turn = |v: [f32; 3], axis: usize, flip: bool| {
let mut r = v;
for _ in 0..axis {
r = [r[2], r[0], r[1]];
}
if flip {
// Half a turn about the axis after the largest one's next.
let largest = (2 + axis) % 3;
r[largest] = -r[largest];
r[(largest + 1) % 3] = -r[(largest + 1) % 3];
}
r
};
let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
for axis in 0..3 {
for flip in [false, true] {
let p = TRIANGLE.map(|v| turn(v, axis, flip));
let r = Ray::new(
turn(ray.origin, axis, flip),
turn(ray.direction, axis, flip),
100.0,
);
let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
}
}
}
}
+181
View File
@@ -0,0 +1,181 @@
//! The DXBC container: a header, then a table of FourCC-tagged parts.
//!
//! ```text
//! 0x00 "DXBC"
//! 0x04 digest[16]
//! 0x14 version major u16, minor u16
//! 0x18 total size u32
//! 0x1C part count u32
//! 0x20 part offsets u32[count]
//! part: fourcc[4], size u32, data[size]
//! ```
use crate::ShaderError;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FourCC(pub [u8; 4]);
impl FourCC {
pub const DXIL: FourCC = FourCC(*b"DXIL");
pub const STAT: FourCC = FourCC(*b"STAT");
pub const RTS0: FourCC = FourCC(*b"RTS0");
pub const PSV0: FourCC = FourCC(*b"PSV0");
pub const ISG1: FourCC = FourCC(*b"ISG1");
pub const OSG1: FourCC = FourCC(*b"OSG1");
/// Per-primitive outputs of a mesh shader.
pub const PSG1: FourCC = FourCC(*b"PSG1");
pub const SFI0: FourCC = FourCC(*b"SFI0");
pub const HASH: FourCC = FourCC(*b"HASH");
pub const ILDB: FourCC = FourCC(*b"ILDB");
pub const ILDN: FourCC = FourCC(*b"ILDN");
}
impl std::fmt::Debug for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
impl std::fmt::Display for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for &b in &self.0 {
let c = if b.is_ascii_graphic() { b as char } else { '.' };
write!(f, "{c}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Part<'a> {
pub fourcc: FourCC,
/// Offset of the part header within the container.
pub offset: usize,
pub data: &'a [u8],
}
#[derive(Debug, Clone)]
pub struct Container<'a> {
pub digest: [u8; 16],
pub version: (u16, u16),
pub parts: Vec<Part<'a>>,
}
const HEADER_SIZE: usize = 0x20;
const MAX_PARTS: usize = 256;
impl<'a> Container<'a> {
pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" {
return Err(ShaderError::NotDxbc);
}
let digest = data[4..20].try_into().expect("16 bytes");
let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?);
let total = u32_at(data, 0x18)? as usize;
if total > data.len() || total < HEADER_SIZE {
return Err(ShaderError::Malformed("container size disagrees with data"));
}
let data = &data[..total];
let count = u32_at(data, 0x1C)? as usize;
if count > MAX_PARTS {
return Err(ShaderError::Malformed("implausible part count"));
}
let mut parts = Vec::with_capacity(count);
for i in 0..count {
let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize;
let fourcc = FourCC(
data.get(offset..offset + 4)
.ok_or(ShaderError::Malformed("part header out of bounds"))?
.try_into()
.expect("4 bytes"),
);
let size = u32_at(data, offset + 4)? as usize;
let body = data
.get(offset + 8..offset + 8 + size)
.ok_or(ShaderError::Malformed("part data out of bounds"))?;
parts.push(Part {
fourcc,
offset,
data: body,
});
}
Ok(Container {
digest,
version,
parts,
})
}
pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> {
self.parts.iter().find(|p| p.fourcc == fourcc)
}
}
pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
data.get(at..at + 2)
.map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> {
data.get(at..at + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> {
data.get(at..at + 8)
.map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
/// Builds a container from parts (test helper).
#[cfg(test)]
pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> {
let table = HEADER_SIZE + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
let mut out = Vec::with_capacity(total);
out.extend_from_slice(b"DXBC");
out.extend_from_slice(&[0; 16]);
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&(total as u32).to_le_bytes());
out.extend_from_slice(&(parts.len() as u32).to_le_bytes());
let mut offset = table;
for (_, d) in parts {
out.extend_from_slice(&(offset as u32).to_le_bytes());
offset += 8 + d.len();
}
for (fourcc, d) in parts {
out.extend_from_slice(&fourcc.0);
out.extend_from_slice(&(d.len() as u32).to_le_bytes());
out.extend_from_slice(d);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_parts() {
let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]);
let c = Container::parse(&bytes).unwrap();
assert_eq!(c.parts.len(), 2);
assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]);
assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20);
assert!(c.part(FourCC::DXIL).is_none());
}
#[test]
fn rejects_bad_input() {
assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc);
let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]);
let last = bytes.len() - 1;
bytes[0x20] = 0xFF; // corrupt the first part offset
assert!(Container::parse(&bytes).is_err());
bytes.truncate(last);
assert!(Container::parse(&bytes).is_err());
}
}
+211
View File
@@ -0,0 +1,211 @@
//! The DXIL program inside a container's `DXIL` (or `STAT`) part.
//!
//! ```text
//! 0x00 program version u32 (kind << 16 | major << 4 | minor)
//! 0x04 size in dwords u32
//! 0x08 "DXIL" <- bitcode offset is relative to here
//! 0x0C dxil version u32
//! 0x10 bitcode offset u32 (16 in standard PC DXIL)
//! 0x14 bitcode size u32
//! ```
use crate::ShaderError;
use crate::dxbc::u32_at;
const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE];
#[cfg(test)]
const STANDARD_BITCODE_OFFSET: u32 = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShaderKind {
Pixel,
Vertex,
Geometry,
Hull,
Domain,
Compute,
Library,
RayGeneration,
Intersection,
AnyHit,
ClosestHit,
Miss,
Callable,
Mesh,
Amplification,
Node,
Unknown(u16),
}
impl ShaderKind {
fn from_raw(v: u16) -> Self {
use ShaderKind::*;
match v {
0 => Pixel,
1 => Vertex,
2 => Geometry,
3 => Hull,
4 => Domain,
5 => Compute,
6 => Library,
7 => RayGeneration,
8 => Intersection,
9 => AnyHit,
10 => ClosestHit,
11 => Miss,
12 => Callable,
13 => Mesh,
14 => Amplification,
15 => Node,
other => Unknown(other),
}
}
}
#[derive(Debug, Clone)]
pub struct DxilProgram<'a> {
pub kind: ShaderKind,
pub shader_model: (u8, u8),
pub dxil_version: u32,
/// LLVM bitcode (starts with `BC C0 DE`).
pub bitcode: &'a [u8],
/// Bytes between the bitcode header and the bitcode. Empty on PC.
pub prefix: &'a [u8],
/// Bytes after the bitcode, up to the program size. Empty on PC.
pub trailer: &'a [u8],
}
/// Xbox additions recognised around the bitcode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct XboxExtras {
/// The prefix starts with an `XDAT` table.
pub xdat: bool,
/// The trailer contains an `xbop` blob (compiler options).
pub xbop: bool,
}
impl<'a> DxilProgram<'a> {
pub fn parse(part: &'a [u8]) -> Result<Self, ShaderError> {
let version = u32_at(part, 0)?;
let size = (u32_at(part, 4)? as usize)
.checked_mul(4)
.filter(|&s| s <= part.len() && s >= 24)
.ok_or(ShaderError::Malformed(
"program size disagrees with part size",
))?;
let part = &part[..size];
if part.get(8..12) != Some(b"DXIL") {
return Err(ShaderError::Malformed("missing DXIL magic"));
}
let dxil_version = u32_at(part, 12)?;
let offset = u32_at(part, 16)?;
let len = u32_at(part, 20)? as usize;
let start = 8 + offset as usize;
let bitcode = part
.get(start..start + len)
.ok_or(ShaderError::Malformed("bitcode out of bounds"))?;
if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) {
return Err(ShaderError::Malformed("bitcode lacks LLVM magic"));
}
let prefix = part
.get(24..start)
.ok_or(ShaderError::Malformed("bitcode offset too small"))?;
Ok(DxilProgram {
kind: ShaderKind::from_raw((version >> 16) as u16),
shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8),
dxil_version,
bitcode,
prefix,
trailer: &part[start + len..],
})
}
/// True for a program laid out exactly like PC DXIL.
pub fn is_standard_layout(&self) -> bool {
self.prefix.is_empty() && self.trailer.is_empty()
}
pub fn xbox_extras(&self) -> XboxExtras {
XboxExtras {
xdat: self.prefix.starts_with(b"XDAT"),
xbop: self.trailer.windows(4).any(|w| w == b"xbop"),
}
}
}
/// Builds a standard PC-layout program around `bitcode` (test helper).
#[cfg(test)]
pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1);
let padded = bitcode.len().next_multiple_of(4);
let size_dwords = (24 + padded) / 4;
out.extend_from_slice(&version.to_le_bytes());
out.extend_from_slice(&(size_dwords as u32).to_le_bytes());
out.extend_from_slice(b"DXIL");
out.extend_from_slice(&dxil_version.to_le_bytes());
out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes());
out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
out.extend_from_slice(bitcode);
out.resize(24 + padded, 0);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn fake_bitcode() -> Vec<u8> {
let mut b = LLVM_BITCODE_MAGIC.to_vec();
b.extend_from_slice(&[0xAA; 12]);
b
}
#[test]
fn parses_standard_layout() {
let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode());
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Pixel);
assert_eq!(p.shader_model, (6, 0));
assert!(p.is_standard_layout());
assert_eq!(p.xbox_extras(), XboxExtras::default());
}
#[test]
fn detects_xbox_layout() {
// Xbox layout: XDAT table before the bitcode, xbop blob after it.
let bitcode = fake_bitcode();
let xdat = b"XDAT\x01\x00\x00\x00";
let trailer = b"xbop\x02\x00\x00\x00";
let mut bytes = Vec::new();
let size = 24 + xdat.len() + bitcode.len() + trailer.len();
bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5
bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes());
bytes.extend_from_slice(b"DXIL");
bytes.extend_from_slice(&0x105u32.to_le_bytes());
bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes());
bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
bytes.extend_from_slice(xdat);
bytes.extend_from_slice(&bitcode);
bytes.extend_from_slice(trailer);
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Compute);
assert_eq!(p.shader_model, (6, 5));
assert!(!p.is_standard_layout());
assert_eq!(
p.xbox_extras(),
XboxExtras {
xdat: true,
xbop: true
}
);
assert_eq!(p.bitcode, &bitcode[..]);
}
#[test]
fn rejects_missing_bitcode_magic() {
let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]);
assert!(DxilProgram::parse(&bytes).is_err());
}
}
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen addition to the vendored victory-shader crate (see ../../UPSTREAM.md): a public
// entry point for a raw compute program, with the same stages `translate` runs for a container.
use super::{HostShader, lower};
use crate::native::{HwStage, NativeProgram};
use crate::{ShaderError, io, resource, spill, structure};
/// Translates a compute program that is already a [`NativeProgram`] (machine code plus its
/// root layout) instead of one stored in a console shader container. Only the compute stage is
/// accepted: graphics stages need signatures that only a container carries.
pub fn translate_native(native: &NativeProgram) -> Result<HostShader, ShaderError> {
if native.stage != HwStage::Cs {
return Err(ShaderError::Unsupported {
offset: 0,
what: "translate_native takes compute programs only",
});
}
// (what an earlier program's lowering on this thread left behind)
lower::take_needs();
let p = spill::build(native)?;
let st = structure::structure(&p);
let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
let io = io::raise(&p, native)?;
let st = st?;
let lowered = lower::lower(&lower::Parts {
native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})?;
Ok(HostShader {
stage: native.stage,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
})
}
@@ -0,0 +1,222 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen tests for the vendored victory-shader crate (see ../../UPSTREAM.md).
//
// BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled
// with LLVM's llvm-mc) are translated to DXIL by the vendored recompiler. Their expected output
// words come from `fixtures/manifest.toml`, derived by hand there and checked by BetterXen's own
// independent reference; nothing in this file derives an expectation from the recompiler.
//
// Fixture ABI (docs/interfaces.md): v0 = grid index, V# of the input buffer in s[0:3], of the
// output buffer in s[4:7]. The vendored recompiler instead gets descriptors from a table, so
// the program is wrapped in a prologue that loads both from a descriptor table into s[0:3] and
// s[4:7] and then continues into the fixture's code unchanged.
use super::translate_native;
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
const MANIFEST: &str = include_str!("../../../../fixtures/manifest.toml");
/// Fixtures that bind an input and an output buffer and have expected words in the manifest.
/// Keyed by the file name in the manifest's `path`.
const BINARIES: &[(&str, &[u8])] = &[
("add.bin", include_bytes!("../../../../fixtures/rdna2/add.bin")),
("float-exact.bin", include_bytes!("../../../../fixtures/rdna2/float-exact.bin")),
("bitwise-branch.bin", include_bytes!("../../../../fixtures/rdna2/bitwise-branch.bin")),
("or.bin", include_bytes!("../../../../fixtures/rdna2/or.bin")),
("shifts.bin", include_bytes!("../../../../fixtures/rdna2/shifts.bin")),
("ashr.bin", include_bytes!("../../../../fixtures/rdna2/ashr.bin")),
];
struct Fixture {
id: String,
code: &'static [u8],
input: Vec<u32>,
expected: Vec<u32>,
}
fn words(line: &str) -> Vec<u32> {
line.trim()
.trim_start_matches('[')
.trim_end_matches(']')
.split(',')
.filter(|t| !t.trim().is_empty())
.map(|t| t.trim().parse().expect("a decimal word"))
.collect()
}
/// Fixtures with input and expected words in the manifest. A fixture the manifest lists with
/// expected words but that is not embedded above fails the test instead of being skipped.
fn fixtures() -> Vec<Fixture> {
let mut out = Vec::new();
for block in MANIFEST.split("[[fixture]]").skip(1) {
let get = |key: &str| {
block
.lines()
.find_map(|l| l.strip_prefix(&format!("{key} = ")))
.map(str::to_owned)
};
let (Some(input), Some(expected)) = (get("input"), get("expected")) else { continue };
let (input, expected) = (words(&input), words(&expected));
if input.is_empty() || expected.is_empty() {
continue;
}
let id = get("id").unwrap().trim_matches('"').to_owned();
let path = get("path").unwrap().trim_matches('"').to_owned();
let name = path.rsplit('/').next().unwrap();
let code = BINARIES
.iter()
.find(|(n, _)| *n == name)
.unwrap_or_else(|| panic!("fixture {id} ({name}) is in the manifest but not embedded"))
.1;
out.push(Fixture { id, code, input, expected });
}
out
}
/// `s_mov_b32 sdst, 0` (inline constant 0 is source 0x80).
const fn s_mov_b32_zero(sdst: u32) -> u32 {
0xBE80_0000 | sdst << 16 | 0x03 << 8 | 0x80
}
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
const fn s_load_dwordx4(dst: u32, base: u32, byte_offset: u32) -> [u32; 2] {
[0x3D << 26 | 0x02 << 18 | dst << 6 | base >> 1, 125 << 25 | byte_offset]
}
/// `s_waitcnt lgkmcnt(0)` with the other counters left alone.
const S_WAITCNT_LGKM0: u32 = 0xBF8C_C07F;
/// Wraps a fixture so its descriptors arrive through a descriptor table. The table's two
/// 32-byte slots hold the input SRV (heap index 0) and the output UAV (heap index 1).
fn program(code: &[u8], threads: u32) -> NativeProgram {
let mut w: Vec<u32> = Vec::new();
w.push(s_mov_b32_zero(9)); // upper half of the table address; the lower half is user data s8
w.extend(s_load_dwordx4(0, 8, 0x00)); // input V# -> s[0:3]
w.extend(s_load_dwordx4(4, 8, 0x20)); // output V# -> s[4:7]
w.push(S_WAITCNT_LGKM0);
let mut bytes: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
bytes.extend_from_slice(code);
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 32,
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 8,
slot: 0,
}],
used: vec![
UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
dwords: 4,
user_data: 8,
slot: 0,
},
UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 8,
lower_bound: 0,
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
dwords: 4,
user_data: 8,
slot: 0,
},
],
io: StageIo::Cs(ComputeIo { rsrc2: 9 << 1, threads: [threads, 1, 1] }),
code: bytes,
}
}
#[test]
fn every_embedded_fixture_is_listed_in_the_manifest() {
let listed = fixtures();
assert_eq!(listed.len(), BINARIES.len(), "embedded list and manifest disagree");
}
#[test]
fn fixtures_translate_to_a_dxil_container() {
for f in fixtures() {
assert!(!f.expected.is_empty(), "{}: no expected words", f.id);
let native = program(f.code, f.input.len() as u32);
let shader = translate_native(&native)
.unwrap_or_else(|e| panic!("{}: translate_native failed: {e}", f.id));
assert_eq!(&shader.dxil[..4], b"DXBC", "{}: not a DXBC/DXIL container", f.id);
assert!(shader.dxil.len() > 100, "{}: container too small", f.id);
}
}
#[cfg(windows)]
mod on_the_gpu {
use super::*;
use crate::emit::host::{Dispatch, Host, Root, Stride, View};
fn run_on_gpu(host: &Host, f: &Fixture) -> Vec<u32> {
let shader = translate_native(&program(f.code, f.input.len() as u32)).expect("translate");
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
// The table parameter's value is the heap offset: both views start at heap index 0.
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer { data: &f.input, stride: Stride::Raw },
View::RawUav(f.input.len() as u32),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{}: dispatch failed: {e}", f.id));
out[0][..f.expected.len()].to_vec()
}
/// Runs each fixture on the default D3D12 device and compares every output word with the
/// manifest. If no suitable device exists the test fails loudly rather than passing: a
/// skipped run is not GPU verification.
#[test]
fn fixtures_on_the_default_d3d12_device_match_the_manifest() {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified");
let mut ran = 0;
for f in fixtures() {
let got = run_on_gpu(&host, &f);
assert_eq!(got, f.expected, "{}: output words differ from the manifest", f.id);
eprintln!("betterxen fixture {} ran on the GPU and matched the manifest", f.id);
ran += 1;
}
assert_eq!(ran, fixtures().len());
}
/// Negative control: the comparison above must be able to fail. A copy of each expected
/// output with one bit flipped must not equal what the GPU produced, and the output must
/// not be the untouched zeroed buffer or an echo of the input (unless the manifest says so).
#[test]
fn a_wrong_expectation_is_detected() {
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
let host = Host::new(false).expect("no SM 6.6 D3D12 hardware device: not verified");
for f in fixtures() {
let got = run_on_gpu(&host, &f);
let mut wrong = f.expected.clone();
wrong[0] ^= 1;
assert_ne!(got, wrong, "{}: a flipped expectation was accepted", f.id);
assert!(got.iter().any(|&w| w != 0) || f.expected.iter().all(|&w| w == 0), "{}: output is the zeroed buffer", f.id);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,174 @@
//! Counts of a module's instructions by kind (a diagnostic): what a
//! translated program costs before the driver's compiler sees it.
//!
//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of
//! the module a thread wrote last are read with [`take`]. The `translate`
//! command writes them as a table (see `apps/victory/src/translate.rs`).
use super::{Cast, Module, Op, Tag, Term, V};
use std::cell::RefCell;
/// The kinds, in the order of [`Census::counts`].
pub const KINDS: [&str; 26] = [
"total",
"arith",
"math_call",
"bitcast",
"cast",
"select",
"guard_select",
"phi",
"extract",
"buffer_load",
"cbuffer_load",
"texture_read",
"lds_load",
"buffer_store",
"lds_store",
"atomic",
"handle",
"annotate",
"dimensions",
"barrier",
"wave_op",
"io_other",
"gep",
"clamp",
"loop_counter",
"blocks",
];
/// Instruction counts of one written module, by [`KINDS`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Census {
pub counts: [u32; KINDS.len()],
}
thread_local! {
/// The modules this thread wrote since the last [`take`]: the length and
/// a hash of each one's bitcode, with its counts (a program may be
/// emitted in several forms before one is kept).
static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) };
}
fn fnv(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
})
}
/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set).
pub fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some())
}
/// The counts of the module whose bitcode the container `dxil` holds, if
/// this thread wrote it since the last call (which forgets the others).
pub fn take(dxil: &[u8]) -> Option<Census> {
let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut()));
let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?;
written
.into_iter()
.rev()
.find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash))
.map(|w| w.2)
}
/// Counts `m`, whose written form is `bitcode`, and keeps the result for
/// [`take`].
pub(crate) fn note(m: &Module, bitcode: &[u8]) {
if !enabled() {
return;
}
let c = m.census();
WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c)));
}
fn kind(name: &str) -> usize {
let n = name.strip_prefix("dx.op.").unwrap_or(name);
let n = n.split('.').next().unwrap_or(n);
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
match n {
"unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16"
| "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"),
"bufferLoad" | "rawBufferLoad" => k("buffer_load"),
"cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"),
"bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"),
"atomicBinOp" | "atomicCompareExchange" => k("atomic"),
"createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"),
"annotateHandle" => k("annotate"),
"getDimensions" => k("dimensions"),
"barrier" => k("barrier"),
_ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"),
_ if n.starts_with("textureLoad")
|| n.starts_with("sample")
|| n.starts_with("textureGather")
|| n.starts_with("calculateLOD") =>
{
k("texture_read")
}
_ => k("io_other"),
}
}
impl Module {
/// The instructions [`Module::write`] writes, by kind.
pub(crate) fn census(&self) -> Census {
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
let call_kind: Vec<usize> = self.funcs.iter().map(|f| kind(&f.name)).collect();
let live = self.live();
// The blocks `write` lays out: those reached from the entry.
let mut seen = vec![false; self.blocks.len()];
let mut stack = vec![0usize];
if !self.blocks.is_empty() {
seen[0] = true;
}
while let Some(b) = stack.pop() {
for &s in super::successors(self.blocks[b].term).iter() {
if !seen[s] {
seen[s] = true;
stack.push(s);
}
}
}
let mut c = Census::default();
for (b, blk) in self.blocks.iter().enumerate() {
if !seen[b] {
continue;
}
c.counts[k("blocks")] += 1;
let _: Option<Term> = blk.term;
for &i in blk
.phis
.iter()
.filter(|&&i| live[i as usize])
.chain(&blk.body)
{
c.counts[0] += 1;
let at = match &self.insts[i as usize].op {
Op::Bin(..) | Op::Cmp(..) => k("arith"),
Op::Cast(Cast::Bitcast, _) => k("bitcast"),
Op::Cast(..) => k("cast"),
Op::Select(..) => k("select"),
Op::Extract(..) => k("extract"),
Op::Phi(_) => k("phi"),
Op::Gep(..) => k("gep"),
Op::Load(_) => k("lds_load"),
Op::Store(..) => k("lds_store"),
Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"),
Op::Call(f, _) => call_kind[*f as usize],
};
c.counts[at] += 1;
match self.tags.get(&i) {
Some(Tag::Guard) => c.counts[k("guard_select")] += 1,
Some(Tag::Clamp) => c.counts[k("clamp")] += 1,
Some(Tag::Counter) => c.counts[k("loop_counter")] += 1,
None => {}
}
let _ = V::Inst(i);
}
}
c
}
}
File diff suppressed because it is too large. Load diff
+419
View File
@@ -0,0 +1,419 @@
//! The PC container around emitted DXIL: feature flags (`SFI0`), the
//! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the
//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus
//! the container hash that D3D12 checks.
/// One signature element: one row (D3D12 links stages by semantic).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SigElement {
pub name: String,
pub index: u32,
/// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...).
pub kind: u8,
/// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1).
pub comp: u8,
/// DXIL interpolation mode (0 for none).
pub interp: u8,
/// Start row, if the element has a register.
pub row: Option<u32>,
pub col: u8,
pub cols: u8,
/// Components read (inputs) or written (outputs), relative to `col`.
pub usage: u8,
/// 16-bit on the console (declared 32-bit here).
pub half: bool,
}
impl SigElement {
fn system_value(&self) -> u32 {
match self.kind {
1 => 6, // vertex id
2 => 8, // instance id
3 => 1, // position
4 => 4, // render target array index
5 => 5, // viewport array index
6 => 2, // clip distance
7 => 3, // cull distance
10 => 7, // primitive id
12 => 10,
13 => 9, // front face
14 => 66,
15 => 70,
16 => 64, // target
17 => 65, // depth
18 => 68,
19 => 67,
20 => 69,
28 => 23, // barycentrics
30 => 25, // cull primitive
_ => 0,
}
}
fn sig_comp(&self) -> u32 {
match self.comp {
1 | 5 => 1, // bool and u32
4 => 2,
9 => 3,
_ => 0,
}
}
pub(crate) fn mask(&self) -> u8 {
((1u8 << self.cols) - 1) << self.col
}
}
/// `ISG1`/`OSG1`: 32-byte rows, then the names.
pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
let mut out = Vec::new();
out.extend((elements.len() as u32).to_le_bytes());
out.extend(8u32.to_le_bytes());
// Validator 1.6 writes one name per element in element order, repeats
// included, except that system values share theirs (it keys names by
// the semantic's string, which is one static string per system value);
// the rows sorted by register (unallocated last).
let mut offsets: Vec<u32> = Vec::new();
let mut next = 8 + 32 * elements.len() as u32;
let mut names = Vec::new();
for (i, e) in elements.iter().enumerate() {
let shared = (e.kind != 0)
.then(|| (0..i).find(|&j| elements[j].kind == e.kind))
.flatten();
match shared {
Some(j) => offsets.push(offsets[j]),
None => {
offsets.push(next);
next += e.name.len() as u32 + 1;
names.push(&e.name);
}
}
}
let mut order: Vec<usize> = (0..elements.len()).collect();
order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
for i in order {
let (e, offset) = (&elements[i], offsets[i]);
let used = e.usage << e.col;
let rw = if input { used } else { !used & 0xf };
for v in [
0,
offset,
e.index,
e.system_value(),
e.sig_comp(),
e.row.unwrap_or(u32::MAX),
] {
out.extend(v.to_le_bytes());
}
out.extend([e.mask(), rw, 0, 0]);
out.extend(0u32.to_le_bytes());
}
for name in names {
out.extend(name.as_bytes());
out.push(0);
}
out
}
/// The most a mesh shader's outputs may take, in bytes (D3D12).
pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024;
/// A mesh shader's output size as the DXIL validator measures it against
/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element
/// and primitive element, times the maxima rounded up to multiples of 32.
pub(crate) fn mesh_output_bytes(
vertex: &[SigElement],
primitive: &[SigElement],
max_vertices: u32,
max_primitives: u32,
) -> u64 {
let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::<u64>();
let align = |n: u32| u64::from(n).next_multiple_of(32);
4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives))
}
/// A resource bound by register, as `PSV0` lists it.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Binding {
/// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV.
pub kind: u32,
pub space: u32,
pub register: u32,
/// DXIL resource kind (13 cbuffer, 14 sampler).
pub dxil_kind: u32,
}
pub(crate) struct Psv<'a> {
/// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute.
pub stage: u8,
/// Vertex: writes `SV_Position`. Pixel: writes depth.
pub flag: bool,
pub inputs: &'a [SigElement],
pub outputs: &'a [SigElement],
/// Mesh: per-primitive outputs.
pub prims: &'a [SigElement],
/// Mesh: its state and the group-shared bytes it declares.
pub mesh: Option<(super::shader::Mesh, u32)>,
/// Geometry (triangles in, triangle strips out on stream 0): its
/// maximum vertex count. `flag`: writes `SV_Position`.
pub geometry: Option<u32>,
pub bindings: &'a [Binding],
/// Compute: thread-group size and required wave size.
pub threads: [u32; 3],
pub wave_size: Option<u32>,
}
/// `PSV0` with runtime info version 2 (validator 1.6).
pub(crate) fn psv(p: &Psv) -> Vec<u8> {
let vectors = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row)
.map(|r| r + 1)
.max()
.unwrap_or(0)
};
let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs));
let mut out = Vec::new();
let u32s = |out: &mut Vec<u8>, vs: &[u32]| {
for v in vs {
out.extend(v.to_le_bytes());
}
};
u32s(&mut out, &[48]);
let mut info = [0u8; 48];
info[0] = u8::from(p.flag);
if p.stage == 0 {
// PSInfo.SampleFrequency: an input interpolated per sample, or the
// sample index.
info[1] = u8::from(
p.inputs
.iter()
.any(|e| matches!(e.interp, 6 | 7) || e.kind == 12),
);
}
let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
info[16..20].copy_from_slice(&min.to_le_bytes());
info[20..24].copy_from_slice(&max.to_le_bytes());
info[24] = p.stage;
for (k, n) in p.threads.into_iter().enumerate() {
info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes());
}
info[28] = p.inputs.len() as u8;
info[29] = p.outputs.len() as u8;
info[31] = in_vectors as u8;
info[32] = out_vectors as u8;
if let Some((mesh, shared)) = p.mesh {
info[0..4].copy_from_slice(&shared.to_le_bytes());
info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes());
info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes());
info[26] = vectors(p.prims) as u8;
info[27] = mesh.topology;
info[30] = p.prims.len() as u8;
}
if let Some(max_vertices) = p.geometry {
// Input primitive (3: triangles), output topology (5: triangle
// strips), stream mask, position written; the vertex maximum.
info[0..4].copy_from_slice(&3u32.to_le_bytes());
info[4..8].copy_from_slice(&5u32.to_le_bytes());
info[8..12].copy_from_slice(&1u32.to_le_bytes());
info[12] = u8::from(p.flag);
info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes());
}
out.extend(info);
u32s(&mut out, &[p.bindings.len() as u32]);
if !p.bindings.is_empty() {
u32s(&mut out, &[24]);
for b in p.bindings {
u32s(
&mut out,
&[b.kind, b.space, b.register, b.register, b.dxil_kind, 0],
);
}
}
// Names of arbitrary semantics (system values use ""), then indices.
let mut strings = vec![0u8];
let mut indices: Vec<u32> = Vec::new();
let mut elements = Vec::new();
for e in p.inputs.iter().chain(p.outputs).chain(p.prims) {
let name = if e.kind == 0 {
let needle: Vec<u8> = e.name.bytes().chain([0]).collect();
match find(&strings, &needle) {
Some(at) => at,
None => {
strings.extend(&needle);
strings.len() - needle.len()
}
}
} else {
0
};
let index = match indices.iter().position(|&i| i == e.index) {
Some(at) => at,
None => {
indices.push(e.index);
indices.len() - 1
}
};
let (start, alloc) = match e.row {
Some(r) => (r as u8, 0x40 | (e.col << 4)),
None => (0, 0),
};
elements.push((name as u32, index as u32, start, e.cols | alloc, e));
}
strings.resize(strings.len().next_multiple_of(4), 0);
u32s(&mut out, &[strings.len() as u32]);
out.extend(&strings);
u32s(&mut out, &[indices.len() as u32]);
u32s(&mut out, &indices);
if !elements.is_empty() {
u32s(&mut out, &[16]);
for (name, index, start, cols, e) in elements {
u32s(&mut out, &[name, index]);
out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]);
}
}
// Input-to-output dependencies, as the view-id state declares them:
// every output scalar on every input scalar.
if in_vectors > 0 && out_vectors > 0 {
let scalars = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
.max()
.unwrap_or(0)
};
let (ni, no) = (scalars(p.inputs), scalars(p.outputs));
let per = (out_vectors * 4).div_ceil(32);
for i in 0..in_vectors * 4 {
for k in 0..per {
let bits = if i < ni {
no.saturating_sub(32 * k).min(32)
} else {
0
};
let mask = if bits == 32 {
u32::MAX
} else {
(1u32 << bits) - 1
};
u32s(&mut out, &[mask]);
}
}
}
out
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
/// The container: parts in order, hashed.
pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
let table = 0x20 + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
let mut out = Vec::with_capacity(total);
out.extend(b"DXBC");
out.extend([0; 16]);
out.extend(1u16.to_le_bytes());
out.extend(0u16.to_le_bytes());
out.extend((total as u32).to_le_bytes());
out.extend((parts.len() as u32).to_le_bytes());
let mut offset = table;
for (_, d) in parts {
out.extend((offset as u32).to_le_bytes());
offset += 8 + d.len();
}
for (fourcc, d) in parts {
out.extend(*fourcc);
out.extend((d.len() as u32).to_le_bytes());
out.extend(*d);
}
let digest = hash(&out[20..]);
out[4..20].copy_from_slice(&digest);
out
}
/// The container hash D3D12 checks: MD5 whose last block carries the bit
/// count first and `2 × bytes + 1` last instead of standard padding.
pub(crate) fn hash(data: &[u8]) -> [u8; 16] {
let len = data.len();
let left = len % 64;
let mut tail = Vec::with_capacity(128);
if left < 56 {
tail.extend(((len as u32) << 3).to_le_bytes());
tail.extend(&data[len - left..]);
tail.push(0x80);
tail.resize(60, 0);
} else {
tail.extend(&data[len - left..]);
tail.push(0x80);
tail.resize(64, 0);
tail.extend(((len as u32) << 3).to_le_bytes());
tail.resize(124, 0);
}
tail.extend(((len as u32) << 1 | 1).to_le_bytes());
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
for block in data[..len - left]
.as_chunks::<64>()
.0
.iter()
.chain(tail.as_chunks::<64>().0)
{
md5_block(&mut state, block);
}
let mut out = [0; 16];
for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) {
o.copy_from_slice(&s.to_le_bytes());
}
out
}
fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
let x: Vec<u32> = block
.as_chunks::<4>()
.0
.iter()
.map(|c| u32::from_le_bytes(*c))
.collect();
let [mut a, mut b, mut c, mut d] = *state;
for i in 0..64 {
let (f, g) = match i / 16 {
0 => ((b & c) | (!b & d), i),
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
2 => (b ^ c ^ d, (3 * i + 5) % 16),
_ => (c ^ (b | !d), (7 * i) % 16),
};
let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32;
let rotated = a
.wrapping_add(f)
.wrapping_add(k)
.wrapping_add(x[g])
.rotate_left(S[(i / 16) * 4 + i % 4]);
(a, b, c, d) = (d, b.wrapping_add(rotated), b, c);
}
for (s, v) in state.iter_mut().zip([a, b, c, d]) {
*s = s.wrapping_add(v);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn md5_core_matches_the_standard() {
// Standard MD5 of "abc" with standard padding, through md5_block.
let mut block = b"abc".to_vec();
block.push(0x80);
block.resize(56, 0);
block.extend(24u64.to_le_bytes());
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
md5_block(&mut state, block.as_slice().try_into().unwrap());
let hex: String = state
.iter()
.flat_map(|s| s.to_le_bytes())
.map(|b| format!("{b:02x}"))
.collect();
assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72");
}
}
File diff suppressed because it is too large. Load diff
+411
View File
@@ -0,0 +1,411 @@
//! 64-bit floating point by integer operations: the host (D3DMetal, Metal) has no fp64, and the
//! console's shaders use a little of it (`v_cvt_f32_f64` of a constant stored as a double,
//! `v_add_f64` sums). The algorithms are written once over [`Ops`], on values that are 64-bit
//! integers, and run on the IR builder in the lowering and on `u64` in the tests, where they are
//! checked against the CPU's own `f64`.
//!
//! Round-to-nearest-even throughout, denormals included (the f32 result of a conversion may be
//! one too).
/// What the algorithms need: 64-bit integer values and conditions. Shifts are by amounts below 64.
pub(crate) trait Ops {
type V: Copy;
type C: Copy;
fn k(&mut self, v: u64) -> Self::V;
fn and(&mut self, a: Self::V, b: Self::V) -> Self::V;
fn or(&mut self, a: Self::V, b: Self::V) -> Self::V;
#[allow(dead_code)]
fn xor(&mut self, a: Self::V, b: Self::V) -> Self::V;
fn add(&mut self, a: Self::V, b: Self::V) -> Self::V;
fn sub(&mut self, a: Self::V, b: Self::V) -> Self::V;
fn shl(&mut self, a: Self::V, by: Self::V) -> Self::V;
fn lshr(&mut self, a: Self::V, by: Self::V) -> Self::V;
fn eq(&mut self, a: Self::V, b: Self::V) -> Self::C;
fn ne(&mut self, a: Self::V, b: Self::V) -> Self::C;
/// Unsigned a < b.
fn ult(&mut self, a: Self::V, b: Self::V) -> Self::C;
/// Signed a >= b.
fn sge(&mut self, a: Self::V, b: Self::V) -> Self::C;
fn sel(&mut self, c: Self::C, a: Self::V, b: Self::V) -> Self::V;
}
fn kshl<O: Ops>(o: &mut O, a: O::V, n: u64) -> O::V {
let n = o.k(n);
o.shl(a, n)
}
fn klshr<O: Ops>(o: &mut O, a: O::V, n: u64) -> O::V {
let n = o.k(n);
o.lshr(a, n)
}
fn kn_plus_one<O: Ops>(o: &mut O, n: u64) -> O::V {
o.k(n + 1)
}
fn kand<O: Ops>(o: &mut O, a: O::V, m: u64) -> O::V {
let m = o.k(m);
o.and(a, m)
}
/// `v_cvt_f32_f64`: the f32 bits (in the low 32 bits of the result) of the double `b`.
pub(crate) fn cvt_f32_f64<O: Ops>(o: &mut O, b: O::V) -> O::V {
let sign = klshr(o, b, 63);
let e = klshr(o, b, 52);
let e = kand(o, e, 0x7ff);
let m = kand(o, b, (1 << 52) - 1);
let (zero, one) = (o.k(0), o.k(1));
// infinity and NaN (a quiet NaN with the payload's top bits)
let payload = klshr(o, m, 29);
let qnan = o.k(0x40_0000);
let payload = o.or(payload, qnan);
let m_zero = o.eq(m, zero);
let payload = o.sel(m_zero, zero, payload);
let inf = o.k(0x7f80_0000);
let special = o.or(inf, payload);
// normal results
let bias = o.k(896); // 1023 - 127
let ee = o.sub(e, bias);
let rem = kand(o, m, 0x1fff_ffff);
let q = klshr(o, m, 29);
let half = o.k(1 << 28);
let above = o.ult(half, rem);
let tie = o.eq(rem, half);
let odd = o.and(q, one);
let up_tie = o.sel(tie, odd, zero);
let up = o.sel(above, one, up_tie);
let ee23 = kshl(o, ee, 23);
let normal = o.add(ee23, q);
let normal = o.add(normal, up);
// results below the smallest normal
let implicit = o.k(1 << 52);
let mant = o.or(m, implicit);
let thirty = o.k(30);
let raw = o.sub(thirty, ee);
let sixty3 = o.k(63);
let too_far = o.ult(sixty3, raw); // raw > 63, or negative (huge)
let raw = o.sel(too_far, sixty3, raw);
let ee_pos = o.sge(ee, one);
let s = o.sel(ee_pos, thirty, raw);
let q2 = o.lshr(mant, s);
let mask = o.shl(one, s);
let mask = o.sub(mask, one);
let rem2 = o.and(mant, mask);
let sm1 = o.sub(s, one);
let half2 = o.shl(one, sm1);
let above2 = o.ult(half2, rem2);
let tie2 = o.eq(rem2, half2);
let odd2 = o.and(q2, one);
let up_tie2 = o.sel(tie2, odd2, zero);
let up2 = o.sel(above2, one, up_tie2);
let denormal = o.add(q2, up2);
// choose
let k255 = o.k(255);
let big = o.sge(ee, k255);
let mag = o.sel(ee_pos, normal, denormal);
let mag = o.sel(big, inf, mag);
let e_zero = o.eq(e, zero);
let mag = o.sel(e_zero, zero, mag);
let k7ff = o.k(0x7ff);
let e_all = o.eq(e, k7ff);
let mag = o.sel(e_all, special, mag);
let sign = kshl(o, sign, 31);
o.or(sign, mag)
}
/// `v_add_f64`: the bits of `a + b` for the doubles `a` and `b`.
pub(crate) fn add_f64<O: Ops>(o: &mut O, a: O::V, b: O::V) -> O::V {
let (zero, one) = (o.k(0), o.k(1));
let magnitude = |o: &mut O, x: O::V| kand(o, x, (1 << 63) - 1);
let (ma, mb) = (magnitude(o, a), magnitude(o, b));
// `big` has the larger magnitude
let swap = o.ult(ma, mb);
let big = o.sel(swap, b, a);
let small = o.sel(swap, a, b);
let parts = |o: &mut O, x: O::V| {
let s = klshr(o, x, 63);
let e = klshr(o, x, 52);
let e = kand(o, e, 0x7ff);
let m = kand(o, x, (1 << 52) - 1);
(s, e, m)
};
let (sb, eb0, mb_) = parts(o, big);
let (ss, es0, ms_) = parts(o, small);
let k7ff = o.k(0x7ff);
// 53-bit significands (a denormal has no implicit bit and the exponent 1)
let implicit = o.k(1 << 52);
let sig = |o: &mut O, e: O::V, m: O::V| {
let full = o.or(m, implicit);
let z = o.k(0);
let is0 = o.eq(e, z);
o.sel(is0, m, full)
};
let (mant_b, mant_s) = (sig(o, eb0, mb_), sig(o, es0, ms_));
let eff = |o: &mut O, e: O::V| {
let z = o.k(0);
let one = o.k(1);
let is0 = o.eq(e, z);
o.sel(is0, one, e)
};
let (eb, es) = (eff(o, eb0), eff(o, es0));
// three extra low bits (guard, round, sticky)
let mant_b = kshl(o, mant_b, 3);
let mant_s = kshl(o, mant_s, 3);
// align the smaller one
let d = o.sub(eb, es);
let sixty3 = o.k(63);
let far = o.ult(sixty3, d);
let sh = o.sel(far, sixty3, d);
let shifted = o.lshr(mant_s, sh);
let mask = o.shl(one, sh);
let mask = o.sub(mask, one);
let lost = o.and(mant_s, mask);
let lost = o.ne(lost, zero);
let sticky = o.sel(lost, one, zero);
let shifted = o.or(shifted, sticky);
// add or subtract
let same = o.eq(sb, ss);
let sum = o.add(mant_b, shifted);
let diff = o.sub(mant_b, shifted);
let mut v = o.sel(same, sum, diff);
let mut e = eb;
// carry out: bit 56
let top = o.k(1 << 56);
let carry = o.and(v, top);
let carried = o.ne(carry, zero);
let lowbit = o.and(v, one);
let halved = klshr(o, v, 1);
let halved = o.or(halved, lowbit);
v = o.sel(carried, halved, v);
let e_plus = o.add(e, one);
e = o.sel(carried, e_plus, e);
// cancellation: shift left until bit 55 is set
for n in [32u64, 16, 8, 4, 2, 1] {
// the top n bits below bit 56: bits 55 down to 56 - n
let ones = (1u64 << n) - 1;
let field = ones << (56 - n);
let top_bits = kand(o, v, field);
let empty = o.eq(top_bits, zero);
let nonzero = o.ne(v, zero);
let kn = o.k(n);
let shift = o.sel(empty, kn, zero);
let shift = o.sel(nonzero, shift, zero);
// not below the exponent 1: the result is then a denormal
let np1 = kn_plus_one(o, n);
let allowed = o.sge(e, np1);
let shift = o.sel(allowed, shift, zero);
v = o.shl(v, shift);
e = o.sub(e, shift);
}
// round to nearest even
let low = kand(o, v, 7);
let m = klshr(o, v, 3);
let k4 = o.k(4);
let above = o.ult(k4, low);
let tie = o.eq(low, k4);
let odd = o.and(m, one);
let up_tie = o.sel(tie, odd, zero);
let up = o.sel(above, one, up_tie);
let m = o.add(m, up);
// (exponent - 1) << 52 plus the significand with its hidden bit: a carry out of the
// significand, and a denormal that rounds up to the smallest normal, add to the exponent
let e_minus = o.sub(e, one);
let e_field = kshl(o, e_minus, 52);
let bits = o.add(e_field, m);
let sign = kshl(o, sb, 63);
let inf_mag = o.k(0x7ff0_0000_0000_0000);
let overflow = o.ult(bits, inf_mag);
let mag = o.sel(overflow, bits, inf_mag);
let finite = o.or(sign, mag);
// exact cancellation: +0, or -0 for two negative zeros
let result_zero = o.eq(v, zero);
let neg_zero = o.sel(same, sign, zero);
let r = o.sel(result_zero, neg_zero, finite);
// infinities and NaNs
let a_all = {
let ea = {
let t = klshr(o, a, 52);
kand(o, t, 0x7ff)
};
o.eq(ea, k7ff)
};
let b_all = {
let eb2 = {
let t = klshr(o, b, 52);
kand(o, t, 0x7ff)
};
o.eq(eb2, k7ff)
};
let a_m = kand(o, a, (1 << 52) - 1);
let b_m = kand(o, b, (1 << 52) - 1);
let a_nan = {
let nz = o.ne(a_m, zero);
let x = o.sel(nz, one, zero);
o.sel(a_all, x, zero)
};
let b_nan = {
let nz = o.ne(b_m, zero);
let x = o.sel(nz, one, zero);
o.sel(b_all, x, zero)
};
let nan_bits = o.k(0x7ff8_0000_0000_0000);
let any_nan = o.or(a_nan, b_nan);
let any_nan = o.ne(any_nan, zero);
// a (or b) is an infinity: the result is that infinity, a NaN if the other is the opposite one
let a_inf = a_all;
let b_inf = b_all;
let (sa, sb2) = (klshr(o, a, 63), klshr(o, b, 63));
let signs_differ = o.ne(sa, sb2);
let both_inf = {
let x = o.sel(a_inf, one, zero);
let y = o.sel(b_inf, one, zero);
let z = o.and(x, y);
o.ne(z, zero)
};
let inf_nan = {
let x = o.sel(both_inf, one, zero);
let y = o.sel(signs_differ, one, zero);
let z = o.and(x, y);
o.ne(z, zero)
};
let r = o.sel(b_inf, b, r);
let r = o.sel(a_inf, a, r);
let nan_case = {
let x = o.sel(any_nan, one, zero);
let y = o.sel(inf_nan, one, zero);
let z = o.or(x, y);
o.ne(z, zero)
};
o.sel(nan_case, nan_bits, r)
}
#[cfg(test)]
mod tests {
use super::*;
/// The algorithms on `u64`.
struct Native;
impl Ops for Native {
type V = u64;
type C = bool;
fn k(&mut self, v: u64) -> u64 { v }
fn and(&mut self, a: u64, b: u64) -> u64 { a & b }
fn or(&mut self, a: u64, b: u64) -> u64 { a | b }
fn xor(&mut self, a: u64, b: u64) -> u64 { a ^ b }
fn add(&mut self, a: u64, b: u64) -> u64 { a.wrapping_add(b) }
fn sub(&mut self, a: u64, b: u64) -> u64 { a.wrapping_sub(b) }
fn shl(&mut self, a: u64, by: u64) -> u64 { assert!(by < 64, "shift by {by}"); a << by }
fn lshr(&mut self, a: u64, by: u64) -> u64 { assert!(by < 64, "shift by {by}"); a >> by }
fn eq(&mut self, a: u64, b: u64) -> bool { a == b }
fn ne(&mut self, a: u64, b: u64) -> bool { a != b }
fn ult(&mut self, a: u64, b: u64) -> bool { a < b }
fn sge(&mut self, a: u64, b: u64) -> bool { a as i64 >= b as i64 }
fn sel(&mut self, c: bool, a: u64, b: u64) -> u64 { if c { a } else { b } }
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
fn cvt(x: f64) -> u32 {
cvt_f32_f64(&mut Native, x.to_bits()) as u32
}
fn same_f32(got: u32, want: f32) -> bool {
if want.is_nan() {
f32::from_bits(got).is_nan()
} else {
got == want.to_bits()
}
}
#[test]
#[allow(clippy::approx_constant)] // 3.14159265358979 is a test value, not the constant
fn f32_from_f64_edges() {
let cases = [
0.0, -0.0, 1.0, -1.0, 0.5, 3.14159265358979, 1e-10, 1e10, 1e38, 3.4028234663852886e38, 3.4028235677973366e38,
3.4028236e38, 1e39, -1e39, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 1e-38, 1.1754943508222875e-38, 1e-40,
1.4e-45, 7e-46, 7.006492321624085e-46, 7.006492321624086e-46, 1e-50, 5e-324, 2.2250738585072014e-308,
// ties: 1 + 2^-24 (halfway between two f32), and just above and below
1.0 + 2f64.powi(-24), 1.0 + 2f64.powi(-24) + 2f64.powi(-40), 1.0 + 3.0 * 2f64.powi(-24),
16777217.0, 16777219.0, 8388609.5,
];
for x in cases {
let got = cvt(x);
assert!(same_f32(got, x as f32), "{x:e}: got {got:#010x}, want {:#010x}", (x as f32).to_bits());
}
}
#[test]
fn f32_from_f64_random() {
let mut r = Rng(0x1234_5678_9abc_def1);
for i in 0..400_000u32 {
let bits = r.next();
// spread over exponents near the f32 range as well as everywhere
let bits = if i % 2 == 0 { bits } else { (bits & !(0x7ff << 52)) | ((896 - 30 + (r.next() % 330)) << 52) };
let x = f64::from_bits(bits);
let got = cvt(x);
assert!(same_f32(got, x as f32), "{bits:#018x} {x:e}: got {got:#010x}, want {:#010x}", (x as f32).to_bits());
}
}
fn add(a: f64, b: f64) -> u64 {
add_f64(&mut Native, a.to_bits(), b.to_bits())
}
fn same_f64(got: u64, want: f64) -> bool {
let g = f64::from_bits(got);
if want.is_nan() {
g.is_nan()
} else {
got == want.to_bits()
}
}
#[test]
fn f64_sums_edges() {
let vals = [
0.0, -0.0, 1.0, -1.0, 0.5, 3.0, -3.0, 1e300, -1e300, 1.7976931348623157e308, 2.0f64.powi(-1022), 1.5,
5e-324, -5e-324, 2.2250738585072014e-308, 1.0 + f64::EPSILON, 1.0 - f64::EPSILON / 2.0, 1e-300, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 123456.789, 2f64.powi(53),
2f64.powi(53) + 2.0, 4.0 / 3.0,
];
for a in vals {
for b in vals {
let got = add(a, b);
assert!(same_f64(got, a + b), "{a:e} + {b:e}: got {:e} ({got:#x}), want {:e} ({:#x})", f64::from_bits(got), a + b, (a + b).to_bits());
}
}
// signed zeros
assert_eq!(add(-0.0, -0.0), (-0.0f64).to_bits());
assert_eq!(add(0.0, -0.0), 0.0f64.to_bits());
assert_eq!(add(1.0, -1.0), 0.0f64.to_bits());
}
#[test]
fn f64_sums_random() {
let mut r = Rng(0x9e37_79b9_7f4a_7c15);
for i in 0..400_000u32 {
let (mut x, mut y) = (r.next(), r.next());
// exponents within a few bits of each other make cancellation and carries common
if i % 3 != 0 {
let e = 1000 + (r.next() % 50);
x = (x & !(0x7ff << 52)) | (e << 52);
y = (y & !(0x7ff << 52)) | ((e + (r.next() % 4) - 1) << 52);
}
if i % 7 == 0 {
// a nearly cancelling pair
y = x ^ (1 << 63) ^ (r.next() & 0xfff);
}
let (a, b) = (f64::from_bits(x), f64::from_bits(y));
let got = add(a, b);
assert!(same_f64(got, a + b), "{x:#018x} + {y:#018x}: got {got:#018x}, want {:#018x}", (a + b).to_bits());
}
}
}
File diff suppressed because it is too large. Load diff
+557
View File
@@ -0,0 +1,557 @@
//! The console's ray-tracing node test, `image_bvh_intersect_ray` and
//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction
//! that tests one ray against one node of the title's own structures.
//!
//! [`crate::bvh`] says what the instruction computes and is the reference:
//! the code made here does the same float operations in the same order
//! (DXIL float operations carry no fast-math flags, so the host may not
//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on
//! the card against the reference.
//!
//! The title's nodes are in title memory, named by address: they are read
//! through the host's copies of title memory ([`Lower::memory`]), one look
//! in its directory per node (two for a 128-byte box node).
//!
//! Shape of the code, under the instruction's lane guard:
//!
//! ```text
//! kind = pointer & 7
//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4);
//! four slab tests; the sorting network
//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test
//! other (6, 7): a triangle miss
//! ```
//!
//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit
//! box node, 16 for a 16-bit one, 10 for a triangle.
use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred};
use crate::bvh;
use crate::resource::BvhNodes;
#[cfg(test)]
thread_local! {
/// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a
/// heap slot holding a raw buffer, and the title address of its first
/// byte. (The card tests have no host to keep copies of title memory
/// and their directory.)
pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> =
const { std::cell::Cell::new(None) };
}
/// Where the instruction's node is.
#[derive(Clone, Copy)]
enum NodeAt {
/// At this byte of a raw buffer of the host.
Buffer { handle: V, byte: V },
/// In title memory: the raw view of the host copy holding the node's
/// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
/// and the node's address, for the second half of a 128-byte node.
Memory { handle: V, byte: V, low: V, high: V },
}
/// The ray operands, as floats.
struct Ray {
extent: V,
origin: [V; 3],
direction: [V; 3],
inverse: [V; 3],
}
impl<'a> Lower<'a> {
/// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`.
pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
let Fields::Image {
data,
addr,
rsrc,
dmask,
a16,
d16,
tfe,
lwe,
..
} = &inst.fields
else {
unreachable!()
};
if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf {
return Err("a ray-tracing node test with 16-bit operands or a partial result");
}
let wide = inst.name() == "image_bvh64_intersect_ray";
// Operand VGPRs in order: the node pointer (two dwords in the
// 64-bit form), the ray's extent, origin, direction and inverse
// direction.
let mut regs = Vec::new();
for a in addr {
if let Operand::Vector { reg, dwords } = *a {
regs.extend((0..dwords).map(|k| reg + k));
}
}
if regs.len() != if wide { 12 } else { 11 } {
return Err("a ray-tracing node test's operands");
}
let Operand::Vector { reg: dst, .. } = *data else {
return Err("a ray-tracing node test's result");
};
let site = (b, i);
let nodes = self
.x
.res
.bvh
.iter()
.find(|n| n.0 == site)
.map(|n| n.1)
.ok_or("an untracked ray-tracing structure")?;
let (sort, barycentrics) = match nodes {
BvhNodes::Resource => (true, true),
BvhNodes::Memory { word1, word3 } => (
word1 & bvh::BOX_SORT != 0,
word3 & bvh::RETURN_BARYCENTRICS != 0,
),
};
if !barycentrics {
// Mode 0 returns a triangle id and a hit status in the last two
// dwords; no program of the title asks for it.
return Err("a ray-tracing structure that returns triangle ids");
}
let guard = self.guard(b, i)?;
let mut x = Vec::with_capacity(regs.len());
for &r in &regs {
let v = inst.read(Reg::V(r)).ok_or("an unread operand")?;
x.push(self.i32_of(v)?);
}
let pointer = x[0];
let pointer_high = wide.then(|| x[1]);
let f: Vec<V> = x[1 + usize::from(wide)..]
.iter()
.map(|&v| self.as_float(v))
.collect();
let ray = Ray {
extent: f[0],
origin: [f[1], f[2], f[3]],
direction: [f[4], f[5], f[6]],
inverse: [f[7], f[8], f[9]],
};
let c = self.cur;
let at = match nodes {
BvhNodes::Resource => {
let src = self
.descriptors
.get(&(site, false))
.copied()
.ok_or("an untracked ray-tracing structure")?;
let handle = self.handle(site, src, false, (11, 0))?;
// (pointer >> 3) << 6 from the buffer's start.
let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3));
let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits);
let byte = self.s.m.bin(c, Bin::Shl, byte, k3);
NodeAt::Buffer { handle, byte }
}
BvhNodes::Memory { .. } => {
let Operand::Scalar { code, .. } = *rsrc else {
return Err("a ray-tracing structure descriptor not in SGPRs");
};
let mut words = [pointer; 2];
for (k, w) in words.iter_mut().enumerate() {
let v = inst
.read(Reg::S(code + k as u8))
.ok_or("an unread operand")?;
*w = self.i32_of(v)?;
}
let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high);
// One look for the node's copy, before the branches: a
// node is 64 bytes on 64, so its first half lies in one
// 64 KiB page whatever its kind.
let (handle, byte) = self.bvh_memory(low, high, guard);
NodeAt::Memory {
handle,
byte,
low,
high,
}
}
};
let zero = self.s.m.i32(0);
let gate = self.begin_guarded(guard);
let head = self.cur;
let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7));
let kind = self.s.m.bin(head, Bin::And, pointer, k7);
let pair = self.s.m.bin(head, Bin::And, pointer, k6);
let is_box = self.s.m.cmp(head, pred::EQ, pair, k4);
let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4);
let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block());
let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block());
self.s
.m
.terminate(head, Term::CondBr(is_box, box_block, leaf_block));
self.s
.m
.terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
self.cur = box_block;
let boxes = self.bvh_boxes(at, kind, &ray, sort);
let box_end = self.cur;
self.s.m.terminate(box_end, Term::Br(join));
self.cur = triangle_block;
let triangle = self.bvh_triangle(at, kind, &ray);
let triangle_end = self.cur;
self.s.m.terminate(triangle_end, Term::Br(join));
self.cur = join;
// Kinds 6 and 7 (an instance, a procedural primitive): not known
// what the console returns; the title's programs do not read it.
let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits()));
let i32t = self.s.t.i32;
let mut results = Vec::with_capacity(4);
for k in 0..4 {
let phi = self.s.m.phi(join, i32t);
self.s.m.set_phi(
phi,
vec![
(boxes[k], box_end),
(triangle[k], triangle_end),
(other[k], leaf_block),
],
);
results.push((phi, zero));
}
let results = self.end_guarded(gate, &results);
for (k, &r) in results.iter().enumerate() {
self.write(inst, Reg::V(dst + k as u8), r, guard);
}
Ok(())
}
/// Title memory at `low`/`high` for a node's bytes: the raw view of the
/// host copy holding the address and the byte in that view
/// ([`Lower::memory`]: a page the host has no copy of reads zeros and
/// is left for the host to fetch, for lanes that run).
fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) {
#[cfg(test)]
if let Some((slot, base)) = TEST_MEMORY.get() {
// The buffer at heap slot `slot` holds the bytes from title
// address `base` on; any other address reads past its end,
// which is zeros.
let c = self.cur;
let slot = self.s.m.i32(slot);
let handle = self.s.heap_handle(c, slot, false, false, (11, 0));
let (base_low, base_high) =
(self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32));
let at = self.s.m.bin(c, Bin::Sub, low, base_low);
let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low);
let in_high = self.s.m.cmp(c, pred::EQ, high, base_high);
let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
let outside = self.s.m.i32(0xffff_ff00);
let at = self.s.m.select(c, inside, at, outside);
return (handle, at);
}
self.memory(low, high, guard)
}
/// `count` dwords of the node from its byte `base` + `offset` (`base`
/// computed, `offset` fixed; none of the node's bytes past 127), read
/// four at a time.
fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
let c = self.cur;
let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
// The second half of a 128-byte node may lie in the next 64 KiB
// page, which may be in another copy: its own look, made once.
let mut second = None;
let mut out = Vec::with_capacity(count as usize);
for start in (0..count).step_by(4) {
let n = (count - start).min(4);
let node_byte = offset + 4 * start;
let (handle, mut byte) = match at {
NodeAt::Buffer { handle, byte } => (handle, byte),
NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte),
NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| {
let (low, high) = self.address_plus(low, high, 64);
// Every lane in this block runs the instruction.
let (handle, byte) = self.bvh_memory(low, high, None);
let k64 = self.s.m.i32(64);
(handle, self.s.m.bin(c, Bin::Sub, byte, k64))
}),
};
if let Some(b) = base {
byte = self.s.m.bin(c, Bin::Add, byte, b);
}
let k = self.s.m.i32(node_byte);
let byte = self.s.m.bin(c, Bin::Add, byte, k);
let mask = self.s.m.i8((1u8 << n) - 1);
let r = self.s.op(
c,
"rawBufferLoad.f32",
Attr::ReadOnly,
self.s.t.res_ret,
139,
&[handle, byte, undef, mask, align],
);
for k in 0..n {
let f = self.s.m.extract(c, r, k);
out.push(self.as_int(f));
}
}
out
}
/// The node's title address, [`bvh::node_address`]: the descriptor's
/// base (dword 0 and the low byte of dword 1, in 256-byte units) plus
/// `(pointer >> 3) << 6`.
fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) {
let c = self.cur;
let i64t = self.s.m.int(64);
let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff));
let base_high = self.s.m.bin(c, Bin::And, word1, byte);
let base = self.join64(word0, base_high);
let k8 = self.s.m.int_const(i64t, 8);
let base = self.s.m.bin(c, Bin::Shl, base, k8);
let p = self.join64(pointer, pointer_high.unwrap_or(zero));
let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6));
let p = self.s.m.bin(c, Bin::LShr, p, k3);
let p = self.s.m.bin(c, Bin::Shl, p, k6);
let a = self.s.m.bin(c, Bin::Add, base, p);
self.s.flags |= flags::INT64;
self.split64(a)
}
/// The box test ([`bvh::boxes`]): four result dwords. Starts in the
/// current block and leaves `self.cur` at the block it ends in.
fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] {
let head = self.cur;
let children = self.bvh_node_words(at, None, 0, 4);
let k5 = self.s.m.i32(5);
let wide = self.s.m.cmp(head, pred::EQ, kind, k5);
let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block());
let join = self.s.m.new_block();
self.s
.m
.terminate(head, Term::CondBr(wide, wide_block, half_block));
// 32-bit floats: 24 dwords from byte 16.
self.cur = wide_block;
let k16 = self.s.m.i32(16);
let words = self.bvh_node_words(at, None, 16, 24);
let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
self.s.m.terminate(wide_block, Term::Br(join));
// 16-bit floats: 24 halves in 12 dwords from byte 16, the low half
// of a dword first.
self.cur = half_block;
let words = self.bvh_node_words(at, None, 16, 12);
let f32t = self.s.t.f32;
let mut halves = Vec::with_capacity(24);
for n in 0..24 {
let mut h = words[n / 2];
if n % 2 == 1 {
h = self.s.m.bin(half_block, Bin::LShr, h, k16);
}
// The conversion reads the low 16 bits.
halves.push(self.s.op(
half_block,
"legacyF16ToF32",
Attr::ReadNone,
f32t,
131,
&[h],
));
}
self.s.m.terminate(half_block, Term::Br(join));
self.cur = join;
let mut coords = Vec::with_capacity(24);
for n in 0..24 {
let phi = self.s.m.phi(join, f32t);
self.s
.m
.set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]);
coords.push(phi);
}
// The inverse direction held finite ([`bvh::boxes`]).
let (most, least) = (
self.s.m.f32(f32::MAX.to_bits()),
self.s.m.f32((-f32::MAX).to_bits()),
);
let inverse = ray.inverse.map(|x| {
let x = self.binary(35, x, least);
self.binary(36, x, most)
});
let c = join;
let (none, infinity, fzero) = (
self.s.m.i32(bvh::NONE),
self.s.m.f32(f32::INFINITY.to_bits()),
self.s.m.f32(0),
);
let mut ids = [none; 4];
let mut distances = [infinity; 4];
for n in 0..4 {
let bx = &coords[6 * n..6 * n + 6];
let (mut near, mut far) = ([fzero; 3], [fzero; 3]);
for a in 0..3 {
let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]);
let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]);
let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]);
let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]);
near[a] = self.binary(36, low, high);
far[a] = self.binary(35, low, high);
}
let enter = self.binary(35, near[0], near[1]);
let enter = self.binary(35, enter, near[2]);
let leave = self.binary(36, far[0], far[1]);
let leave = self.binary(36, leave, far[2]);
let from = self.binary(35, enter, fzero);
// Ordered compares: a NaN anywhere is a miss.
let through = self.s.m.cmp(c, pred::OGE, leave, from);
let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent);
let off = self.is_nan_f32(bx[0]);
let on = self.s.m.bool(true);
let on = self.s.m.bin(c, Bin::Xor, off, on);
let hit = self.s.m.bin(c, Bin::And, through, before);
let hit = self.s.m.bin(c, Bin::And, hit, on);
ids[n] = self.s.m.select(c, hit, children[n], none);
distances[n] = self.s.m.select(c, hit, enter, infinity);
}
if sort {
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]);
let (da, db) = (distances[a], distances[b]);
distances[a] = self.s.m.select(c, swap, db, da);
distances[b] = self.s.m.select(c, swap, da, db);
let (ia, ib) = (ids[a], ids[b]);
ids[a] = self.s.m.select(c, swap, ib, ia);
ids[b] = self.s.m.select(c, swap, ia, ib);
}
}
ids
}
/// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]):
/// four result dwords, made in the current block.
fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] {
let c = self.cur;
let k = |l: &mut Self, v: u32| l.s.m.i32(v);
// The triangle's byte of the dword at byte 60: which of its
// vertices barycentric I and J weigh.
let id = self.bvh_node_words(at, None, 60, 1)[0];
let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15));
let shift = self.s.m.bin(c, Bin::Shl, kind, k3);
let id = self.s.m.bin(c, Bin::LShr, id, shift);
let i = self.s.m.bin(c, Bin::And, id, k3);
let j = self.s.m.bin(c, Bin::LShr, id, k2);
let j = self.s.m.bin(c, Bin::And, j, k3);
let first = self.s.m.bin(c, Bin::Sub, k3, i);
let first = self.s.m.bin(c, Bin::Sub, first, j);
let first = self.s.m.bin(c, Bin::And, first, k3);
// The node's vertices the triangle is made of, four bits each.
let (k0, k1) = (k(self, 0), k(self, 1));
let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32)));
let (is0, is1, is2) = (
self.s.m.cmp(c, pred::EQ, kind, k0),
self.s.m.cmp(c, pred::EQ, kind, k1),
self.s.m.cmp(c, pred::EQ, kind, k2),
);
let map = self.s.m.select(c, is2, maps[2], maps[3]);
let map = self.s.m.select(c, is1, maps[1], map);
let map = self.s.m.select(c, is0, maps[0], map);
let mut p = Vec::with_capacity(3);
for n in [first, i, j] {
let nibble = self.s.m.bin(c, Bin::Shl, n, k2);
let vertex = self.s.m.bin(c, Bin::LShr, map, nibble);
let vertex = self.s.m.bin(c, Bin::And, vertex, k15);
let byte = self.s.m.bin(c, Bin::Mul, vertex, k12);
let words = self.bvh_node_words(at, Some(byte), 0, 3);
// Relative to the ray's origin.
let r: Vec<V> = (0..3)
.map(|a| {
let f = self.as_float(words[a]);
self.s.m.bin(c, Bin::Sub, f, ray.origin[a])
})
.collect();
p.push([r[0], r[1], r[2]]);
}
// The ray's largest axis z, and x and y after it in an order that
// keeps the winding.
let fzero = self.s.m.f32(0);
let size = ray.direction.map(|d| self.unary(6, d));
let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]);
let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]);
let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]);
let z0 = self.s.m.bin(c, Bin::And, xy, xz);
let on = self.s.m.bool(true);
let not_xy = self.s.m.bin(c, Bin::Xor, xy, on);
let z1 = self.s.m.bin(c, Bin::And, not_xy, yz);
// Component (kz + n) % 3 of `q`.
let pick = |l: &mut Self, q: [V; 3], n: usize| {
let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]);
l.s.m.select(c, z0, q[n % 3], rest)
};
let dz = pick(self, ray.direction, 0);
let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero);
// (x, y, z) of `q`: the two after the largest axis, swapped for a
// ray that runs backwards along it.
let axes = |l: &mut Self, q: [V; 3]| {
let (x, y) = (pick(l, q, 1), pick(l, q, 2));
[
l.s.m.select(c, backwards, y, x),
l.s.m.select(c, backwards, x, y),
pick(l, q, 0),
]
};
let d = axes(self, ray.direction);
let sz = pick(self, ray.inverse, 0);
let sx = self.s.m.bin(c, Bin::Mul, d[0], sz);
let sy = self.s.m.bin(c, Bin::Mul, d[1], sz);
let mut sheared = Vec::with_capacity(3);
for r in p {
let r = axes(self, r);
let x = self.s.m.bin(c, Bin::Mul, sx, r[2]);
let x = self.s.m.bin(c, Bin::Sub, r[0], x);
let y = self.s.m.bin(c, Bin::Mul, sy, r[2]);
let y = self.s.m.bin(c, Bin::Sub, r[1], y);
let z = self.s.m.bin(c, Bin::Mul, sz, r[2]);
sheared.push((x, y, z));
}
let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else {
unreachable!()
};
// p * q - r * s.
let cross = |l: &mut Self, p: V, q: V, r: V, s: V| {
let a = l.s.m.bin(c, Bin::Mul, p, q);
let b = l.s.m.bin(c, Bin::Mul, r, s);
l.s.m.bin(c, Bin::Sub, a, b)
};
let u = cross(self, cx, by, cy, bx);
let v = cross(self, ax, cy, ay, cx);
let w = cross(self, bx, ay, by, ax);
let any = |l: &mut Self, p: u8| {
let a = l.s.m.cmp(c, p, u, fzero);
let b = l.s.m.cmp(c, p, v, fzero);
let d = l.s.m.cmp(c, p, w, fzero);
let a = l.s.m.bin(c, Bin::Or, a, b);
l.s.m.bin(c, Bin::Or, a, d)
};
let behind = any(self, pred::OLT);
let before = any(self, pred::OGT);
let outside = self.s.m.bin(c, Bin::And, behind, before);
let inside = self.s.m.bin(c, Bin::Xor, outside, on);
let det = self.s.m.bin(c, Bin::Add, v, w);
let det = self.s.m.bin(c, Bin::Add, u, det);
let t = self.s.m.bin(c, Bin::Mul, u, az);
let t2 = self.s.m.bin(c, Bin::Mul, v, bz);
let t = self.s.m.bin(c, Bin::Add, t, t2);
let t2 = self.s.m.bin(c, Bin::Mul, w, cz);
let t = self.s.m.bin(c, Bin::Add, t, t2);
// The distance is not negative: the numerator has the
// denominator's sign (or is 0). Ordered compares: a denominator
// of 0 or a NaN is a miss.
let front = self.s.m.cmp(c, pred::OGT, det, fzero);
let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero);
let front = self.s.m.bin(c, Bin::And, front, front_ahead);
let back = self.s.m.cmp(c, pred::OLT, det, fzero);
let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero);
let back = self.s.m.bin(c, Bin::And, back, back_ahead);
let ahead = self.s.m.bin(c, Bin::Or, front, back);
let hit = self.s.m.bin(c, Bin::And, inside, ahead);
let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits()));
let out = [t, det, v, w];
std::array::from_fn(|n| {
let f = self.s.m.select(c, hit, out[n], miss[n]);
self.as_int(f)
})
}
}
@@ -0,0 +1,690 @@
//! The ray-tracing node test end to end: a synthetic compute program that
//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread,
//! lowered to DXIL, validated by `dxil.dll` when present, run on the host
//! GPU and WARP, and compared dword for dword with the CPU reference
//! ([`crate::bvh`]).
//!
//! The nodes are in a raw buffer. Two ways to name it are run: the
//! buffer's descriptor from the program's table (a resource of the host,
//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a
//! descriptor of numbers over title memory with the structure's address in
//! the node pointer or in the descriptor. These tests have no host that
//! keeps copies of title memory and their directory, so for the second
//! they put a stand-in under the node reader
//! (`lower::intersect::TEST_MEMORY`); without it the same program reads
//! through the directory, which is only checked to lower and validate.
use super::host::{Dispatch, Host, Root, Stride, View};
use super::lower::intersect::TEST_MEMORY;
use super::{HostShader, lower, validator};
use crate::bvh::{self, Ray, tests as nodes};
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
use crate::resource::BvhNodes;
use crate::{ShaderError, io, ir, resource, structure};
/// Threads of one group, each with its own record.
const THREADS: u32 = 32;
/// Bytes of a thread's record: the node pointer (two dwords), the ray's
/// extent, origin, direction and inverse direction, and whether the
/// thread runs the instruction.
const RECORD: u32 = 64;
/// Where the nodes start in the buffer.
const NODES: u32 = THREADS * RECORD;
/// What the result registers hold before the instruction.
const BEFORE: [u32; 4] = [1, 2, 3, 4];
/// How the program names the nodes' memory.
#[derive(Clone, Copy, PartialEq)]
enum Descriptor {
/// The buffer's descriptor from the table.
Table,
/// Numbers, as the title builds it: dwords 0 and 1 (the base address
/// in 256-byte units and the box sorting bit); the size and the rest of
/// the flags as the title sets them.
Numbers(u32, u32),
}
/// The descriptor the title builds for the 64-bit form: the whole address
/// space, sorted boxes, barycentrics returned.
const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT);
/// The program: per thread, the record's twelve operand dwords in v1-v12,
/// the instruction's result in v13-v16 (under a lane mask of the threads
/// whose record says so), stored to the UAV at 16 bytes a thread.
fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> {
let mut w = vec![
0xBE85_0380, // s_mov_b32 s5, 0
0xF408_0202,
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
0xF408_0302,
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
0x3428_0086, // v_lshlrev_b32 v20, 6, v0
0xE038_1000,
0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen
0xE038_1010,
0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16
0xE038_1020,
0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32
0xE030_1030,
0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48
];
for k in 0..4u32 {
// v_mov_b32 v13+k, 1+k
w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k));
}
let rsrc = match descriptor {
Descriptor::Table => 8,
Descriptor::Numbers(word0, word1) => {
// s_mov_b32 s24, word0
w.extend([0xBE98_03FF, word0]);
if word1 == bvh::BOX_SORT {
// As the title makes it.
w.push(0xBE99_0B81); // s_brev_b32 s25, 1
} else {
w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1
}
w.extend([
0xBE9A_03C1, // s_mov_b32 s26, -1
0xBE9B_03FF,
0x8900_03FF, // s_mov_b32 s27, 0x890003ff
]);
24
}
};
w.extend([
0xBE94_037E, // s_mov_b32 s20, exec_lo
0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17
]);
let first = 0x0000_0D01 | (rsrc >> 2) << 16;
if wide {
// image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3]
w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]);
} else {
// image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3]
w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]);
}
w.extend([
0xBEFE_0314, // s_mov_b32 exec_lo, s20
0x342A_0084, // v_lshlrev_b32 v21, 4, v0
0xE078_1000,
0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen
0xBF81_0000, // s_endpgm
]);
w
}
fn native(words: &[u32]) -> NativeProgram {
let table = |kind, at| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords: at,
lower_bound: 0,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
};
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 22,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [THREADS, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
}
}
/// Lowers the program; the DXIL is validated when the validator is there.
fn build(
wide: bool,
descriptor: Descriptor,
) -> Result<(HostShader, resource::Resources), ShaderError> {
let native = native(&program(wide, descriptor));
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
let io = io::raise(&p, &native).expect("io::raise");
let lowered = lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})?;
let shader = HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views.clone(),
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
Ok((shader, res))
}
/// One thread's test: a node (by its index in the node list), the kind its
/// pointer carries, and the ray; `None` leaves the thread masked out.
type Case = Option<(usize, u32, Ray)>;
/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and
/// where each node starts, in dwords from the first node.
struct Scene {
words: Vec<u32>,
starts: Vec<usize>,
}
impl Scene {
fn new() -> Self {
Self {
words: Vec::new(),
starts: Vec::new(),
}
}
/// Adds a node of `dwords` (16 or 32) and returns its index.
fn add(&mut self, node: [u32; 28], dwords: usize) -> usize {
self.starts.push(self.words.len());
let mut padded = [0u32; 32];
padded[..28].copy_from_slice(&node);
// Bytes the instruction must not read as part of the node: what
// follows a 64-byte node, and a box node's last 16 bytes.
for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) {
*w = 0x7fc0_dead;
}
self.words.extend(&padded[..dwords]);
self.starts.len() - 1
}
/// The pointer of node `n` with `kind`, counted from the first node.
fn pointer(&self, n: usize, kind: u32) -> u32 {
(4 * self.starts[n] as u32) >> 3 | kind
}
/// What the instruction reads of node `n`.
fn node(&self, n: usize) -> [u32; 28] {
std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0))
}
}
/// A small generator of repeatable numbers.
struct Numbers(u64);
impl Numbers {
fn next(&mut self) -> u32 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(self.0 >> 33) as u32
}
/// A float in -1..1 in steps of 1/4096 (exactly representable).
fn unit(&mut self) -> f32 {
(self.next() % 8193) as f32 / 4096.0 - 1.0
}
fn vector(&mut self, scale: f32) -> [f32; 3] {
[
self.unit() * scale,
self.unit() * scale,
self.unit() * scale,
]
}
}
/// The scene and batches of cases over it.
fn scene() -> (Scene, Vec<Vec<Case>>) {
let mut s = Scene::new();
let mut g = Numbers(0x5eed);
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
let moved =
|b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) };
let off = [f32::NAN; 6];
let mut box_nodes = Vec::new();
// The boxes of the reference's own tests, in both widths.
let lined = [
moved(UNIT, [30.0, 0.0, 0.0]),
moved(UNIT, [10.0, 0.0, 0.0]),
moved(UNIT, [10.0, 5.0, 0.0]),
moved(UNIT, [20.0, 0.0, 0.0]),
];
let ids = [0x105, 0x20c, 0x304, 0x400];
box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5));
box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4));
// Boxes around the origin, one switched off, one child missing.
let around = [
UNIT,
moved(UNIT, [0.5, 0.5, 0.5]),
off,
[-4.0, -0.25, -0.25, 4.0, 0.25, 0.25],
];
let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
// Random boxes.
for n in 0..6 {
let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {
let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs));
std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] })
});
let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5);
if n % 2 == 0 {
box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5));
} else {
box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4));
}
}
// Triangles: one of the reference's tests, a pair as the title's
// builder stores it, all four triangles of a full node with turned
// ids, random ones.
let mut triangle_nodes = Vec::new();
let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0));
let pair = s.add(
nodes::triangles(
&[front[0], front[1], front[2], [2.0, 2.0, 5.0]],
9 | 0x80 | 6 << 8,
),
16,
);
triangle_nodes.extend([(pair, 0), (pair, 1)]);
let five = [
[-3.0, -1.0, 6.0],
[-1.0, 2.0, 6.5],
[1.0, -1.0, 6.0],
[3.0, 2.0, 6.5],
[5.0, -1.0, 7.0],
];
// I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2).
let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16);
triangle_nodes.extend((0..4).map(|k| (full, k)));
for _ in 0..5 {
let c = g.vector(6.0);
let v: [[f32; 3]; 3] = std::array::from_fn(|_| {
let d = g.vector(3.0);
[c[0] + d[0], c[1] + d[1], c[2] + d[2]]
});
triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0));
}
let mut cases: Vec<Case> = Vec::new();
// Rays of the reference's tests against the lined-up boxes.
for &(n, kind) in &box_nodes[..2] {
for (origin, direction, extent) in [
([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
([0.0; 3], [1.0, 0.0, 0.0], 19.5),
([0.0; 3], [1.0, 0.0, 0.0], 19.0),
([0.0; 3], [-1.0, 0.0, 0.0], 1000.0),
([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0),
([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0),
([0.0; 3], [0.0; 3], 1000.0),
] {
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
}
}
// Random rays at every box node, half of them aimed at a box.
for &(n, kind) in &box_nodes {
let words = s.node(n);
let boxes = if kind == 5 {
bvh::boxes32(&words)
} else {
bvh::boxes16(&words)
};
for k in 0..12 {
let origin = g.vector(12.0);
let direction = if k % 2 == 0 {
let b = boxes[(k / 2) % 4];
if b[0].is_nan() {
g.vector(1.0)
} else {
std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0)
}
} else {
g.vector(1.0)
};
let extent = if k % 3 == 0 { 6.0 } else { 100.0 };
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
}
}
// Rays at every triangle: aimed inside, at an edge, at a vertex, past
// it, from both sides, along each axis.
for &(n, kind) in &triangle_nodes {
let p = bvh::triangle_vertices(&s.node(n), kind);
let at = |w: [f32; 3]| -> [f32; 3] {
std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a])
};
for (k, w) in [
[0.5, 0.25, 0.25],
[0.125, 0.75, 0.125],
[0.5, 0.5, 0.0],
[0.0, 0.5, 0.5],
[1.0, 0.0, 0.0],
[0.75, 0.75, -0.5],
[-0.25, 0.5, 0.75],
[0.25, 0.25, 0.5],
]
.into_iter()
.enumerate()
{
let target = at(w);
let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) };
let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]);
if k == 7 {
// The triangle lies behind.
direction = direction.map(|d| -d);
}
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
}
for axis in 0..3 {
for sign in [1.0f32, -1.0] {
let target = at([0.25, 0.5, 0.25]);
let mut origin = target;
origin[axis] -= 8.0 * sign;
let mut direction = [0.0; 3];
direction[axis] = sign;
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
}
}
}
// Kinds the instruction does not read, and threads masked out.
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
cases.extend([
Some((triangle_nodes[0].0, 6, ray)),
Some((triangle_nodes[0].0, 7, ray)),
None,
Some((
box_nodes[0].0,
5,
Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
)),
None,
]);
let batches = cases
.chunks(THREADS as usize)
.map(<[Case]>::to_vec)
.collect();
(s, batches)
}
/// The buffer for one batch: the threads' records, then the nodes. Node
/// pointers count from `base` before the first node, in bytes.
fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> {
let mut data = vec![0u32; (NODES / 4) as usize];
for (t, case) in batch.iter().enumerate() {
let Some((n, kind, ray)) = case else { continue };
let r = &mut data[t * (RECORD / 4) as usize..][..13];
let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind));
(r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32);
r[2] = ray.extent.to_bits();
for a in 0..3 {
r[3 + a] = ray.origin[a].to_bits();
r[6 + a] = ray.direction[a].to_bits();
r[9 + a] = ray.inverse[a].to_bits();
}
r[12] = 1;
}
data.extend(&scene.words);
data
}
fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] {
match case {
Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort),
None => BEFORE,
}
}
/// Sets the tests' title memory for this thread until dropped.
struct Memory;
impl Memory {
fn at(base: u64) -> Self {
// Heap slot 0: the buffer of records and nodes.
TEST_MEMORY.set(Some((0, base)));
Self
}
}
impl Drop for Memory {
fn drop(&mut self) {
TEST_MEMORY.set(None);
}
}
/// Runs every batch on the hardware adapter and WARP and compares with
/// the reference. `pointers` is what node pointers count from, in bytes
/// before the first node.
fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) {
let (shader, res) = build(wide, descriptor).expect("the program lowers");
assert_eq!(res.bvh.len(), 1);
let (scene, batches) = scene();
// The reference must see a bit of everything, or the comparison
// proves little.
let all: Vec<&Case> = batches.iter().flatten().collect();
let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect();
let boxes = |hits: usize| {
all.iter()
.zip(&results)
.filter(|(c, r)| {
matches!(c, Some((_, 4 | 5, _)))
&& r.iter().filter(|&&x| x != bvh::NONE).count() == hits
})
.count()
};
let triangles = |hit: bool| {
all.iter()
.zip(&results)
.filter(|(c, r)| {
matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit
})
.count()
};
assert!(
boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0,
"box cases"
);
assert!(
triangles(true) > 30 && triangles(false) > 30,
"triangle cases"
);
// Sorting must matter to some case, or the unsorted run proves nothing.
assert!(
all.iter()
.any(|c| expected(&scene, c, true) != expected(&scene, c, false)),
"no case tells sorted from unsorted"
);
let _one = super::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
let mut ran = 0;
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {label} device; skipped");
continue;
};
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
for (b, batch) in batches.iter().enumerate() {
let data = buffer(&scene, batch, pointers);
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(vec![0; 5]))],
views: &[
View::Buffer {
data: &data,
stride: Stride::Raw,
},
View::RawUav(4 * THREADS),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
for t in 0..THREADS as usize {
let case = batch.get(t).copied().flatten();
let want = match batch.get(t) {
Some(c) => expected(&scene, c, sort),
// A thread past the batch: its record is zeros, so it
// is masked out.
None => BEFORE,
};
let got = &out[0][4 * t..4 * t + 4];
assert_eq!(
got,
want,
"{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}",
got,
got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(),
want,
want.map(f32::from_bits),
);
}
}
ran += 1;
}
assert!(ran > 0, "no SM 6.6 device available");
}
#[test]
fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
// Pointers count from the buffer's start.
run(true, Descriptor::Table, u64::from(NODES), true);
assert_eq!(
build(true, Descriptor::Table).unwrap().1.bvh[0].1,
BvhNodes::Resource
);
}
#[test]
fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
run(false, Descriptor::Table, u64::from(NODES), true);
}
/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes.
const BASE: u64 = 0x12_3456_7800;
#[test]
fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
// The title's way: one descriptor for all of memory, the structure's
// address folded into a 64-bit pointer.
let _memory = Memory::at(BASE);
run(true, WHOLE, BASE + u64::from(NODES), true);
}
#[test]
fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
// The title's other way: the structure's address in the descriptor
// (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with
// an address past 2^40 bytes, and without box sorting.
let base = 0x312_3456_7800u64;
let structure = base + u64::from(NODES);
let _memory = Memory::at(base);
let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32);
run(false, descriptor, 0, false);
// And sorted.
let descriptor = Descriptor::Numbers(
(structure >> 8) as u32,
(structure >> 40) as u32 | bvh::BOX_SORT,
);
run(false, descriptor, 0, true);
}
#[test]
fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() {
for wide in [true, false] {
let native = native(&program(wide, WHOLE));
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
// The flags the title sets: sorted boxes, barycentrics, a
// ray-tracing structure. No resource is taken for it: the buffer
// loads' and the store's descriptors are all there is.
assert_eq!(res.bvh.len(), 1);
assert_eq!(
res.bvh[0].1,
BvhNodes::Memory {
word1: 0x8000_0000,
word3: 0x8900_03ff
}
);
assert_eq!(res.descriptors.len(), 5);
// Without the tests' stand-in the nodes are read as the title's
// programs will read them: through the host's directory of title
// memory. The program lowers and validates, and asks the host for
// the directory and for the list of pages it found no copy of.
let (shader, _) = build(wide, WHOLE).expect("lowers through the directory");
assert!(shader.root_srvs.contains(&super::SLOT_MEMORY));
assert!(shader.root_uavs.contains(&super::SLOT_FAULTS));
}
}
#[test]
fn a_structure_that_returns_triangle_ids_is_refused_by_name() {
// Triangle return mode 0 (bit 24 of dword 3 clear): the last two
// result dwords would be a triangle id and a hit status.
let mut words = program(true, WHOLE);
let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap();
words[flags] = 0x8800_03FF;
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
let io = io::raise(&p, &native).expect("io::raise");
let r = lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
});
match r {
Err(ShaderError::Unsupported { what, .. }) => {
assert_eq!(what, "a ray-tracing structure that returns triangle ids");
}
other => panic!("{:?}", other.map(|_| ())),
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+914
View File
@@ -0,0 +1,914 @@
//! Wave ORs that only steer a loop over each lane's own bits.
//!
//! The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and
//! the wave walks the set bits of the result together, each lane working only where its own
//! mask has the bit:
//!
//! ```text
//! merged = WaveActiveBitOr(mask); // over the lanes that run
//! while (merged != 0) {
//! bit = firstbitlow(merged);
//! if (mask & (1 << bit)) { ... } // the body
//! merged ^= 1 << bit;
//! }
//! ```
//!
//! A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not
//! every lane runs (a group barrier must be reached by every thread). It does not have to: as
//! one thread runs it, the loop visits the bits of `merged` in rising order and does something
//! only at the bits of the thread's own mask, so any `merged` that holds the thread's own bits
//! gives that thread the same run. The host wave's own OR is such a value.
//!
//! That holds only if the OR is used for nothing else, and if a round of the loop at a bit the
//! thread does not have leaves nothing behind. [`find`] proves both for each wave OR, with no
//! instruction sequence taken on trust:
//!
//! - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the
//! first-lane read of it, the set less the visited bit) are read only by the loop's own
//! steps: the test for an empty set, the lowest set bit, the removal of that bit, the test
//! that ends the loop;
//! - the lane's test is its own bit of the very value that was ORed, and "the body" is what a
//! lane only reaches with that test true in the same round;
//! - outside the body the loop has no side effect and no cross-lane step, writes nothing that
//! is read after the loop or carried into a later round, and is left only by the test for
//! "no bits left";
//! - no lane mask that depends on the test is used outside the round that made it.
//!
//! Anything else is refused there as before ("a wave reduction where not every lane runs") and
//! left to the forms of the program in which every lane runs that code (`emit`'s retries: the
//! skips left out, the branches around it taken wave-wide), where the halves do exchange.
//! `VICTORY_WAVE_OWN_BITS=0` turns this off.
use std::collections::{HashMap, HashSet};
use super::wave::{self, Op, Shape};
use crate::gfx10::{Fields, NULL, Operand};
use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
use crate::structure::{Atom, Bool, LaneExit, Structured};
type Why = &'static str;
const USED: Why = "a wave OR used as data";
const NO_LOOP: Why = "a wave OR that steers no loop over its bits";
const SHAPE: Why = "a loop over a wave OR's bits of another shape";
const TEST: Why = "a loop over a wave OR's bits whose lanes do not test their own bit";
const LEAVES: Why = "a value of a round over a wave OR's bits that outlives the round";
const EFFECT: Why = "an effect in a loop over a wave OR's bits outside the lanes' own bits";
const CROSS: Why = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits";
const EXIT: Why = "a loop over a wave OR's bits left another way";
const STALE: Why = "a lane's own-bit test used outside its round";
const MASK: Why = "a wave OR over a mask a running lane may be outside";
/// What [`find`] proved.
#[derive(Debug, Default)]
pub(super) struct OwnBits {
/// Wave ORs (the values their sections leave) a host wave may take over its own lanes.
pub totals: HashSet<Value>,
/// VGPR values of those loops that every lane of a host wave holds alike (the bits still
/// to visit): a first-lane read of one is the lane's own value.
pub alike: HashSet<Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum User {
Inst(usize, usize),
Phi(usize, usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Arg {
Val(Value),
K(u32),
Other,
}
struct Ctx<'a> {
p: &'a Program,
st: &'a Structured,
users: HashMap<Value, Vec<User>>,
/// The instruction writing each value.
def: HashMap<Value, (usize, usize)>,
/// Values an instruction reads, directly or through joins.
live: HashSet<Value>,
idom: Vec<usize>,
sections: Vec<HashMap<usize, wave::Section>>,
}
/// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane
/// masks are followed as booleans) and without the old value of a VGPR it writes, which only
/// lanes outside a guard keep.
fn used(p: &Program, st: &Structured, b: usize, i: usize) -> Vec<Value> {
let inst = &p.blocks[b].insts[i];
let ops = crate::ir::operand_reads(p, inst);
let guarded = st.guards[b][i].is_some();
inst.reads
.iter()
.filter(|&&(r, _)| match r {
Reg::S(c) if c == EXEC || c == EXEC + 1 => false,
Reg::V(_) => ops.contains(&r) || guarded,
_ => true,
})
.map(|r| r.1)
.collect()
}
fn value(inst: &Inst, op: &Operand) -> Option<Value> {
match *op {
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
_ => None,
}
}
/// The sources of a scalar or unmodified vector operation.
fn args(inst: &Inst) -> Vec<Arg> {
let src: &[Operand] = match &inst.fields {
Fields::Sop { src, .. } => src,
Fields::Valu(v)
if v.dpp.is_none()
&& v.sdwa.is_none()
&& v.abs == 0
&& v.neg == 0
&& !v.clamp
&& v.omod == 0 =>
{
&v.src
}
_ => &[],
};
src.iter()
.map(|o| match (value(inst, o), o) {
(Some(v), _) => Arg::Val(v),
(None, &Operand::Const(c)) => crate::resource::inline(c).map_or(Arg::Other, Arg::K),
(None, &Operand::Literal(x)) => Arg::K(x),
_ => Arg::Other,
})
.collect()
}
/// The other source of a two-source operation that reads `a`.
fn other(inst: &Inst, a: Value) -> Option<Arg> {
match args(inst)[..] {
[Arg::Val(x), o] if x == a => Some(o),
[o, Arg::Val(x)] if x == a => Some(o),
_ => None,
}
}
/// The scalar (not SCC) or vector dword an instruction writes, if it writes one.
fn result(inst: &Inst) -> Option<Value> {
let mut w = inst.writes.iter().filter(|w| w.0 != Reg::Scc);
match (w.next(), w.next()) {
(Some(&(_, v)), None) => Some(v),
_ => None,
}
}
/// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program
/// sends.
fn effect(inst: &Inst) -> bool {
let name = inst.name();
matches!(inst.fields, Fields::Exp { .. })
|| matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
|| name.contains("store")
|| name.contains("atomic")
|| matches!(inst.fields, Fields::Ds { .. })
&& !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute"))
|| matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt")
}
impl Ctx<'_> {
fn new<'a>(p: &'a Program, st: &'a Structured) -> Ctx<'a> {
let mut users: HashMap<Value, Vec<User>> = HashMap::new();
let mut def = HashMap::new();
let mut live: HashSet<Value> = HashSet::new();
for (b, block) in p.blocks.iter().enumerate() {
for (k, phi) in block.phis.iter().enumerate() {
for &a in &phi.args {
users.entry(a).or_default().push(User::Phi(b, k));
}
}
for (i, inst) in block.insts.iter().enumerate() {
for v in used(p, st, b, i) {
users.entry(v).or_default().push(User::Inst(b, i));
live.insert(v);
}
for &(_, w) in &inst.writes {
def.insert(w, (b, i));
}
}
}
// through joins
let mut changed = true;
while changed {
changed = false;
for block in &p.blocks {
for phi in &block.phis {
if live.contains(&phi.value) {
for &a in &phi.args {
changed |= live.insert(a);
}
}
}
}
}
let order = crate::ir::reverse_postorder(&p.blocks);
let mut index = vec![usize::MAX; p.blocks.len()];
for (n, &b) in order.iter().enumerate() {
index[b] = n;
}
let idom = crate::ir::idoms(&p.blocks, &order, &index);
let sections = (0..p.blocks.len()).map(|b| wave::sections(p, b)).collect();
Ctx {
p,
st,
users,
def,
live,
idom,
sections,
}
}
fn inst(&self, u: (usize, usize)) -> &Inst {
&self.p.blocks[u.0].insts[u.1]
}
fn at(&self, u: (usize, usize)) -> usize {
self.inst(u).machine.offset
}
/// Whether block `a` dominates block `b`.
fn dominates(&self, a: usize, mut b: usize) -> bool {
loop {
if a == b {
return true;
}
let d = self.idom.get(b).copied().unwrap_or(usize::MAX);
if d == b || d == usize::MAX {
return false;
}
b = d;
}
}
fn readers(&self, v: Value) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = self
.users
.get(&v)
.into_iter()
.flatten()
.filter_map(|u| match *u {
User::Inst(b, i) => Some((b, i)),
User::Phi(..) => None,
})
.collect();
out.sort_unstable();
out.dedup();
out
}
/// The joins reading `v` whose value something reads.
fn joins(&self, v: Value) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = self
.users
.get(&v)
.into_iter()
.flatten()
.filter_map(|u| match *u {
User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)),
_ => None,
})
.collect();
out.sort_unstable();
out.dedup();
out
}
/// The loop of header `h`: the blocks that reach one of its back edges without passing it.
fn natural_loop(&self, h: usize) -> Vec<bool> {
let mut inside = vec![false; self.p.blocks.len()];
let mut work: Vec<usize> = self.p.blocks[h]
.preds
.iter()
.copied()
.filter(|&q| self.dominates(h, q))
.collect();
if work.is_empty() {
return inside;
}
inside[h] = true;
while let Some(b) = work.pop() {
if inside[b] {
continue;
}
inside[b] = true;
work.extend(self.p.blocks[b].preds.iter().copied());
}
inside
}
/// Whether `b` holds only in lanes where `a` does.
fn implied(&self, b: Bool, a: Atom, memo: &mut HashMap<Bool, bool>) -> bool {
if b == Bool::FALSE {
return true;
}
if let Some(&r) = memo.get(&b) {
return r;
}
let r = match self.st.bools.node(b) {
None => false,
Some((x, lo, _)) if x == a => lo == Bool::FALSE,
Some((_, lo, hi)) => self.implied(lo, a, memo) && self.implied(hi, a, memo),
};
memo.insert(b, r);
r
}
/// The conditional branch reading `scc`, as (its place, the block it goes to when SCC is
/// set, the other one).
fn branch(&self, scc: Value) -> Option<((usize, usize), usize, usize)> {
let [u] = self.readers(scc)[..] else {
return None;
};
let Exit::Branch { taken, not_taken } = self.p.blocks[u.0].exit else {
return None;
};
if u.1 + 1 != self.p.blocks[u.0].insts.len() {
return None;
}
match self.inst(u).name() {
"s_cbranch_scc1" => Some((u, taken, not_taken)),
"s_cbranch_scc0" => Some((u, not_taken, taken)),
_ => None,
}
}
/// One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the
/// VGPR values its loop keeps alike, or where and why it is not such a loop.
fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result<Vec<Value>, (usize, Why)> {
let p = self.p;
let st = self.st;
let n = p.blocks.len();
let here = p.blocks[sb].offset;
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
// every lane that runs the section is one of the lanes ORed
let &mb = st.masks.get(&mask).ok_or((here, MASK))?;
if st.bools.meet(&[(st.reach[sb], true), (mb, false)]) {
return Err((here, MASK));
}
// ---- the bits still to visit, and the loop's own steps ----
let mut rem: HashSet<Value> = HashSet::from([t]);
let mut pattern: HashSet<(usize, usize)> = HashSet::new();
let mut alike: Vec<Value> = Vec::new();
// an unguarded copy
let copy = |u: (usize, usize)| -> Option<Value> {
let i = self.inst(u);
(matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none())
.then(|| result(i))
.flatten()
};
let mut init = vec![t];
// (SCC, whether it is set when the OR is empty)
let mut zero: Option<(Value, bool)> = None;
for u in self.readers(t) {
let i = self.inst(u);
let name = i.name();
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
&& other(i, t) == Some(Arg::K(0))
&& zero.is_none()
&& let Some(scc) = i.write(Reg::Scc)
{
zero = Some((scc, name.contains("_eq_")));
rem.insert(scc);
} else if let Some(w) = copy(u) {
init.push(w);
rem.insert(w);
if matches!(i.writes[0].0, Reg::V(_)) {
alike.push(w);
}
} else {
return Err((self.at(u), USED));
}
pattern.insert(u);
}
// the loop's join of them
let mut join: Option<(usize, usize)> = None;
for &v in &init {
if v != t
&& let Some(&u) = self.readers(v).first()
{
return Err((self.at(u), USED));
}
for j in self.joins(v) {
if join.is_some_and(|q| q != j) {
return Err((p.blocks[j.0].offset, USED));
}
join = Some(j);
}
}
let (h, k) = join.ok_or((here, NO_LOOP))?;
let phi = &p.blocks[h].phis[k];
let r = phi.value;
rem.insert(r);
let head = p.blocks[h].offset;
let lp = self.natural_loop(h);
if !lp[h] || lp[sb] {
return Err((head, NO_LOOP));
}
// the set as a scalar: the first lane's copy of it
let cur = if matches!(phi.reg, Reg::V(_)) {
alike.push(r);
let [u] = self.readers(r)[..] else {
return Err((head, USED));
};
let i = self.inst(u);
if i.name() != "v_readfirstlane_b32" || args(i).len() != 1 || !lp[u.0] {
return Err((self.at(u), USED));
}
pattern.insert(u);
let c = result(i).ok_or((self.at(u), SHAPE))?;
if !self.joins(r).is_empty() {
return Err((head, USED));
}
c
} else {
r
};
rem.insert(cur);
// its lowest bit, the set without it, the tests for "that was the last"
let mut idx: Option<Value> = None;
let mut next: Option<(Value, Value)> = None;
// (SCC, whether it is set while bits remain)
let mut more: Vec<(Value, bool)> = Vec::new();
let mut bits: Vec<Value> = Vec::new();
for u in self.readers(cur) {
let i = self.inst(u);
let name = i.name();
if !lp[u.0] {
return Err((self.at(u), USED));
}
match (name, &args(i)[..]) {
("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i),
("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => {
let bit = match (name, &args(i)[..]) {
("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b,
("s_xor_b32", _) => match other(i, cur) {
Some(Arg::Val(b)) if b != cur => b,
_ => return Err((self.at(u), USED)),
},
_ => return Err((self.at(u), USED)),
};
let w = result(i).ok_or((self.at(u), SHAPE))?;
next = Some((w, bit));
bits.push(bit);
if let Some(scc) = i.write(Reg::Scc) {
more.push((scc, true));
rem.insert(scc);
}
}
("s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32", _) => {
let (Some(Arg::Val(b)), Some(scc)) = (other(i, cur), i.write(Reg::Scc)) else {
return Err((self.at(u), USED));
};
bits.push(b);
more.push((scc, name.contains("_lg_")));
rem.insert(scc);
}
_ => return Err((self.at(u), USED)),
}
pattern.insert(u);
}
if cur != r && !self.joins(cur).is_empty() {
return Err((head, USED));
}
let (Some(idx), Some((nx, bit))) = (idx, next) else {
return Err((head, SHAPE));
};
if bits.iter().any(|&b| b != bit) {
return Err((head, SHAPE));
}
// the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it)
let made = |v: Value| self.def.get(&v).map(|&u| (u, self.inst(u)));
let shifted = match made(bit) {
Some((u, i)) if i.name() == "s_lshl_b32" && lp[u.0] => match args(i)[..] {
[Arg::K(1), Arg::Val(sh)] => Some(sh),
_ => None,
},
_ => None,
};
let by_idx = shifted.is_some_and(|sh| {
sh == idx
|| made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31)))
});
if !by_idx {
return Err((head, SHAPE));
}
// the set less the bit: back into the join, or tested for empty
rem.insert(nx);
let mut nexts = vec![nx];
for u in self.readers(nx) {
let i = self.inst(u);
let name = i.name();
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
&& other(i, nx) == Some(Arg::K(0))
&& let Some(scc) = i.write(Reg::Scc)
{
more.push((scc, name.contains("_lg_")));
rem.insert(scc);
} else if let Some(w) = copy(u) {
nexts.push(w);
rem.insert(w);
if matches!(i.writes[0].0, Reg::V(_)) {
alike.push(w);
}
} else {
return Err((self.at(u), USED));
}
pattern.insert(u);
}
for &v in &nexts {
if v != nx
&& let Some(&u) = self.readers(v).first()
{
return Err((self.at(u), USED));
}
if self.joins(v).iter().any(|&j| j != (h, k)) {
return Err((head, USED));
}
}
for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) {
let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) };
if !ok {
return Err((head, SHAPE));
}
}
// the loop goes on while bits remain and is left when none does
let mut leaves: HashSet<usize> = HashSet::new();
for &(scc, set_while_more) in &more {
if !self.joins(scc).is_empty() {
return Err((head, USED));
}
if self.readers(scc).is_empty() {
continue;
}
let (u, set, clear) = self.branch(scc).ok_or((head, USED))?;
let (on, out) = if set_while_more { (set, clear) } else { (clear, set) };
if !lp[u.0] || !lp[on] || lp[out] {
return Err((self.at(u), SHAPE));
}
leaves.insert(u.0);
pattern.insert(u);
}
if leaves.is_empty() {
return Err((head, SHAPE));
}
// "no bit at all" skips the loop; what lies between that test and the loop runs only
// when there is one
let mut pre = vec![false; n];
if let Some((scc, set_when_empty)) = zero {
if !self.joins(scc).is_empty() {
return Err((here, USED));
}
if !self.readers(scc).is_empty() {
let (u, set, clear) = self.branch(scc).ok_or((here, USED))?;
let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) };
if none == some || lp[u.0] {
return Err((self.at(u), SHAPE));
}
if some != h {
if p.blocks[some].preds[..] != [u.0] || !self.dominates(some, h) {
return Err((self.at(u), SHAPE));
}
for b in 0..n {
pre[b] = self.dominates(some, b) && !self.dominates(h, b);
}
for b in (0..n).filter(|&b| pre[b]) {
let inside = match p.blocks[b].exit {
Exit::End | Exit::Indirect => false,
ref e => e.successors().iter().all(|&s| pre[s] || s == h),
};
if !inside {
return Err((p.blocks[b].offset, SHAPE));
}
}
}
pattern.insert(u);
}
}
// ---- the lane's test of its own bit ----
// (the atom of the compare, its block, its index)
let mut tests: Vec<(Atom, usize, usize)> = Vec::new();
for u in self.readers(bit) {
let i = self.inst(u);
if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() {
continue;
}
let Some(y) = result(i) else { continue };
for c in self.readers(y) {
let ci = self.inst(c);
if matches!(
ci.name(),
"v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32"
| "v_cmp_lg_i32" | "v_cmpx_lg_i32"
) && other(ci, y) == Some(Arg::K(0))
&& lp[c.0]
{
tests.extend(ci.writes.iter().map(|w| (Atom::Lane(w.1), c.0, c.1)));
}
}
}
if tests.is_empty() {
return Err((head, TEST));
}
let mut memo: Vec<HashMap<Bool, bool>> = vec![HashMap::new(); tests.len()];
// what a lane only reaches with its own bit set, in the round of that test
let mut body_block = vec![false; n];
for b in (0..n).filter(|&b| lp[b]) {
body_block[b] = tests.iter().enumerate().any(|(j, &(a, tb, _))| {
b != tb && self.dominates(tb, b) && self.implied(st.reach[b], a, &mut memo[j])
});
}
let body_inst = |b: usize, i: usize, memo: &mut Vec<HashMap<Bool, bool>>| {
body_block[b]
|| lp[b]
&& st.guards[b][i].is_some_and(|g| {
tests.iter().enumerate().any(|(j, &(a, tb, ti))| {
(b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j])
})
})
};
// ---- a round outside the body leaves nothing behind ----
for b in (0..n).filter(|&b| lp[b] || pre[b]) {
for (i, inst) in p.blocks[b].insts.iter().enumerate() {
if lp[b] && body_inst(b, i, &mut memo) {
continue;
}
let u = (b, i);
for &(reg, w) in &inst.writes {
if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) {
continue;
}
for user in self.users.get(&w).into_iter().flatten() {
let stays = match *user {
User::Inst(b2, _) => lp[b2] || pre[b2],
User::Phi(b2, k2) => {
body_block[b2] || !self.live.contains(&p.blocks[b2].phis[k2].value)
}
};
if !stays {
return Err((self.at(u), LEAVES));
}
}
}
if pattern.contains(&u) {
continue;
}
if effect(inst) {
return Err((self.at(u), EFFECT));
}
let name = inst.name();
let cross = name.starts_with("ds_swizzle")
|| name.contains("permute")
|| name.starts_with("v_mbcnt")
|| name.contains("lane")
|| matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some())
|| super::lower::reads_mask_as_data(st, inst)
|| self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end);
if cross {
return Err((self.at(u), CROSS));
}
if used(p, st, b, i).iter().any(|v| rem.contains(v)) {
return Err((self.at(u), USED));
}
}
// left only by "no bits left"; the body may leave it as it likes
if lp[b] && !body_block[b] {
let ok = match p.blocks[b].exit {
Exit::End | Exit::Indirect => false,
ref e => leaves.contains(&b) || e.successors().iter().all(|&s| lp[s]),
};
if !ok {
return Err((p.blocks[b].offset, EXIT));
}
}
}
// ---- no mask that depends on the test outlives its round ----
let mut dep: HashSet<Atom> = tests.iter().map(|t| t.0).collect();
let mut changed = true;
while changed {
changed = false;
for (&id, edges) in &st.phi_masks {
if !dep.contains(&Atom::Phi(id))
&& edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a)))
{
dep.insert(Atom::Phi(id));
changed = true;
}
}
}
let mut seen: HashMap<Bool, bool> = HashMap::new();
let mut tainted = |b: Bool| -> bool {
*seen
.entry(b)
.or_insert_with(|| st.bools.support(b).iter().any(|a| dep.contains(a)))
};
for b in 0..n {
if lp[b] && tests.iter().any(|&(_, tb, _)| self.dominates(tb, b)) {
continue;
}
let stale = st.guards[b].iter().flatten().any(|&g| tainted(g))
|| matches!(st.exits[b], LaneExit::Branch { when, .. } if tainted(when));
if stale {
return Err((p.blocks[b].offset, STALE));
}
}
for (&v, &m) in &st.masks {
if !tainted(m) {
continue;
}
for user in self.users.get(&v).into_iter().flatten() {
let outside = match *user {
User::Inst(b2, _) => !lp[b2],
User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value),
};
if outside {
return Err((head, STALE));
}
}
}
Ok(alike)
}
}
/// The wave ORs of `p` that only steer a loop over each lane's own bits (see the module
/// notes). `why`: one line on stderr for each wave OR that is not one.
pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits {
let mut out = OwnBits::default();
let mut ctx: Option<Ctx> = None;
for b in 0..p.blocks.len() {
let sections = wave::sections(p, b);
let mut starts: Vec<_> = sections.keys().copied().collect();
starts.sort_unstable();
for s in starts {
let sec = &sections[&s];
let mut left: Vec<_> = sec.shapes.iter().collect();
left.sort_unstable_by_key(|(v, _)| v.0);
for (&t, &shape) in left {
let Shape::Active(Op::Or, x, mask, 0) = shape else {
continue;
};
let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st));
// (values only the section itself reads are not results)
let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end);
if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) {
continue;
}
match ctx.site(b, t, x, mask) {
Ok(alike) => {
out.totals.insert(t);
out.alike.extend(alike);
}
Err((offset, what)) => {
if why {
eprintln!(
"WAVE64-OWN-BITS the wave OR at {:#x}: not a loop over the lanes' own bits at {offset:#x}: {what}",
p.blocks[b].insts[s].machine.offset
);
}
}
}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::emit::wave::WAVE_OR_V7_TO_S7;
const ADD_BIT_NUMBER: u32 = 0x4A0A_0A0A; // v_add_nc_u32 v5, s10, v5
/// The title's scalarised light loop (`indirect_light_probes:CS_IrradianceCache_Shade`,
/// 0x71f8 on), in small: the wave OR of v7 in s7, a loop over its bits with the lowest
/// one's number in s10 and the bit in s11, and `body` for the lanes whose v7 has the bit
/// (`own`) or for every lane; `latch` runs in every lane after the body, `after` after
/// the loop.
fn light_loop(own: bool, body: &[u32], latch: &[u32], after: &[u32]) -> Program {
let mut w = WAVE_OR_V7_TO_S7.to_vec();
let test: &[u32] = if own {
&[
0x3608_0E0B, // v_and_b32 v4, s11, v7
0xBE8C_047E, // s_mov_b64 s[12:13], exec
0x7DAA_0880, // v_cmpx_ne_u32 exec, 0, v4
]
} else {
&[0xBE8C_047E] // s_mov_b64 s[12:13], exec
};
// from the loop's head to its last branch
let head = 3 + test.len() + usize::from(own) + body.len() + 1 + latch.len() + 3;
w.extend_from_slice(&[
0xBF06_8007, // s_cmp_eq_u32 s7, 0
0xBF85_0000 | (3 + head) as u32, // s_cbranch_scc1 past the loop
0x7E06_0207, // v_mov_b32 v3, s7
0xBF82_0001, // s_branch to the loop's head
0x7E06_0209, // again: v_mov_b32 v3, s9
0x7E10_0503, // head: v_readfirstlane_b32 s8, v3
0xBE8A_1308, // s_ff1_i32_b32 s10, s8
0x8F0B_0A81, // s_lshl_b32 s11, 1, s10
]);
w.extend_from_slice(test);
if own {
w.push(0xBF88_0000 | body.len() as u32); // s_cbranch_execz past the body
}
w.extend_from_slice(body);
w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13]
w.extend_from_slice(latch);
w.extend_from_slice(&[
0x8909_080B, // s_xor_b32 s9, s11, s8
0xBF06_0B08, // s_cmp_eq_u32 s8, s11
0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again
]);
w.extend_from_slice(after);
w.push(0xBF81_0000); // s_endpgm
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
crate::ir::build(&code, true, 256).unwrap()
}
fn found(p: &Program) -> OwnBits {
let st = crate::structure::structure(p).unwrap();
find(p, &st, false)
}
#[test]
fn a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() {
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[]);
let insts = || p.blocks.iter().flat_map(|b| &b.insts);
let names: Vec<&str> = insts().map(|i| i.name()).collect();
for n in [
"s_ff1_i32_b32",
"s_lshl_b32",
"v_and_b32",
"v_cmpx_ne_u32",
"s_xor_b32",
"v_readfirstlane_b32",
"s_cbranch_execz",
] {
assert!(names.contains(&n), "{n} in {names:?}");
}
// a loop: its last branch goes back to the copy of the bits still to visit
assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b)));
let own = found(&p);
// the OR is the section's last lane read, and the bits still to visit (v3) are alike
let total = insts()
.rfind(|i| i.name() == "v_readlane_b32")
.and_then(|i| i.write(Reg::S(7)))
.unwrap();
assert_eq!(own.totals, HashSet::from([total]));
let first = insts().find(|i| i.name() == "v_readfirstlane_b32").unwrap();
assert!(own.alike.contains(&first.read(Reg::V(3)).unwrap()));
}
#[test]
fn a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() {
// (the same title's volume loops, 0xa668 on: no test of the lane's own mask)
let p = light_loop(false, &[ADD_BIT_NUMBER], &[], &[]);
assert!(found(&p).totals.is_empty());
}
#[test]
fn a_bit_number_read_after_the_loop_is_not_the_lanes_own() {
// v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020A]);
assert!(found(&p).totals.is_empty());
}
#[test]
fn the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() {
// v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too
let p = light_loop(true, &[0x4A0A_0A08], &[], &[]);
assert!(found(&p).totals.is_empty());
}
#[test]
fn a_count_of_the_rounds_is_not_the_lanes_own() {
// s_add_i32 s14, s14, 1 where every lane passes, read after the loop
// (v_mov_b32 v6, s14): one round for each bit any lane has
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]);
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32"));
assert!(found(&p).totals.is_empty());
// (reading s14 there without counting in it is nothing of the loop's)
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]);
assert_eq!(found(&p).totals.len(), 1);
}
#[test]
fn an_effect_where_every_lane_passes_is_not_the_lanes_own() {
// ds_write_b32 v5, v5 after the body: once for each bit any lane has
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]);
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32"));
assert!(found(&p).totals.is_empty());
}
}
+484
View File
@@ -0,0 +1,484 @@
//! The geometry shader that completes the console's rectangle lists (list
//! topology 17, pipeline topology type 19). A rectangle comes as three
//! vertices, three corners of a screen-aligned rectangle; the hardware
//! draws the whole rectangle and continues every vertex shader output
//! linearly into the fourth corner. The host has no such topology: the
//! draw goes out as a triangle list with this shader behind the translated
//! vertex shader, so vertex counts, vertex numbers, indices and indirect
//! arguments stay the title's, and each rectangle arrives here as one
//! triangle.
//!
//! Which vertex is the corner between the other two varies:
//! the title's full-screen rectangles come as top left, bottom left, bottom
//! right (the second), its tiled lighting as top left, bottom left, top
//! right (the first). The corner is the vertex that shares x with one of
//! the others and y with the other; the fourth vertex lies opposite it,
//! `a + b - corner` for the position and every float output. That holds
//! for three vertices with one positive w (then it is the same in clip
//! space and on the screen, whatever the interpolation mode); three that
//! differ in w, or are not such corners, stay the triangle they make.
//!
//! Flat values are the first vertex's: both triangles start with it (the
//! halves on either side of the diagonal through it, turning as the three
//! vertices do), which is the vertex the host takes a flat input from, and
//! the fourth vertex's integer outputs are the first vertex's.
//!
//! shortcut: that the console takes a rectangle's flat values from its
//! first vertex follows from the hardware's provoking-vertex setting for
//! triangles; it is not measured on a rectangle.
use super::bitcode::{Attr, Bin, Term, V, pred};
use super::container::SigElement;
use super::shader::{Geometry, Shader};
use crate::ShaderError;
use crate::dxbc::{Container, FourCC};
/// Vertices emitted per rectangle: two triangles.
const VERTICES: u32 = 6;
/// The scalars a geometry shader may emit per invocation (vertices times
/// output components).
const MAX_SCALARS: u32 = 1024;
/// The geometry shader (a DXIL container) for rectangle lists drawn with
/// the translated vertex shader `vs` and, if the pipeline has one, the
/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its
/// inputs and outputs are the vertex shader's outputs, register for
/// register, so it links with both. A pixel shader that declares a
/// primitive id gets the rectangle's number, which the host leaves to the
/// geometry stage when there is one.
pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
let sig = |dxil: &[u8], fourcc| -> Result<Vec<SigElement>, ShaderError> {
let c = Container::parse(dxil)?;
match c.part(fourcc) {
Some(part) => super::signature(part.data),
None => Ok(Vec::new()),
}
};
let outputs = sig(vs, FourCC::OSG1)?;
let wanted = match ps {
Some(ps) => sig(ps, FourCC::ISG1)?,
None => Vec::new(),
};
build(outputs, &wanted)
}
/// [`rect_list_gs`] from the vertex shader's outputs and the pixel
/// shader's inputs.
fn build(mut outputs: Vec<SigElement>, ps_inputs: &[SigElement]) -> Result<Vec<u8>, ShaderError> {
let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
if outputs.iter().any(|e| e.row.is_none()) {
return Err(unsupported("a rectangle list output without a register"));
}
let Some(position) = outputs
.iter()
.position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4)
else {
return Err(unsupported("a rectangle list without a four-component position"));
};
for e in &mut outputs {
// Interpolation as `emit_program` declares a vertex shader's
// outputs; a geometry shader's inputs carry the same modes.
e.interp = match (e.kind, e.comp) {
(3, _) => 4,
(0 | 6 | 7, 9) => 2,
(0, _) => 1,
_ => 0,
};
e.usage = (1 << e.cols) - 1;
}
let mut s = Shader::new(false);
s.geometry = Some(Geometry {
max_vertices: VERTICES,
});
s.inputs = outputs.clone();
// The primitive id the pixel shader declares, as one more output.
let wanted = ps_inputs
.iter()
.find(|e| e.kind == 10 && e.row.is_some())
.filter(|_| !outputs.iter().any(|o| o.kind == 10));
let primitive = match wanted {
Some(e) => {
// Alone in its columns, and in a row of constant elements.
let clash = outputs.iter().any(|o| {
let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols;
o.row == e.row && (o.interp != 1 || overlap)
});
if clash {
return Err(unsupported(
"a rectangle list whose primitive id shares a register with a vertex output",
));
}
outputs.push(SigElement {
interp: 1,
usage: (1 << e.cols) - 1,
..e.clone()
});
Some(outputs.len() - 1)
}
None => None,
};
let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum();
if scalars * VERTICES > MAX_SCALARS {
return Err(unsupported(
"a rectangle list with more output components than a geometry shader emits",
));
}
s.outputs = outputs;
let b = s.entry;
// Every input of the three vertices: [element][column][vertex].
let mut corners: Vec<Vec<[V; 3]>> = Vec::new();
for id in 0..s.inputs.len() {
let mut columns = Vec::new();
for col in 0..s.inputs[id].cols {
columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex)));
}
corners.push(columns);
}
// One positive w, and no two vertices in one place.
let (x, y, w) = (
corners[position][0],
corners[position][1],
corners[position][3],
);
let zero = s.m.f32(0);
let mut plain = s.m.cmp(b, pred::OGT, w[0], zero);
for &other in &w[1..] {
let one_w = same(&mut s, other, w[0]);
plain = both(&mut s, plain, one_w);
}
for (i, j) in [(0, 1), (0, 2), (1, 2)] {
let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j]));
let together = both(&mut s, same_x, same_y);
let apart = not(&mut s, together);
plain = both(&mut s, plain, apart);
}
// corner[i]: vertex i is the corner between the other two (the first
// that shares x with one of them and y with the other).
let mut corner: Vec<V> = Vec::new();
for i in 0..3 {
let (a, c) = ((i + 1) % 3, (i + 2) % 3);
let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c]));
let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a]));
let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya));
let shares = either(&mut s, one, other);
let mut here = both(&mut s, shares, plain);
for &found in &corner {
let earlier = not(&mut s, found);
here = both(&mut s, here, earlier);
}
corner.push(here);
}
// What the six emitted vertices carry: [element][column][vertex].
let mut emitted: Vec<Vec<[V; 6]>> = Vec::new();
for (id, columns) in corners.iter().enumerate() {
let float = s.inputs[id].comp == 9;
let mut out = Vec::new();
for &[p0, p1, p2] in columns {
// The fourth vertex: `a + b - corner`. Integers (flat), and
// three vertices without a corner, keep the first vertex's
// value; the second triangle of the latter is then empty.
let mut fourth = p0;
if float {
for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)]
.into_iter()
.enumerate()
{
let sum = s.m.bin(b, Bin::Add, a, c);
let opposite = s.m.bin(b, Bin::Sub, sum, at);
fourth = s.m.select(b, corner[k], opposite, fourth);
}
}
// Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1,
// v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1).
let third = s.m.select(b, corner[0], fourth, p2);
let fifth = s.m.select(b, corner[1], p2, fourth);
let sixth = s.m.select(b, corner[0], p2, p1);
let sixth = s.m.select(b, corner[1], fourth, sixth);
out.push([p0, p1, third, p0, fifth, sixth]);
}
emitted.push(out);
}
// The rectangle's number: the triangle's, three vertices a rectangle.
let mut number = None;
if let Some(id) = primitive {
let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]);
number = Some((id, n));
}
let stream = s.m.i8(0);
for vertex in 0..VERTICES as usize {
for (id, columns) in emitted.iter().enumerate() {
let name = if s.outputs[id].comp == 9 {
"storeOutput.f32"
} else {
"storeOutput.i32"
};
for (col, values) in columns.iter().enumerate() {
let args = [
s.m.i32(id as u32),
s.m.i32(0),
s.m.i8(col as u8),
values[vertex],
];
s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args);
}
}
if let Some((id, n)) = number {
let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n];
s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args);
}
s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]);
// The strip ends after the first triangle.
if vertex == 2 {
s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]);
}
}
s.m.terminate(b, Term::Ret);
Ok(s.finish())
}
/// Column `col` of input `id` at vertex `vertex` of the triangle.
fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V {
let (name, ty) = if s.inputs[id].comp == 9 {
("loadInput.f32", s.t.f32)
} else {
("loadInput.i32", s.t.i32)
};
let args = [
s.m.i32(id as u32),
s.m.i32(0),
s.m.i8(col),
s.m.i32(vertex),
];
let entry = s.entry;
s.op(entry, name, Attr::ReadNone, ty, 4, &args)
}
/// Two floats are equal.
fn same(s: &mut Shader, a: V, b: V) -> V {
let entry = s.entry;
s.m.cmp(entry, pred::OEQ, a, b)
}
fn both(s: &mut Shader, a: V, b: V) -> V {
let entry = s.entry;
s.m.bin(entry, Bin::And, a, b)
}
fn either(s: &mut Shader, a: V, b: V) -> V {
let entry = s.entry;
s.m.bin(entry, Bin::Or, a, b)
}
fn not(s: &mut Shader, a: V) -> V {
let (entry, on) = (s.entry, s.m.bool(true));
s.m.bin(entry, Bin::Xor, a, on)
}
#[cfg(test)]
mod tests {
use super::*;
fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement {
SigElement {
name: name.into(),
index,
kind,
comp,
interp: 0,
row: Some(row),
col: 0,
cols,
usage: 0,
half: false,
}
}
/// A position, a float interpolant and an integer one.
fn outputs() -> Vec<SigElement> {
vec![
element("SV_Position", 0, 3, 9, 0, 4),
element("TEXCOORD", 0, 0, 9, 1, 4),
element("TEXCOORD", 1, 0, 5, 2, 2),
]
}
/// The stage is a geometry shader of triangles in and six strip
/// vertices out, with the vertex shader's outputs on both sides and
/// the primitive id the pixel shader declares; the validator, where
/// there is one, accepts it.
#[test]
fn the_rectangle_stage_is_a_geometry_shader() {
let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)];
let gs = build(outputs(), &wanted).unwrap();
let c = Container::parse(&gs).unwrap();
// Program version: geometry (2), shader model 6.6.
assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]);
let psv = c.part(FourCC::PSV0).unwrap().data;
// Triangles in, triangle strips out, stream 0, a position.
assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]);
// Geometry stage, six vertices, three inputs, four outputs.
assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]);
let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap();
let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1));
assert_eq!(ins.len(), 3);
assert_eq!(outs.len(), 4);
for (i, o) in ins.iter().zip(&outs) {
assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row));
assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp));
}
assert_eq!((outs[3].kind, outs[3].row), (10, Some(3)));
#[cfg(windows)]
if let Ok(mut v) = super::super::validator::Validator::load(
super::super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut gs.clone()).unwrap();
let plain = build(outputs(), &[]).unwrap();
v.validate(&mut plain.clone()).unwrap();
}
}
/// Refused with a reason: no position, a primitive id in a register a
/// vertex output has, more components than six vertices may carry.
#[test]
fn rectangle_stages_that_cannot_be_made_are_refused() {
assert!(build(outputs()[1..].to_vec(), &[]).is_err());
let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)];
assert!(build(outputs(), &taken).is_err());
let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)];
many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4)));
assert!(build(many, &[]).is_err());
}
/// A vertex shader that passes a position and a float4 through, and a
/// pixel shader that writes the float4.
#[cfg(windows)]
fn pass_through() -> (super::super::HostShader, super::super::HostShader) {
let position = SigElement {
interp: 4,
usage: 15,
..element("SV_Position", 0, 3, 9, 0, 4)
};
let coord = SigElement {
interp: 2,
usage: 15,
..element("TEXCOORD", 0, 0, 9, 1, 4)
};
let mut vs = Shader::new(false);
vs.inputs = vec![
SigElement {
usage: 15,
..element("POSITION", 0, 0, 9, 0, 4)
},
SigElement {
interp: 0,
..coord.clone()
},
];
vs.outputs = vec![position.clone(), coord.clone()];
let mut ps = Shader::new(true);
ps.inputs = vec![
SigElement {
usage: 0,
..position
},
coord,
];
ps.outputs = vec![SigElement {
usage: 15,
..element("SV_Target", 0, 16, 9, 0, 4)
}];
// Vertex: output id from input id. Pixel: target 0 from input 1.
for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] {
let b = s.entry;
for &(from, to) in copies {
for col in 0..4 {
let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)];
let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args);
let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v];
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
}
}
s.m.terminate(b, Term::Ret);
}
let host = |stage, s: Shader| super::super::HostShader {
stage,
dxil: s.finish(),
user_data: Vec::new(),
samplers: Vec::new(),
static_samplers: Vec::new(),
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
};
(
host(crate::native::HwStage::Vs, vs),
host(crate::native::HwStage::Ps, ps),
)
}
/// Three corners of the whole target, the corner between the other two
/// first (as the tiled lighting sends its tiles), second (as
/// full-screen rectangles come) or third: with the stage every texel
/// is drawn and the interpolant continues into the fourth corner's
/// half; without it part of the target is not drawn.
#[test]
#[cfg(windows)]
fn rectangles_are_drawn_whole() {
use super::super::host::{Draw, Host};
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 device; skipped");
return;
};
let (vs, ps) = pass_through();
if let Ok(mut v) = super::super::validator::Validator::load(
super::super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut vs.dxil.clone()).unwrap();
v.validate(&mut ps.dxil.clone()).unwrap();
}
let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap();
let root = host.root_signature(&vs, &ps).unwrap();
// Position (z 0.5, w 1) and an interpolant that is the position.
let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0];
for (name, corners) in [
("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]),
("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]),
("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]),
] {
let vertices = corners.map(vertex).concat();
let draw = |gs: Option<&[u8]>| {
let pso = host
.pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil)
.unwrap();
let d = Draw {
roots: Vec::new(),
textures: &[],
samplers: &[],
vertices: &vertices,
stride: 32,
size: (8, 8),
mesh_groups: 0,
};
host.draw(&root, &pso, &d).unwrap()
};
let whole = draw(Some(&gs[..]));
for (i, texel) in whole.iter().enumerate() {
let (x, y) = ((i % 8) as f32, (i / 8) as f32);
let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0];
assert!(
texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4),
"{name}: texel {i} is {texel:?}, not {want:?}"
);
}
let half = draw(None);
let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count();
assert!(missing >= 24, "{name}: only {missing} texels need the stage");
}
}
}
+125
View File
@@ -0,0 +1,125 @@
//! Immediate samplers: the console's four sampler words (the GPU's public
//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler.
//!
//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum
//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0
//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD
//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8),
//! magnification and minification filters (20-21, 22-23: point, linear,
//! anisotropic point, anisotropic linear), mip filter (26-27: none, point,
//! linear). Word 3: border colour (30-31: transparent black, opaque black,
//! opaque white, custom).
//!
//! Comparison is the sampling instruction's, not the sampler's: the console
//! encodes a comparison function in every sampler (D3D's default, less or
//! equal, when unused).
/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`,
/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and
/// `D3D12_STATIC_BORDER_COLOR` values.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StaticSampler {
pub filter: u32,
/// U, V, W.
pub address: [u32; 3],
pub mip_lod_bias: f32,
pub max_anisotropy: u32,
pub comparison: u32,
pub border: u32,
pub min_lod: f32,
pub max_lod: f32,
}
// The floats come from fixed-point fields: never NaN.
impl Eq for StaticSampler {}
impl StaticSampler {
/// Decodes the four sampler words.
pub fn from_words(w: [u32; 4]) -> Self {
let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1);
// wrap, mirror, clamp, mirror once; the half-border modes have no
// D3D form and become their nearest.
let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize];
let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2));
let reduction = match bits(w[0], 29, 2) {
1 => 2,
2 => 3,
_ => 0,
};
let filter = if mag >= 2 || min >= 2 {
0x55 | reduction << 7
} else {
(min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7
};
let lod = |v: u32| v as f32 / 256.0;
// Without a mip filter the base level is sampled.
let (min_lod, max_lod) = if mip == 0 {
(0.0, 0.0)
} else {
(lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12)))
};
StaticSampler {
filter,
address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))),
mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0,
max_anisotropy: 1 << bits(w[0], 9, 3).min(4),
comparison: bits(w[0], 12, 3) + 1,
// shortcut: a custom border colour (type 3, a table entry) becomes
// transparent black; upgrade when a title uses one.
border: bits(w[3], 30, 2) % 3,
min_lod,
max_lod,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn console_compiled_samplers_decode() {
// Words the console compiler wrote for static samplers of known
// descriptions.
let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]);
assert_eq!(
point,
StaticSampler {
filter: 0,
address: [1, 2, 3],
mip_lod_bias: 0.5,
max_anisotropy: 1,
comparison: 4,
border: 2,
min_lod: 1.0,
max_lod: 5.25,
}
);
let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]);
assert_eq!(
(aniso.filter, aniso.address, aniso.max_anisotropy),
(0x55, [4, 5, 3], 8)
);
assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0));
let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]);
assert_eq!(
(compare.filter, compare.address, compare.border),
(0x14, [4, 1, 1], 1)
);
let minimum =
StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]);
assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5));
let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]);
assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0));
let max_aniso =
StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]);
assert_eq!(
(
max_aniso.filter,
max_aniso.max_anisotropy,
max_aniso.mip_lod_bias
),
(0x1D5, 16, 15.0)
);
}
}
+908
View File
@@ -0,0 +1,908 @@
//! A DXIL vertex, pixel, compute or mesh shader under construction: the module,
//! the `dx.op` declarations it calls, its signatures and bound resources,
//! and the metadata and container that wrap it up (SM 6.6, validator 1.6).
use super::bitcode::{Attr, Md, Module, Ty, V};
use super::container::{self, Binding, Psv, SigElement};
/// Where the shader reads its user data: `b0` in this space.
pub const USER_DATA_SPACE: u32 = 0;
/// Where immediate samplers are bound: `s<n>` in this space.
pub const SAMPLER_SPACE: u32 = 0;
/// Where root CBVs and SRVs are bound: `b<root parameter index>` and
/// `t<root parameter index>` in this space.
pub const ROOT_CBV_SPACE: u32 = 1;
/// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that
/// reads buffers through descriptors it picks from the view heap at an
/// index it computes (SM 6.6 dynamic resources): a raw buffer of
/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per
/// element of the buffer view at heap slot `i` (0: none or not a buffer).
/// The console's descriptor holds that stride and its hardware multiplies
/// the element index by it; the program's code does not say it, and the
/// used-resource list only names what tables hold. A shader that has this
/// root SRV also tells the host that the buffer views of the whole heap
/// must be ready when it runs, not only those its tables name.
pub const SLOT_STRIDES: u8 = 255;
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
/// Title memory by address (`resource::MEMORY`): console code reads and
/// writes through raw 40-bit addresses it takes from root constants,
/// descriptors and other memory (the ray-tracing structure builder and the
/// programs that walk its structures). The host keeps copies of the title
/// memory shaders use; a shader with such an access finds the copy by the
/// address:
///
/// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of
/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title
/// address space: the number of the host copy holding that page (0: none
/// yet) and the page's byte offset in that copy;
/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base`
/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself
/// reads zeros and drops writes;
/// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that
/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the
/// host reads afterwards to make those copies for the frames to come.
pub const SLOT_MEMORY: u8 = 254;
/// See [`SLOT_MEMORY`].
pub const SLOT_FAULTS: u8 = 253;
/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB.
pub const MEMORY_PAGES: u32 = 1 << 21;
/// Dwords of the [`SLOT_FAULTS`] buffer.
pub const MEMORY_FAULTS: u32 = 4096;
/// `RootType::Other` code of a user-data dword the host computes: the view
/// heap slot of the memory copies' views ([`SLOT_MEMORY`]).
pub const USER_MEMORY_BASE: u32 = 0x100;
/// `RootType::Other` code of a user-data dword the host computes: the low
/// 32 bits of the title address of the buffer view at dword `dword` of the
/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1:
/// its bits from 32 up. (Console code reads the address out of a buffer
/// descriptor and uses it as a pointer.)
pub const USER_VIEW_ADDRESS: u32 = 0x101;
/// `RootType::Other` code of a user-data dword the host computes: the
/// bytes (0 to 15) by which the raw view the host binds for the root view
/// of root parameter `slot` begins before the title's address. A raw view
/// begins on 16 bytes of its host buffer; the console's root views begin
/// anywhere (the structure builder's counters sit at addresses ending in
/// 4 and c). The shader adds the dword to every byte offset through that
/// view. Asked for every root UAV, and for the root SRVs of programs with
/// a spilled user-data table.
pub const USER_VIEW_BIAS: u32 = 0x103;
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
pub(crate) mod flags {
pub const RAW_BUFFERS: u64 = 1 << 4;
pub const DOUBLES: u64 = 1 << 2;
pub const STENCIL_REF: u64 = 1 << 11;
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
pub const WAVE_OPS: u64 = 1 << 19;
pub const BARYCENTRICS: u64 = 1 << 22;
pub const INT64: u64 = 1 << 20;
pub const ATOMIC_TYPED64: u64 = 1 << 27;
pub const ATOMIC_HEAP64: u64 = 1 << 32;
pub const RESOURCE_HEAP: u64 = 1 << 30;
pub const SAMPLER_HEAP: u64 = 1 << 31;
pub const ROVS: u64 = 1 << 18;
}
pub(crate) struct Types {
pub void: Ty,
pub i1: Ty,
pub i32: Ty,
pub f32: Ty,
pub handle: Ty,
pub props: Ty,
pub bind: Ty,
pub cbuf_ret: Ty,
pub res_ret: Ty,
}
/// What a mesh shader declares beyond its thread-group size.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Mesh {
pub max_vertices: u32,
pub max_primitives: u32,
/// 1 lines, 2 triangles.
pub topology: u8,
}
/// What a geometry shader declares: triangles in, triangle strips out on
/// stream 0, one instance.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Geometry {
pub max_vertices: u32,
}
/// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while
/// it is set read that slot for any view index at or past it. A read past a heap's end is
/// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is
/// larger) hung its GPU (GPU-based validation: "descriptor heap index out of bounds"), and AMD
/// RDNA3 took a page fault and removed the device.
static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null.
pub fn set_view_heap_limit(null_slot: u32) {
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
}
/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none).
pub fn view_heap_limit() -> u32 {
VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
}
pub(crate) struct Shader {
pub m: Module,
pub t: Types,
pub pixel: bool,
pub inputs: Vec<SigElement>,
pub outputs: Vec<SigElement>,
/// A mesh shader's per-primitive outputs.
pub prims: Vec<SigElement>,
/// A mesh shader (`threads` is its thread-group size).
pub mesh: Option<Mesh>,
/// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false.
pub geometry: Option<Geometry>,
/// Dwords of user data the shader reads (0: no user-data buffer).
pub user_data: u32,
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
pub samplers: u32,
/// Bit n: immediate sampler n is a comparison sampler.
pub cmp_samplers: u64,
/// Root CBVs read, by root parameter index, with their handles.
pub root_cbvs: Vec<(u8, V)>,
/// Root SRVs (raw buffers) read, likewise.
pub root_srvs: Vec<(u8, V)>,
/// Root UAVs (raw buffers) read or written, likewise.
pub root_uavs: Vec<(u8, V)>,
pub flags: u64,
/// Every UAV the shader opens is rasterizer ordered ([`Self::annotate`]).
pub rov: bool,
/// Heap handles made with a non-uniform index.
pub nonuniform_handles: u32,
/// A compute shader with this thread-group size.
pub threads: Option<[u32; 3]>,
/// The wave size a compute shader requires (`WaveSize`).
pub wave_size: Option<u32>,
/// Thread-group shared memory, in dwords.
pub lds_dwords: u32,
lds: Option<V>,
main: V,
pub entry: usize,
}
impl Shader {
pub fn new(pixel: bool) -> Self {
let mut m = Module::default();
let void = m.void();
let i1 = m.int(1);
let i8 = m.int(8);
let i32 = m.int(32);
let f32 = m.float();
let i8p = m.ptr(i8);
let handle = m.named_struct("dx.types.Handle", vec![i8p]);
let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]);
let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]);
let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]);
let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]);
let main_ty = m.func_ty(void, vec![]);
m.ptr(main_ty);
let main = m.function("main", main_ty, None, true);
let entry = m.new_block();
Shader {
m,
t: Types {
void,
i1,
i32,
f32,
handle,
props,
bind,
cbuf_ret,
res_ret,
},
pixel,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh: None,
geometry: None,
user_data: 0,
samplers: 0,
cmp_samplers: 0,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
root_uavs: Vec::new(),
flags: 0,
rov: false,
nonuniform_handles: 0,
threads: None,
wave_size: None,
lds_dwords: 0,
lds: None,
main,
entry,
}
}
/// The thread-group shared memory: `[lds_dwords x i32]` in address
/// space 3.
pub fn lds(&mut self) -> V {
if let Some(g) = self.lds {
return g;
}
let arr = self.m.array(self.lds_dwords, self.t.i32);
let g = self.m.global("lds", arr, 3);
self.lds = Some(g);
g
}
/// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`.
pub fn op(
&mut self,
block: usize,
name: &str,
attr: Attr,
ret: Ty,
opcode: u32,
args: &[V],
) -> V {
let mut params = vec![self.t.i32];
params.extend(args.iter().map(|&a| self.m.type_of(a)));
let fty = self.m.func_ty(ret, params);
self.m.ptr(fty);
let f = self
.m
.function(&format!("dx.op.{name}"), fty, Some(attr), false);
let mut all = vec![self.m.i32(opcode)];
all.extend(args);
self.m.call(block, f, all)
}
/// The handle of the user-data constant buffer, made in the entry block.
pub fn user_data_handle(&mut self) -> V {
let bind = [
self.m.i32(0),
self.m.i32(0),
self.m.i32(USER_DATA_SPACE),
self.m.i8(2), // CBV
];
let bind = self.m.aggregate(self.t.bind, &bind);
let block = self.entry;
let (i, f) = (self.m.i32(0), self.m.bool(false));
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, i, f],
);
// The size is known in `finish`, which fixes this placeholder.
self.annotate(block, h, 13, u32::MAX)
}
/// The handle of the root CBV of root parameter `slot`, made in the
/// entry block.
pub fn root_cbv_handle(&mut self, slot: u8) -> V {
if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) {
return h;
}
let r = self.m.i32(u32::from(slot));
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)];
let bind = self.m.aggregate(self.t.bind, &bind);
let f = self.m.bool(false);
let block = self.entry;
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, r, f],
);
let h = self.annotate(block, h, 13, 65536);
self.root_cbvs.push((slot, h));
h
}
/// The handle of the root SRV (a raw buffer) of root parameter `slot`.
pub fn root_srv_handle(&mut self, slot: u8) -> V {
if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) {
return h;
}
let r = self.m.i32(u32::from(slot));
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)];
let bind = self.m.aggregate(self.t.bind, &bind);
let f = self.m.bool(false);
let block = self.entry;
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, r, f],
);
let h = self.annotate(block, h, 11, 0);
self.flags |= flags::RAW_BUFFERS;
self.root_srvs.push((slot, h));
h
}
/// The handle of the root UAV (a raw buffer) of root parameter `slot`:
/// `u<slot>` in [`ROOT_CBV_SPACE`].
pub fn root_uav_handle(&mut self, slot: u8) -> V {
if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) {
return h;
}
let r = self.m.i32(u32::from(slot));
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)];
let bind = self.m.aggregate(self.t.bind, &bind);
let f = self.m.bool(false);
let block = self.entry;
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, r, f],
);
let h = self.annotate(block, h, 11 | 0x1000, 0);
self.flags |= flags::RAW_BUFFERS;
self.root_uavs.push((slot, h));
h
}
/// The handle of immediate sampler `n` (a comparison sampler when its
/// bit in `cmp_samplers` is set).
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
let bind = [
self.m.i32(n),
self.m.i32(n),
self.m.i32(SAMPLER_SPACE),
self.m.i8(3), // sampler
];
let bind = self.m.aggregate(self.t.bind, &bind);
let (i, f) = (self.m.i32(n), self.m.bool(false));
let h = self.op(
block,
"createHandleFromBinding",
Attr::ReadNone,
self.t.handle,
217,
&[bind, i, f],
);
let cmp = if self.cmp_samplers >> n & 1 != 0 {
0x8000
} else {
0
};
self.annotate(block, h, 14 | cmp, 0)
}
/// Annotates a handle with its resource properties. Bit 12 of `props0` is
/// "UAV"; with `rov` set a UAV also gets bit 13, rasterizer ordered.
pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V {
let props0 = if self.rov && props0 & 0x1000 != 0 {
self.flags |= flags::ROVS;
props0 | 0x2000
} else {
props0
};
let p = [self.m.i32(props0), self.m.i32(props1)];
let p = self.m.aggregate(self.t.props, &p);
self.op(
block,
"annotateHandle",
Attr::ReadNone,
self.t.handle,
216,
&[h, p],
)
}
/// A descriptor heap handle, annotated with `props`; `nonuniform` when
/// the index may differ between lanes (`NonUniformResourceIndex`).
pub fn heap_handle(
&mut self,
block: usize,
index: V,
sampler: bool,
nonuniform: bool,
props: (u32, u32),
) -> V {
// a view index past the host heap (`set_view_heap_limit`) reads its null slot instead
let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed);
// (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid)
let index = if !sampler && limit != 0 {
let null = self.m.i32(limit);
let i32t = self.t.i32;
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]);
self.m.tag(v, super::bitcode::Tag::Clamp);
v
} else if sampler {
// A sampler heap has at most 2,048 samplers on any host: an
// index past that (a number read from memory the host has not
// got yet) stays inside the largest heap there is.
// shortcut: not the bound heap's own count, which a title
// heap smaller than 2,048 would need.
let last = self.m.i32(2047);
let i32t = self.t.i32;
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
self.m.tag(v, super::bitcode::Tag::Clamp);
v
} else {
index
};
self.flags |= if sampler {
flags::SAMPLER_HEAP
} else {
flags::RESOURCE_HEAP
};
self.nonuniform_handles += u32::from(nonuniform);
let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform));
let h = self.op(
block,
"createHandleFromHeap",
Attr::ReadNone,
self.t.handle,
218,
&[index, s, n],
);
self.annotate(block, h, props.0, props.1)
}
/// The finished container.
pub fn finish(mut self) -> Vec<u8> {
let ud_size = (self.user_data * 4).next_multiple_of(16);
self.fix_user_data_size(ud_size);
// The clean-up, before anything is declared about the code: a
// feature whose last use it removed must not be declared (the
// validator compares the flags with what the code uses).
let passes = super::shader_opt() & super::bitcode::opt::MODULE;
if passes != 0 {
self.m.optimise(passes);
let used = self.m.usage();
for (flag, used) in [
(flags::WAVE_OPS, used.wave_ops),
(flags::ROVS, used.rov),
(flags::INT64, used.int64),
(flags::TYPED_UAV_LOADS, used.typed_uav_loads),
(flags::RESOURCE_HEAP, used.heap_views),
(flags::SAMPLER_HEAP, used.heap_samplers),
(flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64),
] {
if !used {
self.flags &= !flag;
}
}
}
let mut resources = None;
let mut bindings = Vec::new();
let i32c = |s: &mut Self, v: u32| {
let c = s.m.i32(v);
s.m.md_value(c)
};
if self.user_data > 0
|| self.samplers > 0
|| !self.root_cbvs.is_empty()
|| !self.root_srvs.is_empty()
|| !self.root_uavs.is_empty()
{
let empty = self.m.md_str("");
let mut cbvs = None;
let mut cbv_list = Vec::new();
if self.user_data > 0 {
let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32);
let ty = self.m.named_struct("UserData", vec![arr]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let ops = vec![
Some(i32c(&mut self, 0)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, USER_DATA_SPACE)),
Some(i32c(&mut self, 0)),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, ud_size)),
None,
];
cbv_list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 2,
space: USER_DATA_SPACE,
register: 0,
dxil_kind: 13,
});
}
let blob = self.m.array(16384, self.t.i32);
let ty = self.m.named_struct("RootCbv", vec![blob]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
for (slot, _) in self.root_cbvs.clone() {
let ops = vec![
Some(i32c(&mut self, cbv_list.len() as u32)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, ROOT_CBV_SPACE)),
Some(i32c(&mut self, u32::from(slot))),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, 65536)),
None,
];
cbv_list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 2,
space: ROOT_CBV_SPACE,
register: u32::from(slot),
dxil_kind: 13,
});
}
if !cbv_list.is_empty() {
cbvs = Some(self.m.md_node(cbv_list));
}
let mut srvs = None;
if !self.root_srvs.is_empty() {
let ty = self
.m
.named_struct("struct.ByteAddressBuffer", vec![self.t.i32]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let mut list = Vec::new();
for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() {
let ops = vec![
Some(i32c(&mut self, n as u32)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, ROOT_CBV_SPACE)),
Some(i32c(&mut self, u32::from(slot))),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, 11)),
Some(i32c(&mut self, 0)),
None,
];
list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 4,
space: ROOT_CBV_SPACE,
register: u32::from(slot),
dxil_kind: 11,
});
}
srvs = Some(self.m.md_node(list));
}
let mut uavs = None;
if !self.root_uavs.is_empty() {
let ty = self
.m
.named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let no = self.m.bool(false);
let no = self.m.md_value(no);
let mut list = Vec::new();
for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() {
// Id, variable, name, space, lower bound, range size,
// shape (11: raw buffer), globally coherent, counter,
// rasterizer ordered, no extra properties.
let ordered = self.m.bool(self.rov);
let ordered = self.m.md_value(ordered);
let ops = vec![
Some(i32c(&mut self, n as u32)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, ROOT_CBV_SPACE)),
Some(i32c(&mut self, u32::from(slot))),
Some(i32c(&mut self, 1)),
Some(i32c(&mut self, 11)),
Some(no),
Some(no),
Some(ordered),
None,
];
list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 7,
space: ROOT_CBV_SPACE,
register: u32::from(slot),
dxil_kind: 11,
});
}
uavs = Some(self.m.md_node(list));
}
let mut samplers = None;
if self.samplers > 0 {
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
let p = self.m.ptr(ty);
let u = self.m.undef(p);
let mut list = Vec::new();
for n in 0..self.samplers {
let kind = (self.cmp_samplers >> n & 1) as u32;
let ops = vec![
Some(i32c(&mut self, n)),
Some(self.m.md_value(u)),
Some(empty),
Some(i32c(&mut self, SAMPLER_SPACE)),
Some(i32c(&mut self, n)),
Some(i32c(&mut self, 1)),
// Sampler kind: 1 comparison.
Some(i32c(&mut self, kind)),
None,
];
list.push(Some(self.m.md_node(ops)));
bindings.push(Binding {
kind: 1,
space: SAMPLER_SPACE,
register: n,
dxil_kind: 14,
});
}
samplers = Some(self.m.md_node(list));
}
resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers]));
// PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs.
bindings.sort_by_key(|b| match b.kind {
2 => 0,
1 => 1,
7 => 3,
_ => 2,
});
}
if let Some(r) = resources {
self.m.named_md("dx.resources", vec![r]);
}
let graphics = self.threads.is_none() || self.mesh.is_some();
if graphics {
// shortcut: every output is declared to depend on every input; the
// exact sets need a dependence pass. Drivers read this state.
let scalars = |els: &[SigElement]| {
els.iter()
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
.max()
.unwrap_or(0)
};
let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs));
let mut view = vec![ni, no];
// Mesh shaders have no inputs: then the primitive outputs' count.
if self.mesh.is_some() {
view.push(scalars(&self.prims));
}
for _ in 0..ni {
for k in 0..no.div_ceil(32) {
let bits = (no - 32 * k).min(32);
view.push(if bits == 32 {
u32::MAX
} else {
(1 << bits) - 1
});
}
}
// A geometry shader lists four streams: the other three have
// no outputs.
if self.geometry.is_some() {
view.extend([0, 0, 0]);
}
let arr = self.m.array(view.len() as u32, self.t.i32);
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
let arr = self.m.aggregate(arr, &elems);
let arr = self.m.md_value(arr);
let view_node = self.m.md_node(vec![Some(arr)]);
self.m.named_md("dx.viewIdState", vec![view_node]);
}
let sigs = if graphics {
let ins = self.signature_md(self.inputs.clone());
let outs = self.signature_md(self.outputs.clone());
let prims = self.signature_md(self.prims.clone());
Some(self.m.md_node(vec![ins, outs, prims]))
} else {
None
};
// A pixel shader with an SV_StencilRef output (as DXC collects it).
if self.pixel && self.outputs.iter().any(|o| o.kind == 20) {
self.flags |= flags::STENCIL_REF;
}
// Entry properties: shader flags (tag 0), geometry state (1),
// thread-group size (4), wave size (11).
let mut props = Vec::new();
if self.flags != 0 {
props.push(i32c(&mut self, 0));
let i64t = self.m.int(64);
let f = self.m.int_const(i64t, self.flags as i64);
props.push(self.m.md_value(f));
}
if let Some(g) = self.geometry {
// Input primitive (3: triangles), maximum vertices, stream
// mask, output topology (5: triangle strips), instances.
props.push(i32c(&mut self, 1));
let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n)));
props.push(self.m.md_node(state.to_vec()));
}
if let Some(threads) = self.threads {
let t = threads.map(|n| Some(i32c(&mut self, n)));
let t = self.m.md_node(t.to_vec());
match self.mesh {
// Mesh state (tag 9): threads, maximum vertices and
// primitives, topology, payload bytes.
Some(mesh) => {
props.push(i32c(&mut self, 9));
let state = [
mesh.max_vertices,
mesh.max_primitives,
mesh.topology.into(),
0,
]
.map(|n| Some(i32c(&mut self, n)));
let mut node = vec![Some(t)];
node.extend(state);
props.push(self.m.md_node(node));
}
None => {
props.push(i32c(&mut self, 4));
props.push(t);
}
}
}
if let Some(n) = self.wave_size {
props.push(i32c(&mut self, 11));
let n = Some(i32c(&mut self, n));
props.push(self.m.md_node(vec![n]));
}
let props =
(!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect()));
let main = self.m.md_value(self.main);
let name = self.m.md_str("main");
let entry = self
.m
.md_node(vec![Some(main), Some(name), sigs, resources, props]);
let ident = self.m.md_str("victory");
let ident = self.m.md_node(vec![Some(ident)]);
self.m.named_md("llvm.ident", vec![ident]);
let one = i32c(&mut self, 1);
let six = i32c(&mut self, 6);
let version = self.m.md_node(vec![Some(one), Some(six)]);
self.m.named_md("dx.version", vec![version]);
self.m.named_md("dx.valver", vec![version]);
// Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh.
let (name, kind) = match (self.threads, self.pixel) {
_ if self.mesh.is_some() => ("ms", 13u32),
_ if self.geometry.is_some() => ("gs", 2),
(Some(_), _) => ("cs", 5u32),
(None, true) => ("ps", 0),
(None, false) => ("vs", 1),
};
let name = self.m.md_str(name);
let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]);
self.m.named_md("dx.shaderModel", vec![sm]);
self.m.named_md("dx.entryPoints", vec![entry]);
let bitcode = self.m.write();
super::bitcode::census::note(&self.m, &bitcode);
let mut dxil = Vec::with_capacity(24 + bitcode.len());
dxil.extend((kind << 16 | 0x66).to_le_bytes());
dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
dxil.extend(b"DXIL");
dxil.extend(0x106u32.to_le_bytes());
dxil.extend(16u32.to_le_bytes());
dxil.extend((bitcode.len() as u32).to_le_bytes());
dxil.extend(&bitcode);
let mut features = 0u64;
if self.flags & flags::DOUBLES != 0 {
features |= 0x1;
}
if self.flags & flags::STENCIL_REF != 0 {
features |= 0x200;
}
if self.flags & flags::TYPED_UAV_LOADS != 0 {
features |= 0x800;
}
if self.flags & flags::ROVS != 0 {
features |= 0x1000;
}
if self.flags & flags::WAVE_OPS != 0 {
features |= 0x4000;
}
if self.flags & flags::INT64 != 0 {
features |= 0x8000;
}
if self.flags & flags::BARYCENTRICS != 0 {
features |= 0x2_0000;
}
if self.flags & flags::RESOURCE_HEAP != 0 {
features |= 0x200_0000;
}
if self.flags & flags::SAMPLER_HEAP != 0 {
features |= 0x400_0000;
}
if self.flags & flags::ATOMIC_TYPED64 != 0 {
features |= 0x40_0000;
}
if self.flags & flags::ATOMIC_HEAP64 != 0 {
features |= 0x1000_0000;
}
let sfi0 = features.to_le_bytes();
let isg1 = container::signature(&self.inputs, true);
let osg1 = container::signature(&self.outputs, false);
let flag = if self.pixel {
self.outputs.iter().any(|o| (17..=19).contains(&o.kind))
} else {
self.outputs.iter().any(|o| o.kind == 3)
};
let psv0 = container::psv(&Psv {
stage: kind as u8,
flag: flag && self.threads.is_none(),
inputs: &self.inputs,
outputs: &self.outputs,
prims: &self.prims,
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
geometry: self.geometry.map(|g| g.max_vertices),
bindings: &bindings,
threads: self.threads.unwrap_or_default(),
wave_size: self.wave_size,
});
let hash = [0u8; 20];
let psg1 = container::signature(&self.prims, false);
let mut parts: Vec<(&[u8; 4], &[u8])> =
vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)];
if self.mesh.is_some() {
parts.push((b"PSG1", &psg1));
}
parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]);
container::build(&parts)
}
/// The user-data buffer's annotation carries its size, known only now.
fn fix_user_data_size(&mut self, size: u32) {
let old = [self.m.i32(13), self.m.i32(u32::MAX)];
let old = self.m.aggregate(self.t.props, &old);
let new = [self.m.i32(13), self.m.i32(size)];
let new = self.m.aggregate(self.t.props, &new);
self.m.replace_const(old, new);
}
fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> {
if elements.is_empty() {
return None;
}
let mut list = Vec::new();
for (id, e) in elements.iter().enumerate() {
let c32 = |s: &mut Self, v: u32| {
let c = s.m.i32(v);
Some(s.m.md_value(c))
};
let c8 = |s: &mut Self, v: u8| {
let c = s.m.i8(v);
Some(s.m.md_value(c))
};
let idx = c32(self, e.index);
let indices = Some(self.m.md_node(vec![idx]));
let usage = if e.usage != 0 {
let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage)));
Some(self.m.md_node(vec![tag, mask]))
} else {
None
};
let ops = vec![
c32(self, id as u32),
Some(self.m.md_str(&e.name)),
c8(self, e.comp),
c8(self, e.kind),
indices,
c8(self, e.interp),
c32(self, 1),
c8(self, e.cols),
c32(self, e.row.unwrap_or(u32::MAX)),
c8(self, if e.row.is_some() { e.col } else { u8::MAX }),
usage,
];
list.push(Some(self.m.md_node(ops)));
}
Some(self.m.md_node(list))
}
}
+218
View File
@@ -0,0 +1,218 @@
//! Jump threading for uniform diamonds. One arm can set a flag that fixes
//! the join's next branch. Registers recycled on that arm then never reach
//! the other successor, even if an ordinary SSA phi joins their values.
use crate::gfx10::{Fields, Operand, Valu};
use crate::ir::{Exit, Program, Reg, Value};
use crate::structure::{Atom, Bool, LaneExit, Structured};
use std::collections::HashMap;
fn plain(v: &Valu) -> bool {
v.abs == 0
&& v.neg == 0
&& v.opsel == 0
&& !v.clamp
&& v.omod == 0
&& v.sdwa.is_none()
&& v.dpp.is_none()
}
fn immediate(op: Operand) -> Option<u32> {
match op {
Operand::Const(c) => crate::resource::inline(c),
Operand::Literal(n) => Some(n),
_ => None,
}
}
pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> {
let mut constants = HashMap::new();
for (b, block) in p.blocks.iter().enumerate() {
for (i, inst) in block.insts.iter().enumerate() {
if inst.name() == "v_mov_b32"
&& st.guards[b][i].is_none()
&& let Fields::Valu(v) = &inst.fields
&& plain(v)
&& let [src] = v.src.as_slice()
&& let Some(word) = immediate(*src)
&& let [(_, dst)] = inst.writes.as_slice()
{
constants.insert(*dst, word);
}
}
}
let mut edges = Vec::new();
for (join, block) in p.blocks.iter().enumerate() {
let LaneExit::Branch {
when,
taken,
not_taken,
} = st.exits[join]
else {
continue;
};
if when == Bool::TRUE || when == Bool::FALSE {
continue;
}
// Keep memory accesses and wave operations at their original
// reconvergence point. Only duplicate scalar ALU and comparisons.
if !block.insts.iter().all(|i| match &i.fields {
Fields::Sop { .. } => true,
Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"),
Fields::Valu(_) => i.name().starts_with("v_cmp_"),
_ => false,
}) {
continue;
}
let [a, b] = block.preds.as_slice() else {
continue;
};
// A triangle has a direct edge from the fork to the join. A full
// diamond has an unconditional jump at the end of each arm.
let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() {
&[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork),
_ => None,
};
let fork = match (arm_from(*a), arm_from(*b)) {
(Some(f), Some(g)) if f == g => f,
(_, Some(f)) if f == *a => f,
(Some(f), _) if f == *b => f,
_ => continue,
};
if fork == join || a == b {
continue;
}
let LaneExit::Branch { when: entry, .. } = st.exits[fork] else {
continue;
};
if !st
.bools
.support(entry)
.iter()
.all(|a| matches!(a, Atom::Uniform(_)))
{
continue;
}
for (edge, &pred) in block.preds.iter().enumerate() {
let value = |v: Value| {
let input = block
.phis
.iter()
.find(|p| p.value == v)
.map_or(v, |p| p.args[edge]);
constants.get(&input).copied()
};
// Restrict the branch's decision diagram to known comparisons.
// Unknown tests stop the proof. Keep the original join for the
// other arm, which may still go either way.
let mut cond = when;
while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) {
let Some(inst) = block
.insts
.iter()
.find(|i| i.writes.iter().any(|&(_, v)| v == id))
else {
break;
};
let Fields::Valu(v) = &inst.fields else { break };
let [left, right] = v.src.as_slice() else {
break;
};
let operand = |op| match op {
Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?),
_ => immediate(op),
};
let (Some(x), Some(y)) = (operand(*left), operand(*right)) else {
break;
};
if !plain(v) {
break;
}
let yes = match inst.name() {
"v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y,
"v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y,
_ => break,
};
cond = if yes { hi } else { lo };
}
if cond == Bool::TRUE || cond == Bool::FALSE {
edges.push((
pred,
join,
if cond == Bool::TRUE { taken } else { not_taken },
));
break;
}
}
}
edges
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir;
use crate::structure;
// s8 initially holds a descriptor address. One arm overwrites it with
// a buffer load and sets v1. Only that arm can use s8 as the stored value.
const WORDS: [u32; 19] = [
0xbe810380, // s1 = 0 (table address high)
0xf4080200, 0xfa000000, // load SRV into s[8:11]
0xf4080300, 0xfa000020, // load UAV into s[12:15]
0x7e020280, // v1 = 0
0xbf068002, 0xbf850003, // if s2 == 0, jump to join
0xf4200204, 0xfa00000c, // s8 = buffer.Load(12)
0x7e020281, // v1 = 1
0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant
0x7e060208, 0xbf820001, // v3 = s8, jump to store
0x7e060293, // constant: v3 = 19
0xe0700000, 0x80030300, // store v3 at byte 0
0xbf810000, // end
];
fn program(words: &[u32]) -> Program {
ir::build(
&words
.iter()
.flat_map(|w| w.to_le_bytes())
.collect::<Vec<_>>(),
false,
4,
)
.unwrap()
}
#[test]
fn only_the_buffer_load_reaches_the_numeric_read() {
let p = program(&WORDS);
let st = structure::structure(&p).unwrap();
let edges = constant_edges(&p, &st);
assert_eq!(edges, [(0, 2, 4)]);
let p = ir::thread_edges(&p, &edges).unwrap();
let load = &p.blocks[1].insts[0];
assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8)));
assert_eq!(
p.blocks[0].exit,
Exit::Branch {
taken: 6,
not_taken: 1
}
);
assert_eq!(p.blocks[6].exit, Exit::Jump(4));
assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len());
}
#[test]
fn leaves_unknown_flags_and_divergent_forks_alone() {
let mut words = WORDS;
words[5] = 0x7e020202; // v1 = s2
words[10] = 0x7e020203; // v1 = s3
let p = program(&words);
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
let mut words = WORDS;
words[6] = 0x7d840080; // compare 0 with lane-dependent v0
words[7] = 0xbf870003; // branch on VCC
let p = program(&words);
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
}
}
+221
View File
@@ -0,0 +1,221 @@
//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the
//! offline batch. Translated shaders do not need it: they carry the
//! container hash we compute (`container::hash`).
//!
//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's
//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it.
use std::ffi::c_void;
use std::path::PathBuf;
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
type Hresult = i32;
#[repr(C)]
struct Guid(u32, u16, u16, [u8; 8]);
const CLSID_DXC_VALIDATOR: Guid = Guid(
0x8ca3_e215,
0xf728,
0x4cf3,
[0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1],
);
const IID_IDXC_VALIDATOR: Guid = Guid(
0xa6e8_2bd2,
0x1fd7,
0x4826,
[0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a],
);
/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass.
const IN_PLACE_EDIT: u32 = 1;
type CreateInstance =
unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult;
/// COM object: a pointer to a table of method pointers.
type Object = *mut *const usize;
unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F {
// SAFETY: the caller names a slot of the object's interface.
unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) }
}
unsafe fn release(obj: Object) {
if !obj.is_null() {
// SAFETY: slot 2 of every COM interface is Release.
unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) };
}
}
/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release,
/// GetBufferPointer, GetBufferSize. Lives on the caller's stack.
#[repr(C)]
struct Blob {
vtable: *const BlobVtable,
data: *mut u8,
len: usize,
}
/// IUnknown and IDxcBlob, as raw GUID bytes.
const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
const IDXC_BLOB: [u8; 16] = [
0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02,
];
unsafe extern "system" fn blob_qi(
this: *mut Blob,
iid: *const [u8; 16],
out: *mut *mut c_void,
) -> Hresult {
// SAFETY: the validator passes valid pointers.
unsafe {
if *iid == IUNKNOWN || *iid == IDXC_BLOB {
*out = this.cast();
0
} else {
*out = std::ptr::null_mut();
0x8000_4002_u32 as i32 // E_NOINTERFACE
}
}
}
unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 {
1
}
unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 {
// SAFETY: `this` is our blob.
unsafe { (*this).data }
}
unsafe extern "system" fn blob_len(this: *mut Blob) -> usize {
// SAFETY: `this` is our blob.
unsafe { (*this).len }
}
#[repr(C)]
struct BlobVtable {
qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult,
add_ref: unsafe extern "system" fn(*mut Blob) -> u32,
release: unsafe extern "system" fn(*mut Blob) -> u32,
ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8,
len: unsafe extern "system" fn(*mut Blob) -> usize,
}
static BLOB_VTABLE: BlobVtable = BlobVtable {
qi: blob_qi,
add_ref: blob_ref,
release: blob_ref,
ptr: blob_ptr,
len: blob_len,
};
pub struct Validator {
object: Object,
}
// SAFETY: the validator object is free-threaded (DXC's validator has no
// thread affinity); calls are serialised by `&mut self`.
unsafe impl Send for Validator {}
impl Validator {
/// Where `dxil.dll` is looked for.
pub fn default_path() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("VICTORY_DXIL") {
return Some(p.into());
}
let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits)
.ok()?
.filter_map(Result::ok)
.map(|e| e.path().join(r"x64\dxil.dll"))
.filter(|p| p.exists())
.collect();
versions.sort();
versions.pop()
}
/// Loads `path`'s validator (or `dxil.dll` from the DLL search path).
pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> {
let name: Vec<u16> = path
.map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned())
.to_string_lossy()
.encode_utf16()
.chain([0])
.collect();
// SAFETY: plain Win32 calls with a NUL-terminated name.
unsafe {
let module = LoadLibraryW(name.as_ptr());
if module.is_null() {
return Err(format!("cannot load {}", String::from_utf16_lossy(&name)));
}
let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast())
.ok_or("dxil.dll lacks DxcCreateInstance")?;
let create: CreateInstance = std::mem::transmute(create);
let mut object = std::ptr::null_mut();
let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object);
if hr < 0 || object.is_null() {
return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}"));
}
Ok(Validator {
object: object.cast(),
})
}
}
/// Validates `container` and signs it in place; the error text if it
/// is rejected.
pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> {
let mut blob = Blob {
vtable: &BLOB_VTABLE,
data: container.as_mut_ptr(),
len: container.len(),
};
// SAFETY: IDxcValidator::Validate (slot 3) with our blob; then
// IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and
// IDxcBlob GetBufferPointer (3) / GetBufferSize (4).
unsafe {
let mut result: Object = std::ptr::null_mut();
let validate: unsafe extern "system" fn(
Object,
*mut Blob,
u32,
*mut Object,
) -> Hresult = method(self.object, 3);
let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result);
if hr < 0 || result.is_null() {
return Err(format!("Validate failed: {hr:#x}"));
}
let mut status = 0;
let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult =
method(result, 3);
get_status(result, &mut status);
let mut text = String::new();
if status < 0 {
let mut errors: Object = std::ptr::null_mut();
let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult =
method(result, 5);
if get_errors(result, &mut errors) >= 0 && !errors.is_null() {
let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3);
let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4);
let bytes = std::slice::from_raw_parts(ptr(errors), len(errors));
text = String::from_utf8_lossy(bytes)
.trim_end_matches('\0')
.trim()
.into();
release(errors);
}
if text.is_empty() {
text = format!("rejected ({status:#x})");
}
}
release(result);
if status < 0 { Err(text) } else { Ok(()) }
}
}
}
impl Drop for Validator {
fn drop(&mut self) {
// SAFETY: we own one reference.
unsafe { release(self.object) };
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,435 @@
//! End-to-end tests of waterfall loops over per-lane descriptors: the
//! synthetic GFX10 programs of `resource::tests` lowered to DXIL, validated
//! by `dxil.dll` when present, and run on the host GPU and WARP, each lane
//! reading the resource its own descriptor names.
use windows::Win32::Graphics::Direct3D12::*;
use super::host::{Dispatch, Host, Root, Stride, View};
use super::{HostShader, lower, validator};
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
use crate::{io, ir, resource, structure};
/// Lowers a wave32 compute program of 32 threads with the table of views at
/// s0 (textures, or with `buffers` structured buffers of dwords, at entries
/// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1.
fn build(words: &[u32], buffers: bool) -> HostShader {
let table = |user_data: u8| RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data,
slot: user_data,
};
let range = |kind, table_offset_dwords, dwords, stride, user_data| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: 0,
stride,
dwords,
user_data,
slot: user_data,
};
let views = if buffers {
range(ResourceType::Srv, 0, 4, 4, 0)
} else {
range(ResourceType::Srv, 0, 8, 0, 0)
};
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 32,
layout: vec![table(0), table(1)],
used: vec![
views,
range(ResourceType::Uav, 16, 4, 0, 0),
range(ResourceType::Sampler, 0, 4, 0, 1),
],
io: StageIo::Cs(ComputeIo {
rsrc2: 2 << 1,
threads: [32, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track");
let io = io::raise(&p, &native).expect("io::raise");
let lowered = lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})
.expect("lower");
// One access with each lane's own heap index, no wave operation.
assert_eq!(lowered.nonuniform_handles, 1);
assert!(!lowered.wave_ops);
let shader = HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
v.validate(&mut shader.dxil.clone())
.expect("DXIL validation failed");
} else {
eprintln!("no dxil.dll; validation skipped");
}
shader
}
/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the
/// hardware GPU and on WARP (each skipped without a device) and returns,
/// per one that ran, the UAV's 32 dwords.
fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
let samplers = [D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MaxAnisotropy: 1,
MaxLOD: f32::MAX,
..Default::default()
}];
let mut out = Vec::new();
// One GPU test at a time, with the VALU tests: in parallel on the
// hardware adapter and WARP the test process sometimes died of an
// access violation (7 of 24 runs of these four tests).
let _one = super::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {label} device; skipped");
continue;
};
let (root, pso) = match host.compute_pipeline(shader) {
Ok(p) => p,
Err(e) => panic!("{label}: compute_pipeline failed: {e}"),
};
// Both tables start at heap index 0.
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
assert_eq!(u.root, RootType::Table, "{u:?}");
ud[u.index as usize] = 0;
}
let words = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views,
samplers: &samplers,
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
out.push((label, words[0].clone()));
}
out
}
/// The red channel each lane sampled from two 1x1 textures, red 1.0 at
/// heap index 0 and 2.0 at 1.
fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec<f32>)> {
let first = [[1.0f32, 0.0, 0.0, 1.0]];
let second = [[2.0f32, 0.0, 0.0, 1.0]];
let views = [
View::Texture(1, 1, &first),
View::Texture(1, 1, &second),
View::RawUav(32),
];
run(shader, &views)
.into_iter()
.map(|(label, words)| (label, words.into_iter().map(f32::from_bits).collect()))
.collect()
}
#[test]
fn lanes_sample_the_texture_their_if_else_arm_chose() {
use crate::resource::tests::WATERFALL_JOINED_WAVE32;
let shader = build(WATERFALL_JOINED_WAVE32, false);
for (label, red) in sampled(&shader) {
// Lanes below 16 took the first texture, the others the second.
let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect();
assert_eq!(red, want, "{label}");
}
}
#[test]
fn lanes_sample_the_texture_their_arm_loaded_or_picked() {
use crate::resource::tests::WATERFALL_JOINED_MIXED_WAVE32;
let shader = build(WATERFALL_JOINED_MIXED_WAVE32, false);
for (label, red) in sampled(&shader) {
// Lanes below 16 loaded entry (lane & 1); of the others, lanes
// below 24 picked the first, the rest the second.
let want: Vec<f32> = (0..32)
.map(|l| match l {
0..16 => [1.0, 2.0][l & 1],
16..24 => 1.0,
_ => 2.0,
})
.collect();
assert_eq!(red, want, "{label}");
}
}
#[test]
fn lanes_load_from_the_buffer_their_nested_arms_chose() {
use crate::resource::tests::WATERFALL_JOINED_BUFFER_WAVE32;
let shader = build(WATERFALL_JOINED_BUFFER_WAVE32, true);
let first: Vec<u32> = (0..32).map(|i| 100 + i).collect();
let second: Vec<u32> = (0..32).map(|i| 200 + i).collect();
let views = [
View::Buffer {
data: &first,
stride: Stride::Structured(4),
},
View::Buffer {
data: &second,
stride: Stride::Structured(4),
},
View::RawUav(32),
];
for (label, got) in run(&shader, &views) {
// Dword `lane` of the first buffer below 16, of the second from 16
// to 23; lanes from 24 on load and store nothing.
let want: Vec<u32> = (0..32)
.map(|l| match l {
0..16 => 100 + l,
16..24 => 200 + l,
_ => 0,
})
.collect();
assert_eq!(got, want, "{label}");
}
}
#[test]
fn lanes_sample_the_entry_their_offset_names_in_the_console_waterfall() {
use crate::resource::tests::WATERFALL_INDEXED_WAVE32;
let shader = build(WATERFALL_INDEXED_WAVE32, false);
let results = sampled(&shader);
assert!(!results.is_empty());
for (label, red) in results {
// Even lanes hold entry 0's offset, odd lanes entry 1's.
let want: Vec<f32> = (0..32).map(|l| [1.0, 2.0][l & 1]).collect();
assert_eq!(red, want, "{label}");
}
}
#[test]
fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() {
use crate::resource::tests::cmpx_waterfall;
// Lanes below 16 hold the first descriptor, the others the second.
let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect();
for folded in [false, true] {
let shader = build(&cmpx_waterfall(false, folded), false);
let results = sampled(&shader);
assert!(!results.is_empty());
for (label, red) in results {
assert_eq!(red, want, "{label}, folded {folded}");
}
}
}
#[test]
fn immediate_sampler_chosen_by_control_flow() {
let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit];
let s_mov_zero = |dst: u8| 0xBE80_0380 | (dst as u32) << 16;
let s_load_x8 = |dst: u8, base: u8| [0x3D << 26 | 0x03 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25];
let s_load_x4_off = |dst: u8, base: u8, off: u32| [0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25 | off];
// image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
let image_sample_lz: [u32; 2] = [
0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, // dmask=1, dim=2D(1)
(16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2,
];
// buffer_store_dword v4, off, s[20:23], 0
let buf_store: [u32; 2] = [0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8];
// Two distinct valid immediate sampler descriptors (different wrap/filter bits).
let samp_a: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0000, 0];
let samp_b: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0001, 0];
for (case_name, alt) in [("same_sampler", samp_a), ("different_samplers", samp_b)] {
let mut words = Vec::new();
// s[2:3] = view table base (s0, 0).
words.push(0xBE80_0300 | (2 << 16)); // s_mov_b32 s2, s0
words.push(s_mov_zero(3));
words.extend_from_slice(&s_load_x8(8, 2)); // s[8:15] = texture SRV (offset 0)
words.extend_from_slice(&s_load_x4_off(20, 2, 64)); // s[20:23] = raw UAV (offset 16 dwords = 64B)
// v2 = 0.5, v3 = 0.5 (sample coordinates).
words.push(0x7E00_02F0 | (2 << 17)); // v_mov_b32 v2, 0.5
words.push(0x7E00_02F0 | (3 << 17)); // v_mov_b32 v3, 0.5
// s_cmp_eq_u32 s1, 0; s_cbranch_scc0 else_arm
words.push(0xBF00_8001); // s_cmp_eq_u32 s1, 0 (const 128)
let br_else = words.len();
words.push(0); // placeholder s_cbranch_scc0
// then arm: load samp_a into s[16:19]
for (i, &w) in samp_a.iter().enumerate() {
words.extend_from_slice(&s_mov_lit(16 + i as u8, w));
}
let br_join = words.len();
words.push(0); // placeholder s_branch
let else_pc = words.len();
// else arm: load alt into s[16:19]
for (i, &w) in alt.iter().enumerate() {
words.extend_from_slice(&s_mov_lit(16 + i as u8, w));
}
let join_pc = words.len();
words[br_else] = 0xBF84_0000 | ((else_pc - br_else - 1) as u32 & 0xFFFF);
words[br_join] = 0xBF82_0000 | ((join_pc - br_join - 1) as u32 & 0xFFFF);
words.extend_from_slice(&image_sample_lz);
words.extend_from_slice(&buf_store);
words.push(0xBF81_0000); // s_endpgm
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 1,
slot: 1,
},
],
used: vec![
UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 8,
user_data: 0,
slot: 0,
},
UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 16,
lower_bound: 0,
stride: 0,
dwords: 4,
user_data: 0,
slot: 0,
},
],
io: StageIo::Cs(ComputeIo {
rsrc2: 2 << 1,
threads: [1, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let p = ir::build(&native.code, false, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track");
let io = io::raise(&p, &native).expect("io::raise");
let lowered = lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})
.unwrap_or_else(|e| panic!("{case_name}: lower failed: {e}"));
let static_samplers = lowered
.samplers
.iter()
.map(|&w| super::StaticSampler::from_words(w))
.collect();
let shader = HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers,
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
};
if let Ok(mut v) =
validator::Validator::load(validator::Validator::default_path().as_deref())
{
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
let _one = super::valu_tests::ONE_AT_A_TIME
.lock()
.unwrap_or_else(|e| e.into_inner());
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
continue;
};
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{case_name}/{label}: compute_pipeline failed: {e}"));
for branch in [0u32, 1u32] {
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Table, 0) => 0,
(RootType::Constants, 1) => branch,
other => panic!("unexpected user data {other:?}"),
};
}
let texels = [[1.0f32, 0.0, 0.0, 1.0]];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Texture(1, 1, &texels),
View::Texture(1, 1, &texels),
View::RawUav(1),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{case_name}/{label}: dispatch failed: {e}"));
let got = f32::from_bits(out[0][0]);
assert_eq!(got, 1.0, "{case_name}/{label} branch={branch}");
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,532 @@
//! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a
//! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`])
//! so that the two host waves can exchange their halves inside it. Lowered, validated by
//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32.
use std::collections::HashSet;
use super::host::{Dispatch, Host, Root, View};
use super::{HostShader, lower, validator};
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
use crate::{ShaderError, io, ir, resource, structure};
const S_ENDPGM: u32 = 0xBF81_0000;
/// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads
/// below s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store
/// the result to dword 0 of the raw UAV.
/// `skip`: the branch past the body when no thread is below s0: `s_cbranch_execz`, or
/// `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left").
fn program(skip: u32) -> NativeProgram {
let mut words = vec![
0x7E0A_0281, // v_mov_b32 v5, 1
0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0
0x340E_0B06, // v_lshlrev_b32 v7, v6, v5
0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
skip | 23, // the branch to the restore of EXEC
];
words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7);
words.extend_from_slice(&[
0x7E00_0207, // v_mov_b32 v0, s7
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
]);
native(&words)
}
/// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4
/// root constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`.
fn native(body: &[u32]) -> NativeProgram {
native_of(body, true, 64)
}
/// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads.
fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram {
let mut words = vec![
0xBE85_0380, // s_mov_b32 s5, 0
0x3D << 26 | 0x02 << 18 | 8 << 6 | 2,
125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0
];
words.extend_from_slice(body);
words.push(S_ENDPGM);
NativeProgram {
stage: HwStage::Cs,
wave64,
vgprs: 16,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 4,
user_data: 4,
slot: 1,
}],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
threads: [threads, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
}
}
/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide.
fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>) -> Result<HostShader, ShaderError> {
lowered_on(native, p, wide, 32)
}
/// [`lowered`] for a host whose waves have at most `host_wave` lanes.
fn lowered_on(
native: &NativeProgram,
p: &ir::Program,
wide: &HashSet<usize>,
host_wave: u32,
) -> Result<HostShader, ShaderError> {
let st = structure::structure_wide(p, wide).expect("structure");
let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
let io = io::raise(p, native).expect("io::raise");
let was = lower::TEST_HOST_WAVE.replace(Some(host_wave));
let lowered = lower::lower(&lower::Parts {
native,
p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
});
lower::TEST_HOST_WAVE.set(was);
let lowered = lowered?;
Ok(HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
})
}
#[test]
fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() {
// thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd
// mantissas, so that additions round); all of them store the wave's sum
let mut words = vec![
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
0x4A0E_0EFF,
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
];
// (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28)
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
words.extend_from_slice(&[
0x7E00_0207, // v_mov_b32 v0, s7
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
]);
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6);
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
// the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits
// (to nearest, ties to even); values here are normal numbers
let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13);
let narrow = |f: f32| {
let b = f.to_bits();
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
let rest = b & 0x1FFF;
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
};
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
let terms: Vec<u16> = (0..64u16).map(|t| 0x3C00 + 37 * t).collect();
let mut tree = terms.clone();
while tree.len() > 1 {
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
}
let in_a_row = terms.iter().copied().reduce(add).unwrap();
assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order");
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return;
};
let (root, pso) = match host.compute_pipeline(&shader) {
Ok(x) => x,
Err(e) => {
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
return;
}
};
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
// (the high half is lane 0's term's: zero)
assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]);
eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]);
}
/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a
/// thread past the end of the data): on the console they add +0, and after each step of the
/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the
/// lanes that are here read each partner run's sum from a lane of it that is here.
#[test]
fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() {
let mut words = vec![
0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay
0, // s_cbranch_execz to the end (filled in below)
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
0x4A0E_0EFF,
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
];
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
words.extend_from_slice(&[
0x7E00_0207, // v_mov_b32 v0, s7
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
]);
// past every word after it, to the program's end
words[1] = 0xBF88_0000 | (words.len() as u32 - 2);
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
let wide = |h: u16| {
if h == 0 {
0.0
} else {
f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13)
}
};
let narrow = |f: f32| {
if f == 0.0 {
return 0;
}
let b = f.to_bits();
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
let rest = b & 0x1FFF;
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
};
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = false;
for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] {
let terms: Vec<u16> = (0..64u32)
.map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 })
.collect();
let mut tree = terms.clone();
while tree.len() > 1 {
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
}
let Some(got) = on_the_card(&shader, [stay, 0]) else {
return;
};
ran = true;
// (the high half is lane 0's term's: zero)
assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]);
}
if ran {
eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case");
}
}
/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2
/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The
/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the
/// translation gives the console's whatever the host does.
#[test]
fn a_16_bit_sum_rounds_to_nearest_when_asked_to() {
let words = [
0x7E0E_02FF,
0x0000_3C03, // v_mov_b32 v7, 0x3c03
0x7E0C_02FF,
0x0000_4000, // v_mov_b32 v6, 0x4000
0x6400_0D07, // v_add_f16 v0, v7, v6
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
];
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16"));
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
for nearest in [false, true] {
let was = lower::TEST_F16_NEAREST.replace(Some(nearest));
let shader = lowered(&native, &p, &HashSet::new());
lower::TEST_F16_NEAREST.set(was);
let shader = shader.expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return;
};
let Ok((root, pso)) = host.compute_pipeline(&shader) else {
eprintln!("the hardware device does not take this program; not run");
return;
};
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
let got = out[0][0] & 0xFFFF;
eprintln!("v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest {nearest}: {got:#x}");
if nearest {
assert_eq!(got, 0x4202);
} else {
assert!(got == 0x4201 || got == 0x4202, "{got:#x}");
}
}
}
#[test]
fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() {
for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] {
a_wave_or_inside(skip, name);
}
}
fn a_wave_or_inside(skip: u32, name: &str) {
let native = program(skip);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let branch = (0..p.blocks.len())
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == name))
.expect("the branch");
// per lane, the two host waves cannot meet inside the branch
lower::take_needs();
let per_lane = lowered(&native, &p, &HashSet::new());
assert!(
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a wave reduction where not every lane runs"),
"{:?}",
per_lane.err()
);
// ... and the lowering names the block, around which that branch is the one to widen
let needs = lower::take_needs();
let st = structure::structure(&p).expect("structure");
assert_eq!(lower::branches_around(&st, &needs), Some(vec![branch]));
// (taken, past the body, when every lane's bit is clear)
assert_eq!(st.wave_any[branch], Some(false));
// wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there)
let wide = HashSet::from([branch]);
let st = structure::structure_wide(&p, &wide).expect("structure");
let inside = match p.blocks[branch].exit {
ir::Exit::Branch { not_taken, .. } => not_taken,
_ => unreachable!(),
};
assert!(st.guards[inside].iter().any(Option::is_some));
let shader = lowered(&native, &p, &wide).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
// On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of
// both halves, whichever half's lanes take the branch.
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return;
};
let (root, pso) = match host.compute_pipeline(&shader) {
Ok(x) => x,
Err(e) => {
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
return;
}
};
// (threads below s0 take the branch; thread t gives bit t >> 1)
for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] {
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) {
ud[u.index as usize] = below;
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
assert_eq!(out[0][0], expected, "{name}: {below} threads in the branch");
}
eprintln!("ran on the hardware device ({name}): the OR of both halves in every case");
}
/// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0
/// of the UAV; None (and a line) without a device that takes it.
fn on_the_card(shader: &HostShader, constants: [u32; 2]) -> Option<u32> {
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return None;
};
let Ok((root, pso)) = host.compute_pipeline(shader) else {
eprintln!("the hardware device does not take this program; not run");
return None;
};
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) {
ud[u.index as usize] = constants[d as usize];
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
Some(out[0][0])
}
/// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0)
/// and a number on the other, and is read as a number after the join, as the trace programs
/// keep their lanes' masks and their node numbers on one stack
/// (`deferred_tiled:CS_LaserLightShadowRaytracing`, s46 at 0x104, 0x75c and 0x188). The
/// mask arrives as the ballot of its lanes.
#[test]
fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() {
let words = [
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
0xBE94_036A, // s_mov_b32 s20, vcc_lo
0xBF06_8001, // s_cmp_eq_u32 s1, 0
0xBF85_0001, // s_cbranch_scc1 over the next
0xBE94_0385, // s_mov_b32 s20, 5
0x7E00_0214, // v_mov_b32 v0, s20
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
];
let native = native_of(&words, false, 32);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] {
let Some(got) = on_the_card(&shader, [below, other]) else { return };
assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}");
}
eprintln!("ran on the hardware device: the mask's bits, or the number");
}
/// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after
/// the join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along
/// (`rtdirectionalshadows:CS_RTShadowTrace32HQ_TiledFarOnly`, 0x360-0x39c). On the console
/// the skip is taken by the wave, so with some lane inside every lane sees the inner test.
/// A lane that skipped on its own would see "some lane is left" instead: refused per lane,
/// right with the branch taken wave-wide. Lane 31 stores what it saw.
#[test]
fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() {
let words = [
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
0xBE8D_3C6A, // s_and_saveexec_b32 s13, vcc_lo
0xBF88_0001, // s_cbranch_execz over the next
0xBF06_8701, // s_cmp_eq_u32 s1, 7
0xBEFE_030D, // s_mov_b32 exec_lo, s13
0xBF85_0002, // s_cbranch_scc1 to "seven"
0x7E0A_0281, // v_mov_b32 v5, 1
0xBF82_0001, // s_branch over the next
0x7E0A_0282, // seven: v_mov_b32 v5, 2
0x7DA4_009F, // v_cmpx_eq_u32 exec_lo, 31, v0
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16 | 5 << 8, // buffer_store_dword v5, off, s[8:11], 0
];
let native = native_of(&words, false, 32);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let branch = (0..p.blocks.len())
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz"))
.expect("the skip");
lower::take_needs();
let per_lane = lowered(&native, &p, &HashSet::new());
assert!(
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a lane mask read as data"),
"{:?}",
per_lane.err()
);
let st = structure::structure(&p).expect("structure");
assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch]));
let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower");
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
// (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch
for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] {
let Some(got) = on_the_card(&shader, [below, s1]) else { return };
assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}");
}
eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside");
}
+815
View File
@@ -0,0 +1,815 @@
//! Operand fields of GFX10 instructions, by encoding.
//!
//! Layouts follow AMD's RDNA ISA reference. Register ranges carry their size
//! in dwords, which depends on the opcode (read from its name) and, for lane
//! masks (VCC, EXEC, compare results), on the wave size.
use super::{Encoding, Instruction};
/// A source or destination of an instruction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operand {
/// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107
/// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`,
/// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the
/// IR names scalars parked in VGPR lanes by the codes from 128 up
/// (`crate::ir::PARKED`).
Scalar {
code: u8,
dwords: u8,
},
Vector {
reg: u8,
dwords: u8,
},
/// Inline constant or read-only special source, by operand code
/// (128-192: 0-64, 193-208: -1 to -16, 240-248: floats, 251-254: vccz,
/// execz, scc, lds_direct).
Const(u8),
/// The 32-bit literal that follows the instruction.
Literal(u32),
/// Interpolation attribute and channel (0-3 = x-w); `high` selects the
/// upper f16 half.
Attr {
index: u8,
chan: u8,
high: bool,
},
}
/// Operand code of `null` (no register; reads as 0).
pub const NULL: u8 = 125;
const VCC: u8 = 106;
const EXEC: u8 = 126;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Cache {
pub glc: bool,
pub slc: bool,
pub dlc: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Fields {
/// SOP1, SOP2, SOPC, SOPK; `imm` is SOPK's 16-bit immediate.
Sop {
dst: Option<Operand>,
src: Vec<Operand>,
imm: Option<u16>,
},
/// The 16-bit immediate: branch offset in dwords, wait counts, message...
Sopp {
imm: u16,
},
Smem {
data: Option<Operand>,
base: Operand,
/// Signed byte offset, added to `soffset`.
offset: i32,
soffset: Operand,
cache: Cache,
},
Valu(Valu),
Vintrp {
dst: Operand,
/// The i/j VGPR, or for `v_interp_mov_f32` the parameter (0 `p10`,
/// 1 `p20`, 2 `p0`) as [`Operand::Const`].
src: Operand,
attr: Operand,
},
Ds {
dst: Option<Operand>,
addr: Option<Operand>,
data: Vec<Operand>,
offset0: u8,
offset1: u8,
gds: bool,
},
/// MUBUF, and MTBUF with `format` set.
Buffer {
/// Loaded, stored, or the atomic operand (and result with `glc`).
data: Option<Operand>,
addr: Operand,
rsrc: Operand,
soffset: Operand,
offset: u16,
offen: bool,
idxen: bool,
format: Option<u8>,
lds: bool,
tfe: bool,
cache: Cache,
},
Image {
data: Operand,
/// One range, or one VGPR per address with the NSA form.
addr: Vec<Operand>,
rsrc: Operand,
sampler: Option<Operand>,
dmask: u8,
dim: u8,
unorm: bool,
r128: bool,
a16: bool,
d16: bool,
tfe: bool,
lwe: bool,
cache: Cache,
},
/// FLAT, GLOBAL and SCRATCH.
Flat {
dst: Option<Operand>,
addr: Option<Operand>,
data: Option<Operand>,
saddr: Option<Operand>,
offset: i16,
lds: bool,
cache: Cache,
},
Exp {
target: u8,
/// Per channel; `None` when disabled.
src: [Option<Operand>; 4],
compr: bool,
done: bool,
vm: bool,
},
}
/// VOP1, VOP2, VOPC, VOP3 and VOP3P, with their SDWA and DPP forms.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Valu {
/// A VGPR range, an SGPR (`v_readlane_b32`...) or a lane mask (compares).
pub dst: Option<Operand>,
/// Carry-out or the second result of VOP3B (`v_add_co_u32`, `v_div_scale_f32`...).
pub carry: Option<Operand>,
/// In operand order, including the implicit VCC of VOP2 `v_cndmask_b32`
/// and carry-in, and the literal of `v_madmk`/`v_madak` forms.
pub src: Vec<Operand>,
/// Bit i applies to `src[i]`. For VOP3P, `neg` is the low half's.
pub neg: u8,
pub abs: u8,
/// VOP3P: negate the high half (`v_fma_mix*`: absolute value).
pub neg_hi: u8,
/// VOP3: bit 3 is the destination. VOP3P with `opsel_hi`: the halves used.
pub opsel: u8,
pub opsel_hi: u8,
pub clamp: bool,
/// Output modifier: 1 ×2, 2 ×4, 3 ÷2.
pub omod: u8,
pub sdwa: Option<Sdwa>,
pub dpp: Option<Dpp>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sdwa {
/// Selects: 0-3 byte, 4-5 word, 6 dword. Compares have no `dst_sel`.
pub dst_sel: u8,
/// 0 pad with zeros, 1 sign-extend, 2 preserve.
pub dst_unused: u8,
pub src_sel: [u8; 2],
/// Bit i sign-extends `src[i]`.
pub sext: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dpp {
/// DPP16: `ctrl` is the 9-bit permutation (quad_perm, row shifts...).
Row {
ctrl: u16,
row_mask: u8,
bank_mask: u8,
bound_ctrl: bool,
fi: bool,
},
/// DPP8: eight 3-bit lane selects.
Lanes { sel: u32, fi: bool },
}
impl Instruction {
/// Decodes the operand fields. `wave64` sizes lane masks.
pub fn fields(&self, wave64: bool) -> Fields {
let name = self.name().unwrap_or("");
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
let (w0, w1) = (w(0), w(1));
let bit = |word: u32, n: u32| word >> n & 1 != 0;
let cache = |glc, slc, dlc| Cache { glc, slc, dlc };
match self.encoding {
Encoding::Sop2 | Encoding::Sop1 | Encoding::Sopc => {
let (dst, src0, src1) = salu_dwords(name);
let sdst = scalar((w0 >> 16 & 0x7F) as u8, dst);
let ssrc = |shift: u32, dwords| source(w0 >> shift & 0xFF, dwords, w1);
let (dst, src) = match self.encoding {
Encoding::Sop2 => (Some(sdst), vec![ssrc(0, src0), ssrc(8, src1)]),
Encoding::Sopc => (None, vec![ssrc(0, src0), ssrc(8, src1)]),
_ => match name {
"s_getpc_b64" => (Some(sdst), vec![]),
"s_setpc_b64" | "s_rfe_b64" => (None, vec![ssrc(0, src0)]),
_ => (Some(sdst), vec![ssrc(0, src0)]),
},
};
Fields::Sop {
dst,
src,
imm: None,
}
}
Encoding::Sopk => {
let sdst = scalar((w0 >> 16 & 0x7F) as u8, 1 + u8::from(name == "s_call_b64"));
let (dst, src) = match name {
"s_setreg_imm32_b32" => (None, vec![Operand::Literal(w1)]),
"s_version" => (None, vec![]),
n if n.starts_with("s_cmpk_")
|| n.starts_with("s_waitcnt_")
|| n == "s_setreg_b32" =>
{
(None, vec![sdst])
}
_ => (Some(sdst), vec![]),
};
Fields::Sop {
dst,
src,
imm: Some(w0 as u16),
}
}
Encoding::Sopp => Fields::Sopp { imm: w0 as u16 },
Encoding::Smem => {
let data = match name {
"s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None,
n if n.starts_with("s_dcache_discard") => None,
"s_memtime" | "s_memrealtime" => Some(2),
_ => Some(data_dwords(name)),
};
let base = 2 + 2 * u8::from(name.starts_with("s_buffer_"));
Fields::Smem {
data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)),
base: scalar(((w0 & 0x3F) << 1) as u8, base),
offset: (w1 << 11) as i32 >> 11,
soffset: scalar((w1 >> 25) as u8, 1),
cache: cache(bit(w0, 16), false, bit(w0, 14)),
}
}
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => {
Fields::Valu(self.valu(name, if wave64 { 2 } else { 1 }))
}
Encoding::Vintrp => {
let vsrc = (w0 & 0xFF) as u8;
Fields::Vintrp {
dst: vector(w0 >> 18, 1),
src: if name == "v_interp_mov_f32" {
Operand::Const(vsrc)
} else {
vector(vsrc.into(), 1)
},
attr: Operand::Attr {
index: (w0 >> 10 & 0x3F) as u8,
chan: (w0 >> 8 & 3) as u8,
high: false,
},
}
}
Encoding::Ds => {
let ty = data_dwords(name);
let pair = ds_pair(name);
let returns = name.contains("read")
|| name.contains("_rtn")
|| matches!(
name,
"ds_swizzle_b32"
| "ds_permute_b32"
| "ds_bpermute_b32"
| "ds_append"
| "ds_consume"
| "ds_ordered_count"
);
let no_addr = name.starts_with("ds_gws")
|| name.contains("addtid")
|| matches!(name, "ds_nop" | "ds_append" | "ds_consume");
let data = if name.contains("read")
|| name.contains("src2")
|| matches!(
name,
"ds_swizzle_b32"
| "ds_nop"
| "ds_append"
| "ds_consume"
| "ds_ordered_count"
| "ds_gws_sema_v"
| "ds_gws_sema_p"
| "ds_gws_sema_release_all"
) {
0
} else if pair || name.contains("cmpst") || name.contains("mskor") {
2
} else {
1
};
Fields::Ds {
dst: returns.then(|| vector(w1 >> 24, ty * (1 + u8::from(pair)))),
addr: (!no_addr).then(|| vector(w1 & 0xFF, 1)),
data: (0..data)
.map(|i| vector(w1 >> (8 + 8 * i) & 0xFF, ty))
.collect(),
offset0: w0 as u8,
offset1: (w0 >> 8) as u8,
gds: bit(w0, 17),
}
}
Encoding::Mubuf | Encoding::Mtbuf => {
let (offen, idxen, tfe) = (bit(w0, 12), bit(w0, 13), bit(w1, 23));
let mtbuf = self.encoding == Encoding::Mtbuf;
Fields::Buffer {
data: (!name.ends_with("_inv"))
.then(|| vector(w1 >> 8 & 0xFF, data_dwords(name) + u8::from(tfe))),
addr: vector(w1 & 0xFF, 1 + u8::from(offen && idxen)),
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, 4),
soffset: source(w1 >> 24, 1, 0),
offset: (w0 & 0xFFF) as u16,
offen,
idxen,
format: mtbuf.then_some((w0 >> 19 & 0x7F) as u8),
lds: !mtbuf && bit(w0, 16),
tfe,
cache: cache(bit(w0, 14), bit(w1, 22), bit(w0, 15)),
}
}
Encoding::Mimg => {
let (dim, dmask, a16, d16) = (
(w0 >> 3 & 7) as u8,
(w0 >> 8 & 0xF) as u8,
bit(w1, 30),
bit(w1, 31),
);
let (r128, tfe, lwe) = (bit(w0, 15), bit(w0, 16), bit(w0, 17));
let mut data = if name.starts_with("image_gather4") {
4
} else {
dmask.count_ones().max(1) as u8
};
if d16 {
data = data.div_ceil(2);
}
let count = image_addr_dwords(name, dim, a16);
let addr = if w0 >> 1 & 3 == 0 {
vec![vector(w1 & 0xFF, count)]
} else {
// NSA: one VGPR per address, the first in dword 1, the rest
// in the extra dwords.
(0..usize::from(count))
.map(|i| match i {
0 => vector(w1 & 0xFF, 1),
i => vector(w(2 + (i - 1) / 4) >> (8 * ((i - 1) % 4)) & 0xFF, 1),
})
.collect()
};
let sampled = ["image_sample", "image_gather4", "image_get_lod"]
.iter()
.any(|p| name.starts_with(p));
Fields::Image {
data: vector(w1 >> 8 & 0xFF, data + u8::from(tfe || lwe)),
addr,
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, if r128 { 4 } else { 8 }),
sampler: sampled.then(|| scalar(((w1 >> 21 & 0x1F) << 2) as u8, 4)),
dmask,
dim,
unorm: bit(w0, 12),
r128,
a16,
d16,
tfe,
lwe,
cache: cache(bit(w0, 13), bit(w0, 25), bit(w0, 7)),
}
}
Encoding::Flat | Encoding::Global | Encoding::Scratch => {
let saddr = (w1 >> 16 & 0x7F) as u8;
let glc = bit(w0, 16);
let n = data_dwords(name);
let (load, atomic) = (name.contains("_load_"), name.contains("_atomic_"));
let addr = match self.encoding {
Encoding::Flat => Some(vector(w1 & 0xFF, 2)),
Encoding::Global => Some(vector(w1 & 0xFF, 1 + u8::from(saddr == NULL))),
// With an SGPR base, scratch takes no VGPR.
_ => (saddr == NULL).then(|| vector(w1 & 0xFF, 1)),
};
let ret = if atomic && name.contains("cmpswap") {
n / 2
} else {
n
};
Fields::Flat {
dst: (load || atomic && glc).then(|| vector(w1 >> 24, ret)),
addr,
data: (!load).then(|| vector(w1 >> 8 & 0xFF, n)),
saddr: (self.encoding != Encoding::Flat)
.then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))),
offset: match self.encoding {
Encoding::Flat => (w0 & 0x7FF) as i16,
_ => ((w0 << 4) as i16) >> 4,
},
lds: bit(w0, 13),
cache: cache(glc, bit(w0, 17), bit(w0, 12)),
}
}
Encoding::Exp => {
let compr = bit(w0, 10);
Fields::Exp {
target: (w0 >> 4 & 0x3F) as u8,
src: std::array::from_fn(|i| {
let slot = if compr { i / 2 } else { i };
bit(w0, i as u32).then(|| vector(w1 >> (8 * slot) & 0xFF, 1))
}),
compr,
done: bit(w0, 11),
vm: bit(w0, 12),
}
}
}
}
fn valu(&self, name: &str, lanes: u8) -> Valu {
// No operands; the console compiler stores a shader hash in their fields.
if matches!(name, "v_nop" | "v_pipeflush" | "v_clrexcp") {
return Valu::default();
}
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
let w0 = w(0);
let (dst_n, src_n) = valu_dwords(name);
let compare = match self.encoding {
Encoding::Vopc => true,
Encoding::Vop3 => self.opcode < 0x100,
_ => false,
};
let vop3b = VOP3B.contains(&name);
let carry_in = name.ends_with("_co_ci_u32") || name == "v_cndmask_b32";
let mut v = Valu::default();
match self.encoding {
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc => {
let ext = w(1);
let mut src0 = w0 & 0x1FF;
let vsrc1 = 256 + (w0 >> 9 & 0xFF);
let mut src1 = vsrc1;
match src0 {
0xF9 => {
let sdwa = Sdwa {
dst_sel: (ext >> 8 & 7) as u8,
dst_unused: (ext >> 11 & 3) as u8,
src_sel: [(ext >> 16 & 7) as u8, (ext >> 24 & 7) as u8],
sext: (ext >> 19 & 1 | ext >> 26 & 2) as u8,
};
// The s0/s1 bits select an SGPR or constant instead of a VGPR.
src0 = (ext & 0xFF) | if ext >> 23 & 1 == 0 { 256 } else { 0 };
if ext >> 31 == 1 {
src1 = vsrc1 - 256;
}
v.neg = (ext >> 20 & 1 | ext >> 27 & 2) as u8;
v.abs = (ext >> 21 & 1 | ext >> 28 & 2) as u8;
if compare {
if ext >> 15 & 1 == 1 {
v.dst = Some(scalar((ext >> 8 & 0x7F) as u8, lanes));
}
v.sdwa = Some(Sdwa {
dst_sel: 6,
dst_unused: 0,
..sdwa
});
} else {
v.clamp = ext >> 13 & 1 == 1;
v.omod = (ext >> 14 & 3) as u8;
v.sdwa = Some(sdwa);
}
}
0xFA => {
src0 = 256 + (ext & 0xFF);
v.neg = (ext >> 20 & 1 | ext >> 21 & 2) as u8;
v.abs = (ext >> 21 & 1 | ext >> 22 & 2) as u8;
v.dpp = Some(Dpp::Row {
ctrl: (ext >> 8 & 0x1FF) as u16,
row_mask: (ext >> 28) as u8,
bank_mask: (ext >> 24 & 0xF) as u8,
bound_ctrl: ext >> 19 & 1 == 1,
fi: ext >> 18 & 1 == 1,
});
}
0xE9 | 0xEA => {
v.dpp = Some(Dpp::Lanes {
sel: ext >> 8,
fi: src0 == 0xEA,
});
src0 = 256 + (ext & 0xFF);
}
_ => {}
}
let op0 = source(src0, src_n[0], ext);
let op1 = source(src1, src_n[1], ext);
match self.encoding {
Encoding::Vopc => {
let mask = if name.starts_with("v_cmpx") {
EXEC
} else {
VCC
};
v.dst = v.dst.or(Some(scalar(mask, lanes)));
v.src = vec![op0, op1];
}
Encoding::Vop1 => {
v.dst = Some(valu_dst(name, w0 >> 17 & 0xFF, dst_n));
v.src = vec![op0];
}
_ => {
v.dst = Some(vector(w0 >> 17 & 0xFF, dst_n));
v.src = match name {
n if n.ends_with("mk_f32") || n.ends_with("mk_f16") => {
vec![op0, Operand::Literal(ext), op1]
}
n if n.ends_with("ak_f32") || n.ends_with("ak_f16") => {
vec![op0, op1, Operand::Literal(ext)]
}
_ => vec![op0, op1],
};
if carry_in {
v.src.push(scalar(VCC, lanes));
}
if name.ends_with("_co_ci_u32") {
v.carry = Some(scalar(VCC, lanes));
}
}
}
}
Encoding::Vop3 | Encoding::Vop3p => {
let w1 = w(1);
let field = |i: u32| w1 >> (9 * i) & 0x1FF;
let count = match self.opcode {
_ if self.encoding == Encoding::Vop3p => {
if name.starts_with("v_pk_")
&& !name.contains("_fma_")
&& !name.contains("_mad_")
{
2
} else {
3
}
}
0x000..0x100 => 2,
0x100..0x140 => 2 + usize::from(carry_in),
0x180..0x200 => 1,
_ if VOP3_TWO_SOURCES.contains(&name) => 2,
_ => 3,
};
v.src = (0..count)
.map(|i| {
let code = field(i as u32);
if i == 0 && name.starts_with("v_interp_") {
Operand::Attr {
index: (code & 0x3F) as u8,
chan: (code >> 6 & 3) as u8,
high: code >> 8 & 1 == 1,
}
} else if i == 2 && carry_in {
source(code, lanes, w(2))
} else {
source(code, src_n[i], w(2))
}
})
.collect();
v.clamp = w0 >> 15 & 1 == 1;
v.neg = (w1 >> 29) as u8;
if self.encoding == Encoding::Vop3p {
v.neg_hi = (w0 >> 8 & 7) as u8;
v.opsel = (w0 >> 11 & 7) as u8;
v.opsel_hi = (w1 >> 27 & 3 | w0 >> 12 & 4) as u8;
} else {
v.omod = (w1 >> 27 & 3) as u8;
if vop3b {
v.carry = Some(scalar((w0 >> 8 & 0x7F) as u8, lanes));
} else {
v.abs = (w0 >> 8 & 7) as u8;
v.opsel = (w0 >> 11 & 0xF) as u8;
}
}
let vdst = w0 & 0xFF;
v.dst = Some(if compare {
scalar(vdst as u8, lanes)
} else {
valu_dst(name, vdst, dst_n)
});
}
_ => unreachable!("not a VALU encoding"),
}
v
}
}
/// VOP3-only opcodes that take two sources (the rest take three).
const VOP3_TWO_SOURCES: &[&str] = &[
"v_add_f64",
"v_mul_f64",
"v_min_f64",
"v_max_f64",
"v_ldexp_f64",
"v_mul_lo_u32",
"v_mul_hi_u32",
"v_mul_lo_i32",
"v_mul_hi_i32",
"v_trig_preop_f64",
"v_lshlrev_b64",
"v_lshrrev_b64",
"v_ashrrev_i64",
"v_add_nc_u16",
"v_sub_nc_u16",
"v_mul_lo_u16",
"v_lshrrev_b16",
"v_ashrrev_i16",
"v_max_u16",
"v_max_i16",
"v_min_u16",
"v_min_i16",
"v_add_nc_i16",
"v_sub_nc_i16",
"v_add_co_u32",
"v_sub_co_u32",
"v_subrev_co_u32",
"v_pack_b32_f16",
"v_cvt_pknorm_i16_f16",
"v_cvt_pknorm_u16_f16",
"v_lshlrev_b16",
"v_interp_p1ll_f16",
"v_readlane_b32",
"v_writelane_b32",
"v_ldexp_f32",
"v_bfm_b32",
"v_bcnt_u32_b32",
"v_mbcnt_lo_u32_b32",
"v_mbcnt_hi_u32_b32",
"v_cvt_pknorm_i16_f32",
"v_cvt_pknorm_u16_f32",
"v_cvt_pk_u16_u32",
"v_cvt_pk_i16_i32",
"v_sub_nc_i32",
"v_add_nc_i32",
];
/// VOP3 opcodes whose bits 14:8 hold a scalar destination instead of `abs`/`opsel`.
const VOP3B: &[&str] = &[
"v_add_co_u32",
"v_sub_co_u32",
"v_subrev_co_u32",
"v_add_co_ci_u32",
"v_sub_co_ci_u32",
"v_subrev_co_ci_u32",
"v_div_scale_f32",
"v_div_scale_f64",
"v_mad_u64_u32",
"v_mad_i64_i32",
];
fn scalar(code: u8, dwords: u8) -> Operand {
Operand::Scalar { code, dwords }
}
fn vector(reg: u32, dwords: u8) -> Operand {
Operand::Vector {
reg: reg as u8,
dwords,
}
}
/// A 9-bit source field (8-bit scalar fields are the same codes below 256).
fn source(code: u32, dwords: u8, literal: u32) -> Operand {
match code {
0..=127 => scalar(code as u8, dwords),
255 => Operand::Literal(literal),
256.. => vector(code - 256, dwords),
_ => Operand::Const(code as u8),
}
}
/// VALU destinations that are SGPRs.
fn valu_dst(name: &str, field: u32, dwords: u8) -> Operand {
match name {
"v_readlane_b32" | "v_readfirstlane_b32" => scalar(field as u8, 1),
_ => vector(field, dwords),
}
}
/// LDS opcodes on two addresses (`ds_read2_b32`...), with `offset0`/`offset1`.
pub(super) fn ds_pair(name: &str) -> bool {
name.split('_').any(|t| {
["read2", "write2", "wrxchg2"]
.iter()
.any(|p| t.starts_with(p))
})
}
/// Dwords of a type suffix such as `b64` or `f32`.
fn type_dwords(token: &str) -> u8 {
match token {
"b64" | "u64" | "i64" | "f64" => 2,
_ => 1,
}
}
/// (sdst, ssrc0, ssrc1) dwords of a scalar ALU opcode.
fn salu_dwords(name: &str) -> (u8, u8, u8) {
match name {
"s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" | "s_bfe_u64" | "s_bfe_i64"
| "s_bitcmp0_b64" | "s_bitcmp1_b64" => (2, 2, 1),
"s_bfm_b64" | "s_bitset0_b64" | "s_bitset1_b64" | "s_bitreplicate_b64_b32" => (2, 1, 1),
"s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64"
| "s_flbit_i32_b64" | "s_flbit_i32_i64" => (1, 2, 2),
_ => {
let n = type_dwords(name.rsplit('_').next().unwrap_or(""));
(n, n, n)
}
}
}
/// (vdst, [src0, src1, src2]) dwords of a VALU opcode.
fn valu_dwords(name: &str) -> (u8, [u8; 3]) {
let parts: Vec<&str> = name.split('_').collect();
match name {
"v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => (2, [1, 2, 2]),
"v_ldexp_f64" | "v_trig_preop_f64" | "v_cmp_class_f64" | "v_cmpx_class_f64" => {
(2, [2, 1, 2])
}
"v_mad_u64_u32" | "v_mad_i64_i32" => (2, [1, 1, 2]),
"v_qsad_pk_u16_u8" | "v_mqsad_pk_u16_u8" => (2, [2, 1, 2]),
"v_mqsad_u32_u8" => (4, [2, 1, 4]),
"v_frexp_exp_i32_f64" => (1, [2; 3]),
_ if parts.len() == 4 && parts[1] == "cvt" => {
(type_dwords(parts[2]), [type_dwords(parts[3]); 3])
}
_ => {
let n = type_dwords(parts.last().copied().unwrap_or(""));
(n, [n; 3])
}
}
}
/// Dwords of loaded, stored or atomic data, from the opcode name.
fn data_dwords(name: &str) -> u8 {
let mut n: u8 = 1;
for token in name.split('_') {
n = match token {
"dwordx2" | "x2" | "xy" | "b64" | "u64" | "i64" | "f64" => 2,
"dwordx3" | "xyz" | "b96" => 3,
"dwordx4" | "xyzw" | "b128" => 4,
"dwordx8" => 8,
"dwordx16" => 16,
_ => n,
};
}
if name.contains("cmpswap") {
n *= 2;
}
if name.contains("format_d16") {
n = n.div_ceil(2);
}
n
}
/// Address dwords of an image opcode: offset, bias, compare, derivatives,
/// coordinates, then LOD/clamp/mip, packed in pairs with `a16`.
fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 {
// (coordinates, derivatives per direction) for 1D 2D 3D CUBE 1D_ARRAY
// 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY.
const DIMS: [(u8, u8); 8] = [
(1, 1),
(2, 2),
(3, 3),
(3, 2),
(2, 1),
(3, 2),
(3, 2),
(4, 2),
];
let (coords, grads) = DIMS[usize::from(dim & 7)];
match name {
"image_bvh_intersect_ray" => return if a16 { 8 } else { 11 },
"image_bvh64_intersect_ray" => return if a16 { 9 } else { 12 },
"image_get_resinfo" => return 1,
_ => {}
}
let (mut whole, mut derivs, mut packed): (u8, u8, u8) = (0, 0, coords);
if let Some(rest) = name
.strip_prefix("image_sample")
.or_else(|| name.strip_prefix("image_gather4"))
{
for token in rest.split('_') {
match token {
"o" | "b" | "c" => whole += 1,
"d" | "cd" => derivs = grads,
"l" | "cl" => packed += 1,
_ => {}
}
}
} else if name.contains("_mip") {
packed += 1;
}
if a16 {
whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2)
} else {
whole + 2 * derivs + packed
}
}
+496
View File
@@ -0,0 +1,496 @@
//! GFX10 machine code: instruction boundaries, encodings and opcodes.
//!
//! Instructions are found by following control flow from offset 0, not by a
//! linear sweep: compilers place data (constant tables) in the code region
//! after the end of the program. [`Instruction::fields`] decodes the operand
//! fields and [`Instruction::text`] prints them in AMD's SP3 syntax.
//!
//! Encodings by the top bits of the first dword:
//!
//! ```text
//! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC
//! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP
//! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH
//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP
//! ```
mod fields;
mod opcodes;
mod sp3;
pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu};
use std::collections::BTreeMap;
use crate::ShaderError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Encoding {
Sop2,
Sopk,
Sop1,
Sopc,
Sopp,
Smem,
Vop2,
Vop1,
Vopc,
Vop3,
Vop3p,
Vintrp,
Ds,
Mubuf,
Mtbuf,
Mimg,
Exp,
Flat,
Global,
Scratch,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instruction {
/// Byte offset in the program.
pub offset: usize,
pub encoding: Encoding,
pub opcode: u16,
/// Every dword of the instruction, including literals and extra dwords.
pub words: Vec<u32>,
}
impl Instruction {
/// AMD's name for the opcode, if it is in our table.
pub fn name(&self) -> Option<&'static str> {
name(self.encoding, self.opcode)
}
}
/// Decodes every instruction reachable from offset 0, sorted by offset.
pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
if !code.len().is_multiple_of(4) {
return Err(isa(code.len(), "code size is not a multiple of 4"));
}
let mut found = BTreeMap::new();
let mut pending = vec![0usize];
while let Some(mut offset) = pending.pop() {
while !found.contains_key(&offset) {
let inst = instruction(code, offset)?;
let next = offset + 4 * inst.words.len();
let flow = control(&inst, code.len(), |at| {
found.range(..at).next_back().map(|(_, i)| i)
})?;
found.insert(offset, inst);
match flow {
Flow::Next => offset = next,
Flow::Stop => break,
Flow::Jump(target) => offset = target,
Flow::Branch(target) => {
pending.push(target);
offset = next;
}
}
}
}
let list: Vec<Instruction> = found.into_values().collect();
if let Some(w) = list
.windows(2)
.find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset)
{
return Err(isa(w[1].offset, "a branch lands inside an instruction"));
}
Ok(list)
}
/// Where execution goes after an instruction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Flow {
Next,
/// End of the program, or an indirect jump that is not a far jump.
Stop,
Jump(usize),
/// Conditional: to the target or the next instruction.
Branch(usize),
}
/// Control flow after `inst`, resolving far jumps. `before(at)` returns the
/// decoded instruction with the highest offset below `at`, if any.
pub(crate) fn control<'a>(
inst: &Instruction,
len: usize,
before: impl Fn(usize) -> Option<&'a Instruction>,
) -> Result<Flow, ShaderError> {
Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? {
Flow::Stop if inst.name() == Some("s_setpc_b64") => {
far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump)
}
flow => flow,
})
}
fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> {
let target = || {
let delta = 4 * i64::from(inst.words[0] as u16 as i16);
usize::try_from(next as i64 + delta)
.ok()
.filter(|&t| t < len)
.ok_or(isa(inst.offset, "branch target outside the code"))
};
Ok(match (inst.encoding, inst.name().unwrap_or("")) {
(
Encoding::Sopp,
"s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end",
) => Flow::Stop,
(Encoding::Sopp, "s_branch") => Flow::Jump(target()?),
(Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?),
(Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?),
// Indirect jump; `decode` resolves the compiler's far-jump form.
(Encoding::Sop1, "s_setpc_b64") => Flow::Stop,
_ => Flow::Next,
})
}
/// Resolves the far jump compilers emit beyond the reach of a branch offset:
/// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry
/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line
/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next
/// merged stage through registers) gives `None`.
fn far_jump<'a>(
before: impl Fn(usize) -> Option<&'a Instruction>,
setpc: &Instruction,
len: usize,
) -> Result<Option<usize>, ShaderError> {
let n = setpc.words[0] & 0xFF;
let mut delta = None;
let mut at = setpc.offset;
for _ in 0..4 {
let Some(prev) = before(at) else {
break;
};
if prev.offset + 4 * prev.words.len() != at {
break;
}
let w = prev.words[0];
let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF);
match (prev.encoding, prev.name()) {
(Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32")))
if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() =>
{
// The low dword of a signed 64-bit offset: a backward jump
// adds a negative one (its high dword is -1).
let literal = i64::from(prev.words[1] as i32);
delta = Some(if op == "s_add_u32" { literal } else { -literal });
}
(Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => {
let Some(delta) = delta else { break };
// s_getpc_b64 yields the address of the instruction after it.
return usize::try_from(prev.offset as i64 + 4 + delta)
.ok()
.filter(|&t| t < len)
.map(Some)
.ok_or(isa(setpc.offset, "far jump target outside the code"));
}
_ => {}
}
at = prev.offset;
}
Ok(None)
}
fn instruction(code: &[u8], offset: usize) -> Result<Instruction, ShaderError> {
let word = |i: usize| {
code.get(offset + 4 * i..offset + 4 * i + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
.ok_or(isa(offset, "instruction runs past the end of the code"))
};
let w = word(0)?;
let (encoding, opcode, len) = if w >> 31 == 0 {
let src0 = w & 0x1FF;
// Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive.
let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA));
match w >> 25 {
0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra),
0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra),
op => {
let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| {
matches!(
n,
"v_madmk_f32"
| "v_madak_f32"
| "v_fmamk_f32"
| "v_fmaak_f32"
| "v_madmk_f16"
| "v_madak_f16"
| "v_fmamk_f16"
| "v_fmaak_f16"
)
});
(Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak)))
}
}
} else if w >> 30 == 0b10 {
let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF));
match w >> 23 {
0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])),
0x17E => (
Encoding::Sopc,
(w >> 16) & 0x7F,
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
),
0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1),
_ if w >> 28 == 0b1011 => {
let op = (w >> 23) & 0x1F;
let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32");
(Encoding::Sopk, op, 1 + usize::from(imm32))
}
_ => (
Encoding::Sop2,
(w >> 23) & 0x7F,
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
),
}
} else {
let vop3 =
|w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF));
match w >> 26 {
0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1),
0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)),
0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)),
0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2),
0x37 => {
let encoding = match (w >> 14) & 3 {
0 => Encoding::Flat,
1 => Encoding::Scratch,
2 => Encoding::Global,
_ => return Err(isa(offset, "reserved FLAT segment")),
};
(encoding, (w >> 18) & 0x7F, 2)
}
0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2),
0x3A => (
Encoding::Mtbuf,
(w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3,
2,
),
// Bits 2:1 count extra dwords of non-sequential address registers.
0x3C => (
Encoding::Mimg,
(w >> 18) & 0x7F | (w & 1) << 7,
2 + (w as usize >> 1 & 3),
),
0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2),
0x3E => (Encoding::Exp, 0, 2),
_ => return Err(isa(offset, "unknown encoding")),
}
};
Ok(Instruction {
offset,
encoding,
opcode: opcode as u16,
words: (0..len).map(word).collect::<Result<_, _>>()?,
})
}
fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> {
use opcodes as t;
let (table, op) = match encoding {
Encoding::Sop2 => (t::SOP2, opcode),
Encoding::Sopk => (t::SOPK, opcode),
Encoding::Sop1 => (t::SOP1, opcode),
Encoding::Sopc => (t::SOPC, opcode),
Encoding::Sopp => (t::SOPP, opcode),
Encoding::Smem => (t::SMEM, opcode),
Encoding::Vop2 => (t::VOP2, opcode),
Encoding::Vop1 => (t::VOP1, opcode),
Encoding::Vopc => (t::VOPC, opcode),
// VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases.
Encoding::Vop3 => match opcode {
0x000..0x100 => (t::VOPC, opcode),
0x100..0x140 => (t::VOP2, opcode - 0x100),
0x180..0x200 => (t::VOP1, opcode - 0x180),
_ => (t::VOP3, opcode),
},
Encoding::Vop3p => (t::VOP3P, opcode),
Encoding::Vintrp => (t::VINTRP, opcode),
Encoding::Ds => (t::DS, opcode),
Encoding::Mubuf => (t::MUBUF, opcode),
Encoding::Mtbuf => (t::MTBUF, opcode),
Encoding::Mimg => (t::MIMG, opcode),
Encoding::Exp => return Some("exp"),
Encoding::Flat => (t::FLAT, opcode),
Encoding::Global => (t::GLOBAL, opcode),
Encoding::Scratch => (t::SCRATCH, opcode),
};
table
.binary_search_by_key(&op, |&(o, _)| o)
.ok()
.map(|i| table[i].1)
}
fn isa(offset: usize, reason: &'static str) -> ShaderError {
ShaderError::Isa { offset, reason }
}
#[cfg(test)]
mod tests {
use super::*;
const S_ENDPGM: u32 = 0xBF81_0000;
/// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction.
const fn sopp(op: u32, simm16: i16) -> u32 {
0xBF80_0000 | op << 16 | simm16 as u16 as u32
}
fn bytes(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> {
decode(&bytes(code))
.unwrap()
.iter()
.map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?")))
.collect()
}
#[test]
fn tables_are_sorted() {
for t in [
opcodes::SOP2,
opcodes::SOPK,
opcodes::SOP1,
opcodes::SOPC,
opcodes::SOPP,
opcodes::SMEM,
opcodes::VOP2,
opcodes::VOP1,
opcodes::VOPC,
opcodes::VOP3,
opcodes::VOP3P,
opcodes::VINTRP,
opcodes::DS,
opcodes::MUBUF,
opcodes::MTBUF,
opcodes::MIMG,
opcodes::FLAT,
opcodes::GLOBAL,
opcodes::SCRATCH,
] {
assert!(t.windows(2).all(|w| w[0].0 < w[1].0));
}
}
#[test]
fn lengths_and_names() {
let code = [
0xBE80_03FF,
0x3F80_0000, // s_mov_b32 s0, literal
0x0600_0000, // v_add_f32 v0, s0, v0
0xD54B_0000,
0x03FE_0000,
0x4000_0000, // v_fma_f32 with a literal src2
0xF080_0F0A,
0,
0, // image_sample (2D) with one extra address dword
0xF800_080F,
0, // exp
S_ENDPGM,
];
assert_eq!(
summary(&code),
[
(0, 2, "s_mov_b32"),
(8, 1, "v_add_f32"),
(12, 3, "v_fma_f32"),
(24, 3, "image_sample"),
(36, 2, "exp"),
(44, 1, "s_endpgm"),
]
);
}
#[test]
fn follows_branches_and_skips_data() {
let code = [
sopp(0x04, 1), // s_cbranch_scc0 -> 8
sopp(0x02, 1), // s_branch -> 12
S_ENDPGM,
S_ENDPGM,
S_ENDPGM, // data follows the program end
0xFFFF_FFFF,
];
let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect();
assert_eq!(found, [0, 4, 8, 12]);
}
#[test]
fn follows_far_jumps() {
let code = [
0xBE88_1F00, // s_getpc_b64 s[8:9]
0x8008_FF08,
20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24
0x8209_8009, // s_addc_u32 s9, s9, 0
0xBE80_2008, // s_setpc_b64 s[8:9]
0xFFFF_FFFF, // not code
S_ENDPGM,
];
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
assert_eq!(
found,
[
(0, "s_getpc_b64"),
(4, "s_add_u32"),
(12, "s_addc_u32"),
(16, "s_setpc_b64"),
(24, "s_endpgm"),
]
);
// Through other registers (a handover to another stage): the path ends.
assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1);
}
#[test]
fn follows_far_jumps_backward() {
// The compiler's backward far jump adds a negative offset: the low
// dword as a 32-bit literal, the high dword as -1 with the carry.
let code = [
sopp(0x02, 1), // s_branch -> 8, past the jump target
S_ENDPGM, // the far jump's target: only it reaches here
0xBE88_1F00, // s_getpc_b64 s[8:9]
0x8008_FF08,
0xFFFF_FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4
0x8209_C109, // s_addc_u32 s9, s9, -1
0xBE80_2008, // s_setpc_b64 s[8:9]
];
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
assert_eq!(
found,
[
(0, "s_branch"),
(4, "s_endpgm"),
(8, "s_getpc_b64"),
(12, "s_add_u32"),
(20, "s_addc_u32"),
(24, "s_setpc_b64"),
]
);
}
#[test]
fn rejects_bad_code() {
assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4");
assert!(
decode(&bytes(&[sopp(0x02, 100)])).is_err(),
"branch out of range"
);
assert!(
decode(&bytes(&[0xBE80_03FF])).is_err(),
"literal past the end"
);
assert!(
decode(&bytes(&[0xE400_0000, 0])).is_err(),
"unknown encoding"
);
// s_cbranch_scc0 into the literal of the s_mov_b32 at 4.
assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err());
}
}
File diff suppressed because it is too large. Load diff
+784
View File
@@ -0,0 +1,784 @@
//! Instruction text in AMD's SP3 assembly syntax.
use std::fmt::{self, Display, Write};
use super::fields::{Cache, Dpp, Fields, NULL, Operand, Valu};
use super::{Encoding, Instruction};
impl Instruction {
/// The instruction in SP3 syntax, e.g. `v_add_f32 v1, 0.5, v8`.
/// Branch targets are written `label_<byte offset>`.
pub fn text(&self, wave64: bool) -> String {
let name = self.name().unwrap_or("?");
let ops = operands(self, name, &self.fields(wave64));
if ops.is_empty() {
name.to_owned()
} else {
format!("{name} {ops}")
}
}
}
impl Display for Operand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Operand::Scalar { code, dwords: 1 } => f.write_str(&scalar_name(code)),
Operand::Scalar {
code: 106,
dwords: 2,
} => f.write_str("vcc"),
Operand::Scalar {
code: 126,
dwords: 2,
} => f.write_str("exec"),
Operand::Scalar { code, dwords } if code < 106 => {
write!(f, "s[{code}:{}]", code + dwords - 1)
}
Operand::Scalar { code, dwords } if (108..124).contains(&code) => {
write!(f, "ttmp[{}:{}]", code - 108, code - 108 + dwords - 1)
}
Operand::Scalar { code, .. } => f.write_str(&scalar_name(code)),
Operand::Vector { reg, dwords: 1 } => write!(f, "v{reg}"),
Operand::Vector { reg, dwords } => {
write!(f, "v[{reg}:{}]", reg as u32 + dwords as u32 - 1)
}
Operand::Const(code) => f.write_str(&const_name(code)),
Operand::Literal(value) => write!(f, "lit(0x{value:08x})"),
Operand::Attr { index, chan, .. } => write!(
f,
"attr{index}.{}",
['x', 'y', 'z', 'w'][usize::from(chan & 3)]
),
}
}
}
fn scalar_name(code: u8) -> String {
match code {
0..=105 => format!("s{code}"),
106 => "vcc_lo".into(),
107 => "vcc_hi".into(),
108..=123 => format!("ttmp{}", code - 108),
124 => "m0".into(),
125 => "null".into(),
126 => "exec_lo".into(),
_ => "exec_hi".into(),
}
}
fn const_name(code: u8) -> String {
match code {
128..=192 => (i32::from(code) - 128).to_string(),
193..=208 => (192 - i32::from(code)).to_string(),
240 => "0.5".into(),
241 => "-0.5".into(),
242 => "1.0".into(),
243 => "-1.0".into(),
244 => "2.0".into(),
245 => "-2.0".into(),
246 => "4.0".into(),
247 => "-4.0".into(),
248 => "0.15915494".into(),
235 => "src_shared_base".into(),
236 => "src_shared_limit".into(),
237 => "src_private_base".into(),
238 => "src_private_limit".into(),
239 => "src_pops_exiting_wave_id".into(),
251 => "src_vccz".into(),
252 => "src_execz".into(),
253 => "src_scc".into(),
254 => "src_lds_direct".into(),
_ => format!("<src {code}>"),
}
}
fn join(ops: impl IntoIterator<Item = String>) -> String {
ops.into_iter().collect::<Vec<_>>().join(", ")
}
fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String {
let mut out = String::new();
match fields {
Fields::Sop { dst, src, imm } => {
let regs = join(dst.iter().chain(src).map(|o| o.to_string()));
out = match (name, imm) {
("s_getreg_b32", Some(imm)) => format!("{regs}, {}", hwreg(*imm)),
("s_setreg_b32" | "s_setreg_imm32_b32", Some(imm)) => {
format!("{}, {regs}", hwreg(*imm))
}
("s_call_b64", Some(imm)) => format!("{regs}, {}", label(inst, *imm)),
(_, Some(imm)) if regs.is_empty() => format!("0x{imm:04x}"),
(_, Some(imm)) => format!("{regs}, 0x{imm:04x}"),
(_, None) => regs,
};
}
Fields::Sopp { imm } => {
out = match name {
"s_endpgm"
| "s_barrier"
| "s_code_end"
| "s_endpgm_saved"
| "s_endpgm_ordered_ps_done"
| "s_wakeup"
| "s_icache_inv"
| "s_ttracedata" => String::new(),
"s_branch" => label(inst, *imm),
n if n.starts_with("s_cbranch_") => label(inst, *imm),
"s_waitcnt" => waitcnt(*imm),
"s_sendmsg" | "s_sendmsghalt" => sendmsg(*imm),
_ => format!("0x{imm:04x}"),
};
}
Fields::Smem {
data,
base,
offset,
soffset,
cache,
} => {
if let Some(data) = data {
let off = match (soffset, offset) {
(Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(),
(Operand::Scalar { code: NULL, .. }, _) => {
format!("0x{:06x}", offset & 0x1F_FFFF)
}
(_, 0) => soffset.to_string(),
_ => format!("{soffset} offset:0x{:06x}", offset & 0x1F_FFFF),
};
out = format!("{data}, {base}, {off}");
}
flags(&mut out, cache, false);
}
Fields::Valu(v) => out = valu(name, v, inst.encoding),
Fields::Vintrp { dst, src, attr } => {
let src = match (name, src) {
("v_interp_mov_f32", Operand::Const(p)) => ["p10", "p20", "p0"]
.get(usize::from(*p))
.map_or("p?".into(), |p| p.to_string()),
_ => src.to_string(),
};
out = format!("{dst}, {src}, {attr}");
}
Fields::Ds {
dst,
addr,
data,
offset0,
offset1,
gds,
} => {
out = join(dst.iter().chain(addr).chain(data).map(|o| o.to_string()));
if super::fields::ds_pair(name) {
if *offset0 != 0 {
let _ = write!(out, " offset0:{offset0}");
}
if *offset1 != 0 {
let _ = write!(out, " offset1:{offset1}");
}
} else {
let offset = u16::from(*offset1) << 8 | u16::from(*offset0);
if offset != 0 {
let _ = write!(out, " offset:{offset}");
}
}
if *gds {
out.push_str(" gds");
}
}
Fields::Buffer {
data,
addr,
rsrc,
soffset,
offset,
offen,
idxen,
format,
lds,
tfe,
cache,
} => {
if let Some(data) = data {
out = format!("{data}, {addr}, {rsrc}, {soffset}");
if *idxen {
out.push_str(" idxen");
}
if *offen {
out.push_str(" offen");
}
if *offset != 0 {
let _ = write!(out, " offset:{offset}");
}
if let Some(format) = format {
let _ = write!(out, " format:[{}]", buffer_format(*format));
}
}
flags(&mut out, cache, false);
if *lds {
out.push_str(" lds");
}
if *tfe {
out.push_str(" tfe");
}
}
Fields::Image {
data,
addr,
rsrc,
sampler,
dmask,
dim,
unorm,
r128,
a16,
d16,
tfe,
lwe,
cache,
} => {
let addr = match addr.as_slice() {
[one] => one.to_string(),
many => format!(
"[{}]",
many.iter()
.map(|o| o.to_string())
.collect::<Vec<_>>()
.join(",")
),
};
out = join(
[data.to_string(), addr, rsrc.to_string()]
.into_iter()
.chain(sampler.map(|s| s.to_string())),
);
if *dmask != 1 {
let _ = write!(out, " dmask:0x{dmask:x}");
}
let dims = [
"1D",
"2D",
"3D",
"CUBE",
"1D_ARRAY",
"2D_ARRAY",
"2D_MSAA",
"2D_MSAA_ARRAY",
];
let _ = write!(out, " dim:SQ_RSRC_IMG_{}", dims[usize::from(*dim & 7)]);
for (on, text) in [(*r128, "r128"), (*unorm, "unorm")] {
if on {
out.push(' ');
out.push_str(text);
}
}
flags(&mut out, cache, true);
for (on, text) in [(*a16, "a16"), (*d16, "d16"), (*tfe, "tfe"), (*lwe, "lwe")] {
if on {
out.push(' ');
out.push_str(text);
}
}
}
Fields::Flat {
dst,
addr,
data,
saddr,
offset,
lds,
cache,
} => {
let addr = addr.map_or("off".into(), |a| a.to_string());
out = join(
dst.iter()
.map(|o| o.to_string())
.chain([addr])
.chain(data.iter().chain(saddr).map(|o| o.to_string())),
);
if *offset != 0 {
let _ = write!(out, " inst_offset:{offset}");
}
flags(&mut out, cache, false);
if *lds {
out.push_str(" lds");
}
}
Fields::Exp {
target,
src,
compr,
done,
vm,
} => {
let target = match *target {
0..=7 => format!("mrt{target}"),
8 => "mrtz".into(),
9 => "null".into(),
12..=15 => format!("pos{}", target - 12),
20 => "prim".into(),
32..=63 => format!("param{}", target - 32),
_ => format!("<target {target}>"),
};
out = join(
[target].into_iter().chain(
src.iter()
.map(|s| s.map_or("off".into(), |o| o.to_string())),
),
);
for (on, text) in [(*done, " done"), (*compr, " compr"), (*vm, " vm")] {
if on {
out.push_str(text);
}
}
}
}
out
}
/// Cache flags; images write `dlc` first.
fn flags(out: &mut String, cache: &Cache, dlc_first: bool) {
let dlc = (cache.dlc, " dlc");
let (first, last) = if dlc_first {
(dlc, (false, ""))
} else {
((false, ""), dlc)
};
for (on, text) in [first, (cache.glc, " glc"), (cache.slc, " slc"), last] {
if on {
out.push_str(text);
}
}
if out.starts_with(' ') {
out.remove(0);
}
}
fn label(inst: &Instruction, imm: u16) -> String {
let target = inst.offset as i64 + 4 * inst.words.len() as i64 + 4 * i64::from(imm as i16);
format!("label_{target:04X}")
}
fn hwreg(imm: u16) -> String {
let (id, offset, size) = (imm & 0x3F, imm >> 6 & 0x1F, (imm >> 11 & 0x1F) + 1);
let name = match id {
1 => "HW_REG_MODE".into(),
20 => "HW_REG_SHADER_FLAT_SCRATCH_LO".into(),
21 => "HW_REG_SHADER_FLAT_SCRATCH_HI".into(),
25 => "HW_REG_POPS_PACKER".into(),
_ => id.to_string(),
};
if offset == 0 && size == 32 {
format!("hwreg({name})")
} else {
format!("hwreg({name}, {offset}, {size})")
}
}
fn waitcnt(imm: u16) -> String {
let vm = imm & 0xF | (imm >> 14) << 4;
let exp = imm >> 4 & 7;
let lgkm = imm >> 8 & 0x3F;
let mut parts = Vec::new();
if vm != 0x3F {
parts.push(format!("vmcnt({vm})"));
}
if exp != 7 {
parts.push(format!("expcnt({exp})"));
}
if lgkm != 0x3F {
parts.push(format!("lgkmcnt({lgkm})"));
}
if matches!(parts.len(), 0 | 3) {
return format!("0x{imm:04x}");
}
parts.join(" & ")
}
fn sendmsg(imm: u16) -> String {
let (msg, op, stream) = (imm & 0xF, imm >> 4 & 7, imm >> 8 & 3);
let msg_name = match msg {
2 => "MSG_GS".into(),
3 => "MSG_GS_DONE".into(),
7 => "MSG_ORDERED_PS_DONE".into(),
9 => "MSG_GS_ALLOC_REQ".into(),
_ => msg.to_string(),
};
let op_name = ["GS_OP_NOP", "GS_OP_CUT", "GS_OP_EMIT", "GS_OP_EMIT_CUT"]
.get(usize::from(op))
.map_or(op.to_string(), |s| s.to_string());
if msg == 3 && op == 0 {
format!("sendmsg({msg_name}, {op_name})")
} else {
format!("sendmsg({msg_name}, {op_name}, {stream})")
}
}
fn buffer_format(format: u8) -> String {
const NAMES: [&str; 78] = [
"INVALID",
"8_UNORM",
"8_SNORM",
"8_USCALED",
"8_SSCALED",
"8_UINT",
"8_SINT",
"16_UNORM",
"16_SNORM",
"16_USCALED",
"16_SSCALED",
"16_UINT",
"16_SINT",
"16_FLOAT",
"8_8_UNORM",
"8_8_SNORM",
"8_8_USCALED",
"8_8_SSCALED",
"8_8_UINT",
"8_8_SINT",
"32_UINT",
"32_SINT",
"32_FLOAT",
"16_16_UNORM",
"16_16_SNORM",
"16_16_USCALED",
"16_16_SSCALED",
"16_16_UINT",
"16_16_SINT",
"16_16_FLOAT",
"10_11_11_UNORM",
"10_11_11_SNORM",
"10_11_11_USCALED",
"10_11_11_SSCALED",
"10_11_11_UINT",
"10_11_11_SINT",
"10_11_11_FLOAT",
"11_11_10_UNORM",
"11_11_10_SNORM",
"11_11_10_USCALED",
"11_11_10_SSCALED",
"11_11_10_UINT",
"11_11_10_SINT",
"11_11_10_FLOAT",
"10_10_10_2_UNORM",
"10_10_10_2_SNORM",
"10_10_10_2_USCALED",
"10_10_10_2_SSCALED",
"10_10_10_2_UINT",
"10_10_10_2_SINT",
"2_10_10_10_UNORM",
"2_10_10_10_SNORM",
"2_10_10_10_USCALED",
"2_10_10_10_SSCALED",
"2_10_10_10_UINT",
"2_10_10_10_SINT",
"8_8_8_8_UNORM",
"8_8_8_8_SNORM",
"8_8_8_8_USCALED",
"8_8_8_8_SSCALED",
"8_8_8_8_UINT",
"8_8_8_8_SINT",
"32_32_UINT",
"32_32_SINT",
"32_32_FLOAT",
"16_16_16_16_UNORM",
"16_16_16_16_SNORM",
"16_16_16_16_USCALED",
"16_16_16_16_SSCALED",
"16_16_16_16_UINT",
"16_16_16_16_SINT",
"16_16_16_16_FLOAT",
"32_32_32_UINT",
"32_32_32_SINT",
"32_32_32_FLOAT",
"32_32_32_32_UINT",
"32_32_32_32_SINT",
"32_32_32_32_FLOAT",
];
NAMES
.get(usize::from(format))
.map_or(format!("{format}"), |n| format!("BUF_FMT_{n}"))
}
fn valu(name: &str, v: &Valu, encoding: Encoding) -> String {
let bit = |mask: u8, i: usize| mask >> i & 1 != 0;
let mix = name.starts_with("v_fma_mix");
let src = |i: usize| {
let o = v.src[i];
let mut s = o.to_string();
if let Some(sdwa) = v.sdwa
&& bit(sdwa.sext, i)
{
s = format!("sext({s})");
}
if encoding == Encoding::Vop3p {
if mix {
if bit(v.opsel_hi, i) {
s = format!("{}({s})", if bit(v.opsel, i) { "sel_hi" } else { "sel_lo" });
}
if bit(v.neg_hi, i) {
s = format!("abs({s})");
}
if bit(v.neg, i) {
s = format!("-{s}");
}
} else {
if bit(v.neg, i) && bit(v.neg_hi, i) {
s = format!("-{s}");
}
match (bit(v.opsel, i), bit(v.opsel_hi, i)) {
(false, true) => {}
(false, false) => s = format!("sel_lo({s})"),
(true, true) => s = format!("sel_hi({s})"),
(true, false) => s = format!("sel_hi_lo({s})"),
}
}
} else {
if bit(v.abs, i) {
s = format!("abs({s})");
}
if bit(v.neg, i) {
s = format!("-{s}");
}
// v_permlane*: the opsel bits are fi and bound_ctrl.
if bit(v.opsel, i) && !name.starts_with("v_permlane") {
s = format!("sel_hi({s})");
}
}
s
};
let mut ops: Vec<String> = v
.dst
.iter()
.chain(&v.carry)
.map(|o| o.to_string())
.collect();
let mut order: Vec<usize> = (0..v.src.len()).collect();
if name.starts_with("v_interp_") && order.len() > 1 {
// dst, i/j, attribute, then the p1 result for p2.
order.swap(0, 1);
}
ops.extend(order.into_iter().map(src));
let mut out = ops.join(", ");
let mut suffix = |s: &str| {
out.push(' ');
out.push_str(s);
};
if let Some(Operand::Attr { high: true, .. }) = v.src.first() {
suffix("high");
}
let omod = ["", "mul:2", "mul:4", "div:2"][usize::from(v.omod & 3)];
if name.starts_with("v_permlane") {
if v.opsel & 1 != 0 {
suffix("fi:1");
}
if v.opsel & 2 != 0 {
suffix("bound_ctrl:1");
}
}
if let Some(sdwa) = v.sdwa {
if v.clamp {
suffix("clamp");
}
if !omod.is_empty() {
suffix(omod);
}
let sel = [
"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD", "?",
];
if sdwa.dst_sel != 6 {
suffix(&format!("dst_sel:{}", sel[usize::from(sdwa.dst_sel & 7)]));
}
if sdwa.dst_unused != 0 {
let unused = ["UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE", "?"];
suffix(&format!(
"dst_unused:{}",
unused[usize::from(sdwa.dst_unused & 3)]
));
}
for (i, s) in sdwa.src_sel.iter().enumerate() {
if *s != 6 {
suffix(&format!("src{i}_sel:{}", sel[usize::from(s & 7)]));
}
}
} else {
if !omod.is_empty() {
suffix(omod);
}
if v.clamp {
suffix("clamp");
}
}
match v.dpp {
Some(Dpp::Row {
ctrl,
row_mask,
bank_mask,
bound_ctrl,
fi,
}) => {
suffix(&match ctrl {
0x000..=0x0FF => format!(
"quad_perm:[{},{},{},{}]",
ctrl & 3,
ctrl >> 2 & 3,
ctrl >> 4 & 3,
ctrl >> 6 & 3
),
0x101..=0x10F => format!("row_shl:{}", ctrl & 0xF),
0x111..=0x11F => format!("row_shr:{}", ctrl & 0xF),
0x121..=0x12F => format!("row_ror:{}", ctrl & 0xF),
0x140 => "row_mirror".into(),
0x141 => "row_half_mirror".into(),
0x150..=0x15F => format!("row_share:{}", ctrl & 0xF),
0x160..=0x16F => format!("row_xmask:{}", ctrl & 0xF),
_ => format!("dpp_ctrl:0x{ctrl:x}"),
});
if row_mask != 0xF {
suffix(&format!("row_mask:0x{row_mask:x}"));
}
if bank_mask != 0xF {
suffix(&format!("bank_mask:0x{bank_mask:x}"));
}
if bound_ctrl {
suffix("bound_ctrl:1");
}
if fi {
suffix("fi:1");
}
}
Some(Dpp::Lanes { sel, fi }) => {
let lanes: Vec<String> = (0..8).map(|i| (sel >> (3 * i) & 7).to_string()).collect();
suffix(&format!("dpp8:[{}]", lanes.join(",")));
if fi {
suffix("fi:1");
}
}
None => {}
}
out
}
#[cfg(test)]
mod tests {
use crate::gfx10::{Fields, Operand, decode};
/// Text of each instruction in `words` (a straight-line program).
fn texts(words: &[u32], wave64: bool) -> Vec<String> {
let mut code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
code.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm
let insts = decode(&code).unwrap();
insts[..insts.len() - 1]
.iter()
.map(|i| i.text(wave64))
.collect()
}
fn one(words: &[u32], wave64: bool) -> String {
let t = texts(words, wave64);
assert_eq!(t.len(), 1, "{t:?}");
t[0].clone()
}
#[test]
fn scalar() {
assert_eq!(
texts(&[0xBF88_0001, 0xBF8C_0070, 0xBE80_03FF, 0x1234_5678], true),
[
"s_cbranch_execz label_0008",
"s_waitcnt vmcnt(0) & lgkmcnt(0)",
"s_mov_b32 s0, lit(0x12345678)",
]
);
assert_eq!(one(&[0x8782_027E], true), "s_and_b64 s[2:3], exec, s[2:3]");
assert_eq!(
one(&[0xF408_0501, 0xFA00_0040], true),
"s_load_dwordx4 s[20:23], s[2:3], 0x000040"
);
assert_eq!(
one(&[0xF420_0144, 0x0400_0000], true),
"s_buffer_load_dword s5, s[8:11], s2"
);
}
#[test]
fn lane_masks_follow_the_wave_size() {
let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3
assert_eq!(one(&cmp, false), "v_cmp_gt_f32 vcc_lo, 0.5, v3");
assert_eq!(one(&cmp, true), "v_cmp_gt_f32 vcc, 0.5, v3");
let vop3 = [0xD401_0106, 0x0001_E501]; // v_cmp_lt_f32 to s6, |v1| < 1.0
assert_eq!(one(&vop3, false), "v_cmp_lt_f32 s6, abs(v1), 1.0");
assert_eq!(one(&vop3, true), "v_cmp_lt_f32 s[6:7], abs(v1), 1.0");
assert_eq!(
one(&[0x0202_0480], false),
"v_cndmask_b32 v1, 0, v2, vcc_lo"
);
assert_eq!(
one(&[0x5006_0801], true),
"v_add_co_ci_u32 v3, vcc, s1, v4, vcc"
);
}
#[test]
fn vector_modifiers() {
assert_eq!(
one(&[0x1004_0AFF, 0x3F00_0001], true),
"v_mul_f32 v2, lit(0x3f000001), v5"
);
assert_eq!(
one(&[0xD54B_8004, 0x2BC0_0501], true),
"v_fma_f32 v4, -v1, s2, 0.5 mul:2 clamp"
);
assert_eq!(
one(&[0x7E02_16F9, 0x0605_0602], true),
"v_cvt_f32_f16 v1, v2 src0_sel:WORD_1"
);
assert_eq!(
one(&[0x7E06_02E9, 0x0539_7701], true),
"v_mov_b32 v3, v1 dpp8:[7,6,5,4,3,2,1,0]"
);
assert_eq!(
one(&[0x7E0A_02FA, 0xFF08_B106], true),
"v_mov_b32 v5, v6 quad_perm:[1,0,3,2] bound_ctrl:1"
);
assert_eq!(
one(&[0xCC20_0C01, 0x2C10_0702], true),
"v_fma_mix_f32 v1, -sel_hi(v2), s3, abs(v4)"
);
}
#[test]
fn memory_and_export() {
assert_eq!(
one(&[0xE034_7010, 0x0102_0402], true),
"buffer_load_dwordx2 v[4:5], v[2:3], s[8:11], s1 idxen offen offset:16 glc"
);
assert_eq!(
one(&[0xD8DC_0302, 0x0600_0001], true),
"ds_read2_b32 v[6:7], v1 offset0:2 offset1:3"
);
assert_eq!(
one(&[0xF800_1C0F, 0x0000_0302], true),
"exp mrt0, v2, v2, v3, v3 done compr vm"
);
}
#[test]
fn image_d16_data_is_packed() {
// Three f16 channels occupy two VGPRs; NSA lists the addresses.
let words = [0xF09C_070A, 0x8024_0801, 0x0000_0005];
assert_eq!(
one(&words, true),
"image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 dim:SQ_RSRC_IMG_2D d16"
);
let code: Vec<u8> = words
.iter()
.chain(&[0xBF81_0000])
.flat_map(|w| w.to_le_bytes())
.collect();
let Fields::Image { data, addr, .. } = decode(&code).unwrap()[0].fields(true) else {
panic!("not an image instruction");
};
assert_eq!(data, Operand::Vector { reg: 8, dwords: 2 });
assert_eq!(addr.len(), 2);
}
}
+826
View File
@@ -0,0 +1,826 @@
//! I/O raising (decision 0003): what a program's input registers, its
//! interpolation and its exports mean.
//!
//! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed
//! order (barycentrics, then position, front face...). `v_interp_p1` and
//! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of
//! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit
//! export patch ([`NativeProgram::patched_code`]) exports carry plain
//! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and
//! sample mask, `null` nothing. A lane whose EXEC bit is clear at the
//! export that ends the program (`done`) is discarded: that export's guard
//! after structurisation.
//!
//! Vertex shaders that run as the hardware VS get the vertex id in v0, the
//! primitive id in v2 and the instance id in v3; the fetch shader loads
//! channel k of each attribute into its VGPR + k. `exp pos0` is the
//! position, `exp param<n>` the output with parameter n.
//!
//! Attributes and outputs are named by their row: a register of the
//! container's signature part.
//!
//! Compute programs get the thread id in the group in v0-v2 and the group
//! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them.
//!
//! Mesh programs run as one NGG stage. The program computes its thread
//! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and
//! its group id from v5 of the first lane (`v_readfirstlane`: the group
//! times the group size). Lane n exports vertex n (`exp pos`, `exp param`)
//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20,
//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One
//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices |
//! primitives << 12).
use crate::ShaderError;
use crate::gfx10::{Fields, Operand};
use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads};
use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
use crate::resource::Site;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Input {
VertexId,
PrimitiveId,
InstanceId,
/// A vertex attribute the fetch shader loads.
Attribute {
row: u8,
channel: u8,
},
/// `index` 0 is i, 1 is j (2 the pull model's w).
Barycentric {
kind: Barycentric,
index: u8,
},
/// Pixel position channel (0-3: x, y, z, w).
Position(u8),
FrontFace,
/// Sample id and other bits.
Ancillary,
SampleCoverage,
FixedPosition,
LineStipple,
/// Compute: thread-group id component (an SGPR).
GroupId(u8),
/// Compute: thread id within the group, component (a VGPR).
ThreadIdInGroup(u8),
/// Compute: the thread-group info SGPR (wave index and count).
GroupInfo,
/// Mesh: v5, the group id times the group size (read as uniform).
MeshGroup,
/// Mesh: s3, the wave's index in the group in bits 24-27.
MergedWaveInfo,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Barycentric {
PerspectiveSample,
PerspectiveCenter,
PerspectiveCentroid,
PerspectivePullModel,
LinearSample,
LinearCenter,
LinearCentroid,
}
/// The pixel input VGPRs in hardware order: one entry per
/// `SPI_PS_INPUT_ADDR` bit.
const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [
(2, Some(Barycentric::PerspectiveSample)),
(2, Some(Barycentric::PerspectiveCenter)),
(2, Some(Barycentric::PerspectiveCentroid)),
(3, Some(Barycentric::PerspectivePullModel)),
(2, Some(Barycentric::LinearSample)),
(2, Some(Barycentric::LinearCenter)),
(2, Some(Barycentric::LinearCentroid)),
(1, None), // line stipple
(1, None), // position x
(1, None), // y
(1, None), // z
(1, None), // w
(1, None), // front face
(1, None), // ancillary
(1, None), // sample coverage
(1, None), // fixed-point position
];
fn ps_system(bit: usize) -> Input {
match bit {
7 => Input::LineStipple,
8..=11 => Input::Position(bit as u8 - 8),
12 => Input::FrontFace,
13 => Input::Ancillary,
14 => Input::SampleCoverage,
_ => Input::FixedPosition,
}
}
/// An attribute channel of the input signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Attribute {
pub usage: Usage,
pub row: u8,
pub channel: u8,
/// The upper f16 half of the channel (packed fp16 inputs).
pub high: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Interp {
/// This site's result (`v_interp_p2*`) is the attribute interpolated
/// with `barycentric`; `first` are the `v_interp_p1*` halves it
/// completes (one per path where the compiler shares a first half).
Interpolated {
attribute: Attribute,
barycentric: Barycentric,
first: Vec<Site>,
},
/// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
/// 1 for P20, 2 for P0 (the provoking vertex).
Vertex { attribute: Attribute, vertex: u8 },
/// A half of an interpolation whose i or j is computed rather than
/// loaded: each half evaluates as the hardware does, from the
/// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 =
/// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0).
Weighted { attribute: Attribute },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
Color(u8),
/// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables).
Depth,
Null,
Position(u8),
Param {
usage: Usage,
row: u8,
},
/// `param0` of a vertex shader without outputs: the hardware wants one
/// parameter export regardless.
Unread,
/// The primitive export of a merged or mesh stage.
Primitive,
/// A mesh program's per-primitive output (a row of `PSG1`).
PrimitiveParam {
usage: Usage,
row: u8,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Export {
pub site: Site,
pub target: Target,
/// Per channel, as the instruction enables them.
pub values: [Option<Value>; 4],
/// Two f16 values per dword.
pub compressed: bool,
/// The program's last export (for pixels: kills the lanes not in EXEC).
pub done: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Io {
/// Input values the hardware loads, with their meaning; other VGPRs
/// read before written hold undefined values.
pub inputs: Vec<(Value, Input)>,
pub interps: Vec<(Site, Interp)>,
pub exports: Vec<Export>,
/// Compute: how many SGPRs the hardware initializes
/// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)).
pub initialized_sgprs: Option<u8>,
}
/// Raises the I/O of `p`, built from `native`'s patched code. Fails for
/// stages whose stage data is not read and on constructs not covered yet.
pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
let unsupported = |offset, what| ShaderError::Unsupported { offset, what };
let (loaded, ps_inputs, params) = match (&native.io, native.stage) {
(
StageIo::Ps {
inputs, input_addr, ..
},
HwStage::Ps,
) => {
// A pixel shader exports no parameters; `[]` never reaches `Unread`.
let loaded = ps_vgprs(*input_addr)
.into_iter()
.map(|(r, i)| (Reg::V(r), i))
.collect();
(loaded, &inputs[..], &[][..])
}
(StageIo::Vs { inputs, outputs }, HwStage::Vs) => {
let mut loaded = vec![
(Reg::V(0), Input::VertexId),
(Reg::V(2), Input::PrimitiveId),
(Reg::V(3), Input::InstanceId),
];
for i in inputs {
for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) {
let input = Input::Attribute {
row: i.row,
channel,
};
loaded.push((Reg::V(i.vgpr + channel), input));
}
}
(loaded, &[][..], &outputs[..])
}
// Compute: thread ids in v0-v2, group ids and the group info in the
// SGPRs after the user data.
(StageIo::Cs(cs), HwStage::Cs) => {
let (ids, info) = cs.system_sgprs();
let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs())
.map(|c| (Reg::V(c), Input::ThreadIdInGroup(c)))
.collect();
for (c, s) in ids.into_iter().enumerate() {
if let Some(s) = s {
loaded.push((Reg::S(s), Input::GroupId(c as u8)));
}
}
loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo)));
(loaded, &[][..], &[][..])
}
(StageIo::Ms(ms), HwStage::Ms) => {
// The group input, and the phis that may carry it past a join.
let mut group: Vec<Value> = p
.inputs
.iter()
.filter(|i| i.0 == Reg::V(5))
.map(|i| i.1)
.collect();
// No lane is active over the EXEC-zero edge of s_cbranch_execz or
// _execnz, the same case as a partial-EXEC write below.
let no_lanes = |q: usize, b: usize| match (
p.blocks[q].insts.last().map(Inst::name),
p.blocks[q].exit,
) {
(Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => {
taken == b && not_taken != b
}
(Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => {
not_taken == b && taken != b
}
_ => false,
};
while let Some(v) = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f)))
.find_map(|(b, f)| {
let mut args = f.args.iter().zip(&p.blocks[b].preds);
let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b));
(carried && !group.contains(&f.value)).then_some(f.value)
})
{
group.push(v);
}
// The group input holds the same value in every lane only as the
// first lane reads it. A write to v5 reads its old value too, which
// only lanes outside EXEC keep.
// shortcut: writes that may keep the old v5 in active lanes
// (v_fmac_f32's accumulator, a 16-bit half or d16 load,
// v_writelane_b32, v_movreld_b32, DPP that skips lanes) and
// partial-EXEC writes pass; check those too if a mesh program
// writes v5 that way.
let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
i.read(Reg::V(5)).is_some_and(|v| group.contains(&v))
&& i.name() != "v_readfirstlane_b32"
&& (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5)))
});
if let Some(i) = per_lane {
return Err(unsupported(
i.machine.offset,
"the mesh group input read per lane",
));
}
let loaded = vec![
(Reg::V(5), Input::MeshGroup),
(Reg::S(3), Input::MergedWaveInfo),
];
(loaded, &[][..], &ms.outputs[..])
}
_ => return Err(unsupported(0, "I/O of this stage")),
};
let inputs: Vec<(Value, Input)> = p
.inputs
.iter()
.filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1)))
.collect();
let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1);
let attribute = |inst: &Inst, attr: &Operand| match *attr {
Operand::Attr { index, chan, high } => ps_inputs
.iter()
.find(|i: &&PsInput| i.attr == index)
.map(|i| Attribute {
usage: i.usage,
row: i.row,
channel: chan,
high,
})
.ok_or(unsupported(
inst.machine.offset,
"an interpolated attribute the stage data does not list",
)),
_ => Err(unsupported(inst.machine.offset, "an interpolation operand")),
};
// A VGPR value's barycentric kind and index, if it is one as loaded.
let barycentric = |v: Option<Value>| match v.and_then(input_of) {
Some(Input::Barycentric { kind, index }) => Some((kind, index)),
_ => None,
};
let mut io = Io {
inputs: inputs.clone(),
initialized_sgprs: match &native.io {
StageIo::Cs(cs) => Some(cs.initialized_sgprs()),
_ => None,
},
..Io::default()
};
let defs: std::collections::HashMap<Value, Site> = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, block)| {
block
.insts
.iter()
.enumerate()
.flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i))))
})
.collect();
let phis: std::collections::HashMap<Value, (usize, usize)> = p
.blocks
.iter()
.enumerate()
.flat_map(|(b, block)| {
block
.phis
.iter()
.enumerate()
.map(move |(i, phi)| (phi.value, (b, i)))
})
.collect();
let halves = Halves {
p,
defs: &defs,
phis: &phis,
};
for (b, block) in p.blocks.iter().enumerate() {
for (i, inst) in block.insts.iter().enumerate() {
let site = (b, i);
let at = inst.machine.offset;
let name = inst.name();
match &inst.fields {
Fields::Vintrp { dst, src, attr } => {
let attribute = attribute(inst, attr)?;
match (name, *src) {
("v_interp_mov_f32", Operand::Const(vertex)) => {
io.interps
.push((site, Interp::Vertex { attribute, vertex }));
}
("v_interp_p1_f32", _) => {}
("v_interp_p2_f32", Operand::Vector { reg, .. }) => {
let Operand::Vector { reg: d, .. } = *dst else {
return Err(unsupported(at, "an interpolation operand"));
};
// The first half's result is this one's old dst.
let interp = halves
.pair(
attr,
inst.read(Reg::V(d)),
inst.read(Reg::V(reg)),
&barycentric,
)
.map_err(|what| unsupported(at, what))?;
push_pair(&mut io, site, interp, attribute);
}
_ => return Err(unsupported(at, "an interpolation form")),
}
}
Fields::Valu(v) if name.starts_with("v_interp_") => match name {
"v_interp_p1ll_f16" => {}
"v_interp_p2_f16" => {
let attribute = attribute(inst, &v.src[0])?;
let read = |k: usize| match v.src.get(k) {
Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
_ => None,
};
let interp = halves
.pair(&v.src[0], read(2), read(1), &barycentric)
.map_err(|what| unsupported(at, what))?;
push_pair(&mut io, site, interp, attribute);
}
_ => return Err(unsupported(at, "an interpolation form")),
},
Fields::Exp {
target,
src,
compr,
done,
..
} => {
let target = match *target {
t @ 0..=7 => Target::Color(t),
8 => Target::Depth,
9 => Target::Null,
t @ 12..=16 => Target::Position(t - 12),
20 => Target::Primitive,
32 if params.is_empty() => Target::Unread,
t @ 32..=63 => {
// Bit 7: a mesh program's per-primitive output.
let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or(
unsupported(at, "a parameter export the stage data does not list"),
)?;
let (usage, row) = (o.usage, o.row);
if o.param & 0x80 != 0 {
Target::PrimitiveParam { usage, row }
} else {
Target::Param { usage, row }
}
}
_ => return Err(unsupported(at, "an export target")),
};
let values = src.map(|s| match s {
Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
_ => None,
});
io.exports.push(Export {
site,
target,
values,
compressed: *compr,
done: *done,
});
}
_ => {}
}
}
}
Ok(io)
}
/// The pixel input VGPRs that `addr` enables, with their meaning.
fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
let mut out = Vec::new();
let mut next = 0u8;
for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() {
if addr >> bit & 1 == 0 {
continue;
}
for index in 0..count {
let input = match kind {
Some(kind) => Input::Barycentric { kind, index },
None => ps_system(bit),
};
out.push((next + index, input));
}
next += count;
}
out
}
/// An interpolation before its attribute is known: `barycentric` none
/// when i or j is computed.
struct Pair {
barycentric: Option<Barycentric>,
first: Vec<Site>,
}
impl Pair {
fn with(self, attribute: Attribute) -> Interp {
match self.barycentric {
Some(barycentric) => Interp::Interpolated {
attribute,
barycentric,
first: self.first,
},
None => Interp::Weighted { attribute },
}
}
}
/// Records interpolation `pair` at `site`, and its first halves too when
/// they evaluate on their own (computed barycentrics).
fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) {
if pair.barycentric.is_none() {
for &f in &pair.first {
if !io.interps.iter().any(|(s, _)| *s == f) {
io.interps.push((f, Interp::Weighted { attribute }));
}
}
}
io.interps.push((site, pair.with(attribute)));
}
/// Finds the first halves of interpolations.
struct Halves<'a> {
p: &'a Program,
defs: &'a std::collections::HashMap<Value, Site>,
phis: &'a std::collections::HashMap<Value, (usize, usize)>,
}
impl Halves<'_> {
/// The interpolation whose second half reads the first half's result
/// `acc`, the barycentric `j`, and attribute `attr`: every first half
/// must read the same attribute channel. With j and every first half's
/// i loaded as one kind's, the pair interpolates with that kind;
/// otherwise each half evaluates on its own (`Interp::Weighted`).
fn pair(
&self,
attr: &Operand,
acc: Option<Value>,
j: Option<Value>,
barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>,
) -> Result<Pair, &'static str> {
let mut first = Vec::new();
self.sites(
acc.ok_or("an interpolation without its first half")?,
&mut Vec::new(),
&mut first,
)?;
let mut kind = match barycentric(j) {
Some((kind, 1)) => Some(kind),
_ => None,
};
for &(b, i) in &first {
let inst = &self.p.blocks[b].insts[i];
let (a, i) = match &inst.fields {
Fields::Vintrp {
src: Operand::Vector { reg, .. },
attr,
..
} if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))),
Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) {
Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))),
_ => return Err("an interpolation without its first half"),
},
_ => return Err("an interpolation without its first half"),
};
if a != *attr {
return Err("interpolation halves of different attributes");
}
if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) {
kind = None;
}
}
Ok(Pair {
barycentric: kind,
first,
})
}
/// The instructions `v` comes from, through phis (`seen`: phis on the
/// way; a loop back to one adds nothing).
fn sites(
&self,
v: Value,
seen: &mut Vec<Value>,
out: &mut Vec<Site>,
) -> Result<(), &'static str> {
if let Some(&site) = self.defs.get(&v) {
if !out.contains(&site) {
out.push(site);
}
return Ok(());
}
let &(b, i) = self
.phis
.get(&v)
.ok_or("an interpolation without its first half")?;
if !seen.contains(&v) {
seen.push(v);
for &a in &self.p.blocks[b].phis[i].args {
self.sites(a, seen, out)?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::native::ExportPatch;
const S_ENDPGM: u32 = 0xBF81_0000;
fn program(words: &[u32]) -> Program {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
crate::ir::build(&code, false, 256).unwrap()
}
fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram {
NativeProgram {
stage: HwStage::Ps,
wave64: false,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Ps {
inputs,
input_addr,
db_shader_control: 0,
patches: Vec::<ExportPatch>::new(),
},
code: vec![],
}
}
const TEXCOORD: PsInput = PsInput {
usage: Usage::Generic,
row: 1,
mask: 3,
attr: 0,
flat: false,
fp16: false,
pack2: false,
row2: 1,
};
#[test]
fn interpolation_pairs_and_color_exports() {
// Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j
// in v0/v1, then exported unconverted to MRT0.
let p = program(&[
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
0xF800_180F,
0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm
S_ENDPGM,
]);
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1;
let center = |index| Input::Barycentric {
kind: Barycentric::PerspectiveCenter,
index,
};
assert!(io.inputs.contains(&(input(0), center(0))));
assert!(io.inputs.contains(&(input(1), center(1))));
// v2 and v3 are read before written but hold nothing.
assert!(!io.inputs.iter().any(|i| i.0 == input(3)));
assert_eq!(
io.interps,
[(
(0, 1),
Interp::Interpolated {
attribute: Attribute {
usage: Usage::Generic,
row: 1,
channel: 0,
high: false
},
barycentric: Barycentric::PerspectiveCenter,
first: vec![(0, 0)],
}
)]
);
let [e] = &io.exports[..] else {
panic!("{:?}", io.exports)
};
assert_eq!(
(e.target, e.done, e.compressed),
(Target::Color(0), true, false)
);
assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2)));
}
#[test]
fn unpaired_or_unknown_interpolation_fails() {
// p2 alone: its old dst is no p1's result.
let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x
assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err());
// attr1 is not in the stage data.
let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x
assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
}
#[test]
fn computed_barycentrics_evaluate_each_half() {
// i scaled before the first half: both halves stand on their own.
let p = program(&[
0x1006_00F0, // v_mul_f32 v3, 0.5, v0
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
S_ENDPGM,
]);
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
let attribute = Attribute {
usage: Usage::Generic,
row: 1,
channel: 0,
high: false,
};
let mut interps = io.interps.clone();
interps.sort_by_key(|i| i.0);
assert_eq!(
interps,
[
((0, 1), Interp::Weighted { attribute }),
((0, 2), Interp::Weighted { attribute }),
]
);
}
#[test]
fn mesh_inputs_and_primitive_export() {
let mesh = |words: &[u32]| {
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let p = crate::ir::build(&code, true, 256).unwrap();
let native = NativeProgram {
stage: HwStage::Ms,
wave64: true,
vgprs: 256,
layout: vec![],
used: vec![],
io: StageIo::Ms(crate::native::MeshIo {
outputs: vec![],
clip_cntl: 0,
threads: 128,
max_vertices: 128,
max_primitives: 128,
topology: 2,
lds_bytes: 0,
}),
code,
};
raise(&p, &native)
};
let io = mesh(&[
0x7E04_0505, // v_readfirstlane_b32 s2, v5
0xF800_0941,
0x0000_0009, // exp prim, v9, off, off, off done
S_ENDPGM,
])
.unwrap();
assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup));
assert_eq!(io.exports[0].target, Target::Primitive);
// The group input is uniform only as the first lane reads it.
assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
// Also as an operand of a write to v5, or after a join.
let per_lane: [&[u32]; 5] = [
&[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1
&[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5
&[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1]
&[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1
&[
0xBF06_8001, // s_cmp_eq_u32 s1, 0
0xBF85_0001, // s_cbranch_scc1 -> 0xc
0x7E0A_0280, // v_mov_b32 v5, 0
0x7E02_0305, // 0xc: v_mov_b32 v1, v5
S_ENDPGM,
],
];
let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect();
assert!(accepted.is_empty(), "accepted: {accepted:08X?}");
// Overwriting v5 reads the group input only for lanes outside EXEC:
// v_mov_b32 v5, 0; v_mov_b32 v1, v5.
assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok());
// Skipping that write with s_cbranch_execz is the same case: under the
// same mask, the read sees only the 0.
let reuse = [
0x7E04_0505, // v_readfirstlane_b32 s2, v5
0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
0xBF88_0001, // s_cbranch_execz -> 0x14
0x7E0A_0280, // v_mov_b32 v5, 0
0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7]
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
0xBF88_0001, // s_cbranch_execz -> 0x24
0x7E02_0305, // v_mov_b32 v1, v5
0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7]
S_ENDPGM,
];
assert_eq!(mesh(&reuse).map(|_| ()), Ok(()));
}
#[test]
fn pixel_vgprs_follow_the_input_address() {
// Linear center (bit 5), then position x and y (bits 8, 9).
let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9);
assert_eq!(
v,
[
(
0,
Input::Barycentric {
kind: Barycentric::LinearCenter,
index: 0
}
),
(
1,
Input::Barycentric {
kind: Barycentric::LinearCenter,
index: 1
}
),
(2, Input::Position(0)),
(3, Input::Position(1)),
]
);
}
}
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
//! Xbox Series shaders to host shaders.
//!
//! An Xbox Series shader is a standard DXBC container ([`dxbc`]). Its `DXIL`
//! part ([`dxil`]) may carry Xbox additions around the LLVM bitcode: an
//! `XDAT` table before it indexing blobs after it, among them `xbop`
//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use
//! console-only intrinsics, so the GFX10 code is translated in general.
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod bvh;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod dxbc;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod dxil;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod emit;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod gfx10;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod io;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod ir;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod native;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod resource;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod spill;
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
pub mod structure;
pub use dxbc::{Container, FourCC, Part};
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
pub use native::{
HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, native_programs,
};
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ShaderError {
#[error("not a DXBC container")]
NotDxbc,
#[error("malformed shader: {0}")]
Malformed(&'static str),
#[error("GFX10 code at {offset:#x}: {reason}")]
Isa { offset: usize, reason: &'static str },
/// Valid code the translator cannot handle yet: an opcode name or a construct.
#[error("GFX10 code at {offset:#x}: {what} is not supported")]
Unsupported { offset: usize, what: &'static str },
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+380
View File
@@ -0,0 +1,380 @@
//! The spilled user-data table of a compute program.
//!
//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A
//! root signature that needs more dwords than that keeps none of its
//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit
//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and
//! the parameter the layout declares at user-data index N (16 or above) is
//! at byte `4 * (N - 16)` of that table. The code reads it with
//! `s_load_dword*` through that pointer. (Every compute program of the
//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this
//! kind; measured there: 118 of 118 such loads land on a declared parameter.)
//!
//! [`user_data`] rewrites those loads away: each dword they read becomes the
//! entry value of the SGPR its user-data index names, as if the parameter
//! had arrived in a register. Resource tracking and lowering then treat a
//! spilled parameter like any other (the host binds user data by root slot
//! and dword, not by register).
use crate::ShaderError;
use crate::gfx10::{Fields, NULL, Operand};
use crate::ir::{self, Program, Reg, Value};
use crate::native::{HwStage, NativeProgram, StageIo};
/// The user-data index of the table's first dword.
const FIRST: u32 = 16;
/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads
/// of a spilled user-data table rewritten ([`user_data`]).
pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> {
let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
user_data(&mut p, native);
Ok(p)
}
/// Whether `native` is a compute program that keeps its root parameters in
/// a spilled user-data table (see the module): the entries no register
/// holds, as (first user-data index, dwords), if the table starts at index
/// 16 and the program has the two registers of its address.
fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> {
let StageIo::Cs(cs) = &native.io else {
return None;
};
if native.stage != HwStage::Cs {
return None;
}
let registers = u32::from(cs.user_sgprs());
let spilled: Vec<(u32, u32)> = native
.layout
.iter()
.filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers)
.map(|e| (u32::from(e.user_data), e.sgprs))
.collect();
// Only the one arrangement seen: the table starts at index 16.
(spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled)
}
/// Whether `native` reads its root parameters from a spilled user-data
/// table. (In the title exactly the compute programs of the
/// console's ray-tracing structure builder do.)
pub fn is_spilled(native: &NativeProgram) -> bool {
spilled(native).is_some()
}
/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns
/// how many loads it replaced. Nothing changes unless the program is a
/// compute program whose layout has entries past its user SGPRs, the first
/// at index 16. A load is left alone (and resource tracking then refuses it
/// as before) when its offset is not a constant on a dword, or when a dword
/// it reads and the program uses is in no layout entry.
pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize {
let Some(spilled) = spilled(native) else {
return 0;
};
let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1);
let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else {
return 0;
};
// The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies.
let mut lows = vec![low];
let mut highs: Vec<Value> = Vec::new();
let mut raw_highs = vec![high];
// Instructions that only form the pointer: dropped when nothing reads
// them any more.
let mut forming: Vec<(usize, usize)> = Vec::new();
loop {
let mut changed = false;
for (b, block) in p.blocks.iter().enumerate() {
for (i, inst) in block.insts.iter().enumerate() {
let Fields::Sop { dst, src, .. } = &inst.fields else {
continue;
};
let Some(Operand::Scalar { code: d, .. }) = *dst else {
continue;
};
let Some(out) = inst.write(Reg::S(d)) else {
continue;
};
let read = |op: &Operand| match *op {
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
_ => None,
};
let found = match (inst.name(), &src[..]) {
("s_mov_b32", [s]) => match read(s) {
Some(v) if lows.contains(&v) => Some(&mut lows),
Some(v) if highs.contains(&v) => Some(&mut highs),
Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs),
_ => None,
},
("s_and_b32", [x, y]) => {
let masked = |a: &Operand, m: &Operand| {
matches!(*m, Operand::Literal(0xff))
&& read(a).is_some_and(|v| raw_highs.contains(&v))
};
(masked(x, y) || masked(y, x)).then_some(&mut highs)
}
_ => None,
};
if let Some(set) = found
&& !set.contains(&out)
{
set.push(out);
forming.push((b, i));
changed = true;
}
}
}
if !changed {
break;
}
}
if highs.is_empty() {
return 0;
}
// Values some instruction or phi reads.
let mut read_somewhere = std::collections::HashSet::new();
for block in &p.blocks {
read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
}
let mut next = p
.inputs
.iter()
.map(|i| i.1)
.chain(p.blocks.iter().flat_map(|b| {
b.phis
.iter()
.map(|phi| phi.value)
.chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
}))
.map(|v| v.0 + 1)
.max()
.unwrap_or(0);
// Each load through the pointer: its dwords become entry values.
let mut replaced: std::collections::HashMap<Value, Value> = Default::default();
let mut gone: Vec<(usize, usize)> = Vec::new();
let mut inputs = p.inputs.clone();
for (b, block) in p.blocks.iter().enumerate() {
'insts: for (i, inst) in block.insts.iter().enumerate() {
let Fields::Smem {
data: Some(Operand::Scalar { code: first, .. }),
base: Operand::Scalar { code: base, .. },
offset,
soffset,
..
} = inst.fields
else {
continue;
};
if !inst.name().starts_with("s_load_dword")
|| !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128))
|| offset < 0
|| offset % 4 != 0
|| !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v))
|| !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v))
{
continue;
}
let mut dwords = Vec::new();
for &(reg, v) in &inst.writes {
let Reg::S(code) = reg else {
continue 'insts;
};
let Some(k) = code.checked_sub(first) else {
continue 'insts;
};
let index = FIRST + offset as u32 / 4 + u32::from(k);
let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n);
if !declared {
if read_somewhere.contains(&v) {
continue 'insts;
}
continue;
}
// SGPR codes end at 105; no root signature reaches there.
let Ok(code) = u8::try_from(index) else {
continue 'insts;
};
if code > 105 {
continue 'insts;
}
dwords.push((Reg::S(code), v));
}
for (reg, v) in dwords {
let value = match inputs.iter().find(|e| e.0 == reg) {
Some(e) => e.1,
None => {
let value = Value(next);
next += 1;
inputs.push((reg, value));
value
}
};
replaced.insert(v, value);
}
gone.push((b, i));
}
}
if gone.is_empty() {
return 0;
}
p.inputs = inputs;
let renamed = |v: &mut Value| {
if let Some(&to) = replaced.get(v) {
*v = to;
}
};
for block in &mut p.blocks {
for phi in &mut block.phis {
phi.args.iter_mut().for_each(renamed);
}
for inst in &mut block.insts {
inst.reads.iter_mut().for_each(|r| renamed(&mut r.1));
}
}
// The loads go, then what only formed the pointer (last first, so a
// copy goes before what it copied).
let mut drop = gone.clone();
loop {
let read_somewhere = {
let mut used = std::collections::HashSet::new();
for (b, block) in p.blocks.iter().enumerate() {
used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
for (i, inst) in block.insts.iter().enumerate() {
if !drop.contains(&(b, i)) {
used.extend(inst.reads.iter().map(|r| r.1));
}
}
}
used
};
let before = drop.len();
for &site in &forming {
let inst = &p.blocks[site.0].insts[site.1];
if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) {
drop.push(site);
}
}
if drop.len() == before {
break;
}
}
for (b, block) in p.blocks.iter_mut().enumerate() {
let mut i = 0;
block.insts.retain(|_| {
i += 1;
!drop.contains(&(b, i - 1))
});
}
// The pointer's registers are no inputs once nothing reads them.
let mut read = std::collections::HashSet::new();
for block in &p.blocks {
read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
}
p.inputs
.retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v));
gone.len()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::native::{ComputeIo, RootParam, RootType};
fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam {
RootParam {
root,
table_offset_dwords: 0,
sgprs,
base_register: 0,
user_data,
slot,
}
}
/// A compute program with `registers` user SGPRs and the group id after
/// them.
fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram {
NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 256,
layout,
used: vec![],
io: StageIo::Cs(ComputeIo {
rsrc2: registers << 1 | 1 << 7,
threads: [1, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
}
}
// s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3],
// 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm.
const TABLE: [u32; 8] = [
0x8703_FF01,
0x0000_00FF,
0xBE82_0300,
0xF400_0141,
0xFA00_0010,
0xF404_0001,
0xFA00_0000,
0xBF81_0000,
];
#[test]
fn loads_of_the_spilled_table_become_entry_registers() {
let n = native(
&TABLE,
4,
vec![
param(RootType::Descriptor, 16, 2, 0),
param(RootType::Descriptor, 18, 2, 1),
param(RootType::Constants, 20, 16, 2),
],
);
let mut p = ir::build(&n.code, false, 256).unwrap();
assert_eq!(user_data(&mut p, &n), 2);
let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect();
assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}");
// The pointer is gone with the loads; byte 0x10 is index 20, the
// first root constant, and bytes 0-7 are the first root view.
let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect();
regs.sort();
assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]);
}
#[test]
fn parameters_in_registers_are_left_alone() {
// The same code where s0 and s1 are a root view the layout declares.
let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]);
let mut p = ir::build(&n.code, false, 256).unwrap();
let before = p.clone();
assert_eq!(user_data(&mut p, &n), 0);
assert_eq!(p, before);
}
#[test]
fn a_used_dword_no_parameter_declares_keeps_its_load() {
// As above with `s_mov_b32 s6, s5` before the end: the dword at
// byte 0x10 (index 20) is read, and here nothing declares it.
let mut words = TABLE.to_vec();
words.insert(7, 0xBE86_0305);
let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]);
let mut p = ir::build(&n.code, false, 256).unwrap();
assert_eq!(user_data(&mut p, &n), 1);
let loads = p
.blocks
.iter()
.flat_map(|b| &b.insts)
.filter(|i| i.name().starts_with("s_load_"))
.count();
assert_eq!(loads, 1);
// The pointer is still read, by the load that stays.
assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0)));
}
}
File diff suppressed because it is too large. Load diff
+21 -4
View File
@@ -8,9 +8,16 @@ then read the [interface contracts](interfaces.md). Reproduce an
[independent validation suite](../tests/validation/README.md) before changing
either path. The [changelog](../CHANGELOG.md) records notable changes.
Use the [BetterXen development phases](development-phases.md) for current work
order, existing issue/PR dependencies and measurable completion criteria.
Historical phase checkpoints retain their original evidence scope.
Use the [roadmap](roadmap.md) for the active CrossOver-based hybrid plan, phases,
critical path and completion criteria; see [ADR 0005](adr/0005-crossover-hybrid-direction.md)
for the decision and [project board setup](planning/project-board.md). Native work is
paused: [deferred native roadmap](research/native-roadmap.md) and the archived
[native-first plan](archive/development-phases-native-first.md) with
[retired milestones](archive/native-first-milestones.json), the
[native issue archive](research/native-issue-archive.md) and the retired
[H0 to H7 breakdown](archive/hybrid-phases-h0-h7.md). Research inputs: the [upstream research registry](research/upstream-registry.md) and
[component reuse matrix](research/component-reuse-matrix.md). Historical phase
checkpoints retain their original evidence scope.
## Architecture and technical design
@@ -38,6 +45,7 @@ Historical phase checkpoints retain their original evidence scope.
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
- [Proposed AVX and AVX2 guest contract](cpu/avx-contract.md) — VEX decoding, vector state, fault behavior and an original integer fixture specification.
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
- [Guest threads](runtime/threads.md) — Deterministic scheduler, thread services, limits and tests.
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
@@ -45,10 +53,11 @@ Historical phase checkpoints retain their original evidence scope.
## Testing, validation, and benchmarks
- [Migrated pull-request integration review](testing/migration-pr-review.md) — Merge decisions, integration fixes, native verification and excluded concurrent work.
- [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.
- [CPU test runtime and shard selection](testing/cpu-coverage.md) — Measured CPU gate cost and deterministic test-target shards.
- [CPU test runtime, shards and coverage map](testing/cpu-coverage.md) — Measured CPU gate cost, deterministic test-target shards, and a verified per-operation CPU/loader coverage map with exact test evidence.
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
@@ -59,7 +68,15 @@ Historical phase checkpoints retain their original evidence scope.
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
- [Upstream integration audit](research/upstream-integration-audit.md) — Source-level review of external macOS compatibility projects, licence and provenance decisions, and what was implemented in `crates/hybrid`.
- [victory-shader integration](research/victory-shader-integration.md) — The vendored GFX10-to-DXIL recompiler, how BetterXen's fixtures run through it on the GPU under CrossOver, and what is not verified.
- [CrossOver baseline](research/crossover-baseline-2026-11-25.md) — First executions of original workloads under CrossOver 26.3 on the M4, backend comparison and its limits.
- [Windows cross-toolchain](research/hybrid-toolchain.md) — Pinned llvm-mingw release, how original Windows workloads are built, and what was and was not executed.
- [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups.
- [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only.
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
- [Hybrid backlog research record](research/hybrid-backlog-research-2026-11-25.md) — Findings, registry candidates and the issues they produced (2026-11-25); not verified on hardware.
- [Primary-source verification](research/primary-source-verification-2026-11-25.md) — Which hybrid-research claims were confirmed, contradicted or left unverified against vendor documentation.
## Security, licensing, and contributions
@@ -0,0 +1,41 @@
# ADR 0005: CrossOver-based hybrid direction
Status: **Accepted (strategic direction).** Accepted by the maintainers' planning directive of 2026-11-25. The proposed technical architecture below is **not** accepted or verified; each integration still needs validation.
## Context
BetterXen was developed native-first: an independent x86-64 decoder, interpreter, ARM64 translator, runtime, shader compiler and Metal backend, verified only on synthetic programs and shaders. No Xbox title runs on it. The maintainers decided to focus all active engineering on a hybrid architecture and to pause native work.
## Accepted strategic direction
- CrossOver is the primary compatibility foundation, installed externally.
- Hybrid is the only active development direction. Native research is preserved (tag `native-first-final` marks the last `main` commit before this change; the code stays in the workspace) and paused; resuming needs an explicit maintainer decision.
- Reuse established infrastructure; build independent replacements only for demonstrated limitations.
- The engineering rules in `AGENTS.md` (and `CLAUDE.md`, a symlink) were rewritten accordingly, replacing the former prohibition on Wine, CrossOver, Rosetta and MoltenVK.
## Proposed technical architecture (not accepted)
BetterXen provides integration, configuration, environment management, diagnostics, reproducible testing, benchmarking and measured optimization around CrossOver. Within CrossOver, the intended layers are Wine-based runtime APIs, Rosetta 2 for x86-64 translation and D3DMetal or DXMT for graphics, on Apple Silicon (ARM64, Metal, unified memory). The exact responsibility boundary is decided in #351, at the end of Phase 1.
## Unverified integration assumptions
- That CrossOver, Rosetta 2, D3DMetal or DXMT run any authorized workload BetterXen needs. Assumed not until measured (#355).
- That CrossOver offers supported interfaces for bottle management, configuration, launching and diagnostics (#350).
- Rosetta 2's support lifetime and D3DMetal's license terms (#349, #354).
- That any of this provides Xbox runtime compatibility. It is assumed not to.
## Verified implementation capabilities
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
## Planning consequence
Planning is progressive: Phase 1 (research, feasibility and baseline) is the only active phase; later phases are provisional and defined from its findings. Native work is paused indefinitely.
## Consequences
Positive: reuse of mature infrastructure. Negative: dependence on a proprietary vendor and on Rosetta 2 availability; limited ability to modify closed components; the former "No Wine, No CrossOver, No Rosetta" project identity is retired for active work. Anything derived from leaked or unauthorized material stays excluded, including projects built for such inputs (see the upstream registry).
## Alternatives considered
Continue native-first; maintain both tracks at 75/25; a generic Wine-based stack without CrossOver.
@@ -1,3 +1,5 @@
> **Archived 2026-11-25 (superseded). Not the active plan.** Native-first plan retained for history; the active roadmap is [../roadmap.md](../roadmap.md). Relative links below were written for `docs/` and may need `../`.
# BetterXen development phases
This is BetterXen's working development plan. Each phase ends with a reproducible
@@ -26,10 +28,10 @@ Historical results below remain evidence for their recorded candidates only.
| Native app | Swift app, Rust C interface, controller input and audio/virtual-filesystem fixtures | Existing fixtures do not establish one integrated threaded C++ 3D application. |
| Quality tools | CPU/runtime inventories, shader coverage reconciliation, task queue, PR checks and acceptance records | Some inventories and ledgers contain stale limitation text. A successful tool invocation does not prove every catalog entry is current. |
Sources: [CPU registry](cpu/instruction-registry.md),
[runtime registry](runtime/registry.md), [guest threads](runtime/threads.md),
[interfaces](interfaces.md), [shader coverage](shaders/semantic-coverage.md),
[Gate A](testing/gate-a.md), and [QA tooling](testing/infrastructure/README.md).
Sources: [CPU registry](../cpu/instruction-registry.md),
[runtime registry](../runtime/registry.md), [guest threads](../runtime/threads.md),
[interfaces](../interfaces.md), [shader coverage](../shaders/semantic-coverage.md),
[Gate A](../testing/gate-a.md), and [QA tooling](../testing/infrastructure/README.md).
The read-only shader reconciliation reported zero mismatches during this task;
that result is inventory consistency, not new GPU verification.
@@ -40,18 +42,18 @@ but their phase numbers are not the sequence for new BetterXen work.
| Existing record or name | Meaning | How to use it now |
| --- | --- | --- |
| [Phase 01 checkpoints and assurance](testing/phase01-assurance.md), [risk register](risk-register.md), [review log](testing/review-log.md) and [mutation record](testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. |
| [Phase 02 GPU/guest baseline](testing/phase-02-baseline.md) and [CPU feasibility](research/phase02-cpu-feasibility.md), [ecosystem](research/phase02-ecosystem.md), [collaboration](research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. |
| [CPU/runtime campaign ledger](coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. |
| [Infrastructure Phase II/III tooling](testing/infrastructure/README.md) and [compatibility ledger](testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. |
| [Gate A](testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. |
| [Phase 01 checkpoints and assurance](../testing/phase01-assurance.md), [risk register](../risk-register.md), [review log](../testing/review-log.md) and [mutation record](../testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. |
| [Phase 02 GPU/guest baseline](../testing/phase-02-baseline.md) and [CPU feasibility](../research/phase02-cpu-feasibility.md), [ecosystem](../research/phase02-ecosystem.md), [collaboration](../research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. |
| [CPU/runtime campaign ledger](../coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. |
| [Infrastructure Phase II/III tooling](../testing/infrastructure/README.md) and [compatibility ledger](../testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. |
| [Gate A](../testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. |
| Native app numbered gates in `crates/ffi` and `app` | Bounded session, graphics, audio and filesystem fixtures | Inspect their tests before proposing integration. Gate numbers are separate from shader acceptance gates. |
| README X1–X25 milestones | Broad capability map | Retain as a capability reference; use the phases below for the next work order. |
| Supplied Discord III, III-B, IV, V and VI excerpts | Broad runtime, graphics, application and performance objectives | Only excerpts were supplied. Their omitted requirements and completion status are unknown; they are not execution instructions. |
Bare issue numbers in historical documents may refer to the source repository.
All issue and PR links in the work sections below refer to **MacosPorters/betterxen**.
Use [migration records](migration.md) to resolve historical references.
Use [migration records](../migration.md) to resolve historical references.
## Phase 1 — Establish a trustworthy working baseline
+150
View File
@@ -0,0 +1,150 @@
# Detailed hybrid phases H0 to H7 (retired planning)
**Archived 2026-11-25; not the active plan.** These eight phases were defined before any research had been done. The active roadmap is [../roadmap.md](../roadmap.md): five provisional phases, with only Phase 1 active. The text below preserves the objectives, scope and exit conditions of the retired H2 to H7 milestones (and H0/H1) for reference when later phases are defined. Issue numbers in it are historical.
## Phases as originally written
### H0 — CrossOver Architecture Transition
**Status:** In development
**Objective:** Make CrossOver the single authoritative active compatibility foundation across the repository and GitHub planning surfaces.
**Scope:** README, architecture docs, ADR 0005, rewritten engineering rules, roadmap, upstream research registry, technical plans, labels, milestones, issue and PR templates, issue triage, project board, preservation of the native implementation.
**Dependencies:** None.
**Deliverables:** Updated README and docs; ADR 0005; docs/roadmap.md; deferred docs/research/native-roadmap.md; rebuilt issues and milestones; project board; preserved native code.
**Validation:** Repository link/terminology check; GitHub consistency check.
**Exit conditions:** Repository, documentation, issues, milestones and board consistently state the CrossOver-based direction. The project board requires a token with the project scope and is not yet configured.
**Known risks:** Project board cannot be configured without the GitHub project token scope (#346). The engineering rules conflict was resolved by rewriting AGENTS.md (#345).
### H1 — CrossOver Research and Baseline
**Status:** Not started
**Objective:** Establish what the installed CrossOver version actually provides and a reproducible baseline, without assuming it provides Xbox runtime compatibility.
**Scope:** CrossOver architecture, supported macOS versions, Apple Silicon support, relationship to upstream Wine, CPU translation mechanism, graphics backends (D3DMetal, DXMT and others), supported Direct3D versions, configuration interfaces, documented command-line interfaces, bottle management, diagnostics and profiling options, licensing and redistribution, supported integration mechanisms, long-term maintenance. Open-source and proprietary components distinguished.
**Dependencies:** Engineering rules rewritten (#345, done). CrossOver is an externally installed dependency until its license says otherwise; nothing is bundled.
**Deliverables:** CrossOver capability and integration-boundary report; licensing and dependency assessment; reproducible environment; baselines of CPU, GPU, memory and stability on authorized workloads.
**Validation:** Every claim cites vendor or upstream documentation, or a recorded observation on the installed version. Unknown stays unknown. Equivalent workloads, settings, hardware and software versions.
**Exit conditions:** Capabilities and integration boundaries are documented for the installed version; environment is reproducible by another contributor; baselines recorded; BetterXen vs CrossOver responsibilities proposed.
**Known risks:** CrossOver is proprietary: bundling, modifying or redistributing may be prohibited; integration interfaces may be undocumented; Xbox titles may not run at all.
### H2 — BetterXen Integration Foundation
**Status:** Not started
**Objective:** Build the BetterXen layer around CrossOver: integration boundaries, configuration, diagnostics, reproducible test workflows and host integration.
**Scope:** Environment and configuration management, diagnostics, test workflows, verified host integration, regression testing. Only what CrossOver does not already provide adequately.
**Dependencies:** H1.
**Deliverables:** Boundary document; configuration and environment management where justified; diagnostic infrastructure; reproducible test workflows; verified host integration; regression tests.
**Validation:** Independent contributor reproduces the workflows; no placeholder components.
**Exit conditions:** Integration foundation builds, tests and reproduces on a second setup.
**Known risks:** Reliance on undocumented or changing CrossOver behavior.
### H3 — Compatibility Validation
**Status:** Not started
**Objective:** Evaluate authorized workloads and document verified behavior and limitations.
**Scope:** Authorized workloads, documented limitations, runtime behavior, graphics correctness, input and interaction, reproducible failures, integrated validation criteria.
**Dependencies:** H2.
**Deliverables:** Validation criteria; per-workload results; reproducible failure reports; verified runtime, graphics and input results.
**Validation:** Independent verification of rendering and behavior. Startup or a screenshot alone is not proof.
**Exit conditions:** Selected workloads show verified integrated behavior under documented criteria; failures reproducible.
**Known risks:** Failures may originate in CrossOver or its components outside project control.
### H4 — Graphics and Performance Engineering
**Status:** Not started
**Objective:** Evaluate graphics backends and optimize only demonstrated bottlenecks.
**Scope:** Supported backends, CPU/GPU utilization, unified memory, frame-time consistency, synchronization, shader compilation and caching. Metrics: average FPS, 1% low, frame-time percentiles, CPU and GPU utilization, unified memory, memory pressure, translation overhead where measurable, shader compile latency, startup, thermals, long-duration stability. Reference machine: M4 Mac, 24 GB.
**Dependencies:** H3; measurement protocol.
**Deliverables:** Backend comparison; profiling reports; bottleneck list; before/after results; regression tests.
**Validation:** Equivalent workloads, rendering settings, hardware and versions; correctness and rendering equivalence verified.
**Exit conditions:** Improvements measurable, reproducible and without loss of correctness or stability. No improvement is promised before measurement.
**Known risks:** Many components are closed and not modifiable; single reference machine.
### H5 — Stability and Hardware Scaling
**Status:** Not started
**Objective:** Evaluate Apple Silicon configurations, memory pressure, thermals and long-duration stability.
**Scope:** Available Apple Silicon configurations, memory pressure, thermal behavior, long-duration tests, hardware documentation, regression coverage.
**Dependencies:** H3; hardware access.
**Deliverables:** Hardware compatibility documentation; memory-pressure and thermal reports; long-duration results; expanded regression coverage.
**Validation:** Each documented configuration backed by a test run on it.
**Exit conditions:** Tested configurations documented; untested hardware never claimed.
**Known risks:** Only one reference machine currently available.
### H6 — Hybrid Architecture Maturity
**Status:** Not started
**Objective:** Maintainable integration infrastructure and contributor workflows.
**Scope:** Contributor workflows, verified-capability documentation, reproducible performance results, complexity reduction, long-term dependency risk (CrossOver, Rosetta 2, D3DMetal).
**Dependencies:** H3 to H5 evidence.
**Deliverables:** Maintainable infrastructure; contributor documentation; verified capability list; reproducible results; dependency risk assessment.
**Validation:** Contributors other than the authors maintain the workflow.
**Exit conditions:** The architecture shows demonstrated value and the team can maintain it.
**Known risks:** Vendor decisions (CrossOver licensing, Rosetta lifetime) are outside project control.
### H7 — Future Native Reassessment (deferred)
**Status:** Not started
**Objective:** Deferred. Reassess independent native components only on an explicit maintainer decision or when one offers a demonstrated benefit to the active architecture.
**Scope:** See docs/research/native-roadmap.md.
**Dependencies:** Explicit maintainer decision.
**Deliverables:** Reassessment record.
**Validation:** Maintainer decision recorded in an ADR.
**Exit conditions:** A recorded decision to continue, resume specific native work, or archive components.
**Known risks:** Premature reinvention of mature infrastructure.
@@ -0,0 +1 @@
[{"closed_issues":15,"description":"G1–G15 for the bounded native ARM64 and Metal graphics foundation. Release acceptance requires all gates on the exact candidate.","html_url":"https://github.com/MacosPorters/betterxen/milestone/1","number":1,"open_issues":0,"state":"open","title":"Phase 01 - Native Graphics Foundation"},{"closed_issues":7,"description":"Develop independently authored interoperability tests and fixtures from public specifications. External emulator results may inform test selection. Xenora owns its Rust ARM64 runtime, decoder, typed IR, shader compiler and Metal backend. Emulator code, ports, decoder tables, internal metadata and platform-specific dependencies are outside scope.","html_url":"https://github.com/MacosPorters/betterxen/milestone/2","number":2,"open_issues":0,"state":"open","title":"Phase 02 - Ecosystem Integration"},{"closed_issues":8,"description":"Expand independently verified gfx1030 semantics, resource access, wave behavior and native offscreen drawing.\n\n### Deferred engineering\n- [#25](https://github.com/ranveersoni98/Xenora/issues/25) · Verify Wave64 pairing on native Metal. Exercise both halves, cross-half operations, asymmetric masks and barrier safety with 64-lane readback.\n- [#27](https://github.com/ranveersoni98/Xenora/issues/27) · Translate bounded vertex and fragment fixtures. Define stage IO and interpolation from public specifications; verify exact offscreen pixels.","html_url":"https://github.com/MacosPorters/betterxen/milestone/3","number":3,"open_issues":0,"state":"open","title":"Phase 03 - Graphics Maturation"},{"closed_issues":6,"description":"Measure correctness-gated CPU, translation and GPU behavior under reproducible host conditions. Track capability and failure evidence.\n\n### Deferred engineering\n- [#33](https://github.com/ranveersoni98/Xenora/issues/33) · Measure Metal pipeline reuse and cache identity. Separate cold and warm timing; test cache invalidation and verify shared output expectations.","html_url":"https://github.com/MacosPorters/betterxen/milestone/4","number":4,"open_issues":0,"state":"open","title":"Phase 04 - Performance and Compatibility"},{"closed_issues":7,"description":"Grow the bounded interpreter and independently demonstrate ARM64 recompilation, with precise state and fault behavior.\n\n### Deferred engineering\n- [#40](https://github.com/ranveersoni98/Xenora/issues/40) · Choose first measured recompilation target. Use interpreter profiles to choose one bounded basic block and document precise state and fault requirements.\n- [#41](https://github.com/ranveersoni98/Xenora/issues/41) · Execute one translated ARM64 guest basic block. Execute emitted ARM64 code natively, compare registers, flags, memory and traps with interpreter and independent vectors.\n- [#42](https://github.com/ranveersoni98/Xenora/issues/42) · Verify code cache and executable memory policy. Validate mapping permissions, publication, invalidation and dependency provenance on macOS.\n- [#43](https://github.com/ranveersoni98/Xenora/issues/43) · Measure ARM64 translation performance. Compare correctness-gated translated and interpreted inputs with matched native runs and resource records.","html_url":"https://github.com/MacosPorters/betterxen/milestone/5","number":5,"open_issues":0,"state":"open","title":"Phase 05 - CPU Recompilation"},{"closed_issues":6,"description":"Build isolated guest loading, memory, services and checked CPU-to-GPU commands using original inputs.\n\n### Deferred engineering\n- [#49](https://github.com/ranveersoni98/Xenora/issues/49) · Expand synthetic services and authorized runtime boundaries. Define explicit service ABI, faults and lifetimes with original inputs. Document evidence gaps for authentic Xbox platform contracts.\n\nFuture import behavior is tracked in [#55](https://github.com/ranveersoni98/Xenora/issues/55). Compatibility checks do not inspect user acquisition or ownership.","html_url":"https://github.com/MacosPorters/betterxen/milestone/6","number":6,"open_issues":0,"state":"open","title":"Phase 06 - Runtime Infrastructure"},{"closed_issues":5,"description":"Validate the integrated execution path and exact release candidate. Project-run title testing requires suitable inputs and independent evidence. The loader evaluates format and compatibility without checking where user files came from.","html_url":"https://github.com/MacosPorters/betterxen/milestone/7","number":7,"open_issues":1,"state":"open","title":"Phase 07 - Integrated Validation"}]
+70
View File
@@ -0,0 +1,70 @@
# Native-first README milestones (archived)
**Archived 2026-11-25; paused native research, not the active plan.** This section was the README's "Milestones" content on `main` when BetterXen moved to the CrossOver-based hybrid direction. Statuses describe the native implementation only, with synthetic evidence. The active plan is the [roadmap](../roadmap.md). Links below were written for the repository root README and may need adjusting.
## Native-first milestones
BetterXen's work order is the six [development phases](development-phases-native-first.md), which lead to one concrete target: the **first launchable application** (tracker [#311](https://github.com/MacosPorters/betterxen/issues/311)). That target is an original C program, built with native ARM64 tools, that runs through the ARM64 translator, controls its own translated shader pipeline, and shows its Metal frame in the native app window. It is **not** a commercial or authentic Xbox title, and no date or percentage is attached to it.
```mermaid
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
flowchart LR
P1["<b>Phase 1</b><br/>Trustworthy baseline"]:::wip --> P2["<b>Phase 2</b><br/>Hosted C application"]:::wip
P2 --> P3["<b>Phase 3</b><br/>Coherent threading"]:::wip
P3 --> P4["<b>Phase 4</b><br/>Resource updates<br/>to translated rendering"]:::wip
P4 --> P5["<b>Phase 5</b><br/>One integrated<br/>interactive application"]:::plan
P5 --> P6["<b>Phase 6</b><br/>Measured performance"]:::plan
P2 --> L(["<b>First launchable app</b><br/>issue 311"]):::goal
P4 --> L
classDef wip fill:#fff8c5,stroke:#9a6700,color:#4d2d00
classDef plan fill:#eaeef2,stroke:#8c959f,color:#24292f
classDef goal fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:3px
```
<sub>🟨 work under way · ⬜ not started · 🟩 the next original-workload target. Nothing here is independently accepted.</sub>
| Phase | Goal | State | What exists now |
| --- | --- | --- | --- |
| **1 · Baseline** | Contributors can tell what exists on `main`, what is pending review, and which checks ran | 🟡 In progress | CODEOWNERS review, a fast repository hygiene check, claim-before-work rules, generated status tables and claim audits |
| **2 · Hosted C application** | An original hosted C program starts, uses the runtime, reports results and exits with checked cleanup | 🟡 In progress | CRT startup, arguments, exit handlers, formatted output, file streams and the hosted-C fixture (A2) are integrated; a stdio follow-up is still open and the result is not independently accepted |
| **3 · Threaded behavior** | A worker-based application can block and resume without stalling other guest work | 🟡 In progress | Deterministic scheduler, guest thread contexts, guarded stacks and thread services. Guest `Sleep` still delays all guest threads (#304); worker TLS and callback lifecycle is a design draft (#312) |
| **4 · Resource updates to rendering** | A guest updates a texture and geometry, submits translated rendering and gets a checked frame | 🟡 In progress | Persistent resources, descriptor-table texture binding, translated vertex and pixel stages, blend, depth and indexed draws. Guest-selected pipelines and the typed graphics bridge are open (#314–#316) |
| **5 · Integrated interactive app** | Guest execution, rendering, input, audio, filesystem and lifecycle in one session | ⚪ Planned | Swift app with frame loop, input, audio and sandboxed filesystem fixtures exists, but those demonstrations are not guest-integration evidence |
| **6 · Measured performance** | Faster execution of workloads whose correctness is already checked | ⚪ Planned | Startup, DBT and TLS measurements recorded; bottlenecks are chosen from measurements, not assumed |
The launch milestone's proposed acceptance is **60 bounded frames containing two independently distinguishable guest-controlled states, then a clean close and one restart**. Sixty is a fixture criterion, not a measured frame rate. The work is tracked as issues [#313](https://github.com/MacosPorters/betterxen/issues/313)–[#323](https://github.com/MacosPorters/betterxen/issues/323).
<details>
<summary><b>Capability reference: the original X1–X25 map</b></summary>
The X1–X25 names are an older, broad capability map. Keep them as a reference; use the phases above for the next work order. X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence.
| Milestone | Implementation | Status |
| --- | --- | --- |
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | One translated `image_sample_lz` pixel stage with point/clamp sampling of RGBA8 and BC1 2D textures bound through descriptor tables, locally verified on Apple M5 Pro; upload, readback and decode of BC compressed formats (see [Texture support](#texture-support)). Other image instructions and formats are not implemented | Implemented subset |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
</details>
+136
View File
@@ -0,0 +1,136 @@
# Proposed AVX and AVX2 guest contract
[Issue #299](https://github.com/MacosPorters/betterxen/issues/299) defines a
reviewable first step for Advanced Vector Extensions (AVX) in the x86-64 guest.
The current [instruction registry](instruction-registry.md) rejects VEX prefixes.
[`CpuState`](../../crates/loader/src/cpu.rs) holds 16 XMM registers and MXCSR,
the SIMD floating-point control and status register. The synthetic `CPUID`
advertises basic leaves through 1 and reports no AVX or extended-state support.
The architectural expectations come from the public Intel Software Developer's
Manual and apply to BetterXen's synthetic x86-64 guest profile. Which AVX and
AVX2 features Xbox Series X|S CPUs expose, and which extended register state
the console OS enables for applications, remain open research questions.
Resolving them requires public platform documentation or authorized hardware
evidence.
## Architectural state and encoding
In 64-bit mode, XMM0–XMM15 alias bits 127:0 of YMM0–YMM15. A legacy SSE
instruction that writes an XMM destination preserves bits 255:128. For the
packed VEX.128 forms in this proposal, writing an XMM destination clears that
register's upper 128 bits. A VEX.256 register destination replaces all 256 bits.
A store to memory leaves its source vector register intact. The proposed moves
and integer add leave RFLAGS and MXCSR unchanged. [Intel SDM Vol. 1, §14.8,
Accessing YMM Registers][sdm-ymm]. [Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
The shared [decoder](../../crates/loader/src/x86_decode.rs) should retain the
prefix family, opcode map, mandatory prefix, operand width and register
extensions until it selects the form. In 64-bit mode the VEX lead byte
identifies the prefix length. The table lists each payload byte's fields
from bit 7 to bit 0.
| Lead byte | Payload byte 1 | Payload byte 2 | Implied fields |
| --- | --- | --- | --- |
| `C5` | `~R ~vvvv L pp` | — | Map `0F`, `W=0`, logical `X=B=0` |
| `C4` | `~R ~X ~B mmmmm` | `W ~vvvv L pp` | Map selected by `mmmmm` |
The tilde indicates an inverted encoding. `R` extends ModRM.reg, while `X`
and `B` extend the applicable index and r/m or base fields. `vvvv` supplies
the first source of `VPADDD`. For `VMOVDQU` its encoded bits must be `1111b`.
`L=0` selects 128 bits and `L=1` selects 256 bits for these forms. The three
standard VEX maps are `00001b` (`0F`), `00010b` (`0F 38`) and `00011b`
(`0F 3A`). `pp` values 0 through 3 represent no mandatory prefix, `66`, `F3`
and `F2`. Both initial opcodes are in `0F`, with `W` ignored (`WIG`). Decode
both valid prefix lengths for them. Reject reserved maps and encodings,
including a physical `LOCK`, `66`, `F2`, `F3` or REX prefix before VEX, through
the existing illegal-instruction path. Legal forms outside the implemented
subset also stop explicitly. Keep the existing register and effective-address
rules and 15-byte fetch limit. [Intel SDM Vol. 2A, §2.3, VEX encoding][sdm-2a].
[Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
## First implementation increments
1. Append one upper 128-bit half per vector register to `CpuState`, retaining
the existing XMM storage as the low halves. Add layout assertions for the
offsets the dynamic binary translator (DBT) uses. Initialize both halves
in a fresh guest thread and carry them with the thread state when switching
or resuming. Add the shared VEX decoder and encoding controls before execution.
2. Implement `VMOVDQU` (128 and 256 bits, `F3.0F`, `6F /r` and `7F /r`,
register and checked memory forms) and `VPADDD` (128 and 256 bits,
`66.0F`, `FE /r`, register sources initially). The instruction entries
assign both move widths and 128-bit `VPADDD` to AVX, and 256-bit `VPADDD`
to AVX2. Read all sources before publishing the destination, including
when the destination aliases a source. Compare both engines with the
[original fixture specification](../../tests/compat_fixtures/avx/README.md).
3. After shared semantics pass, lower register moves and `VPADDD` to native
ARM64 vector operations on one or two 128-bit halves. Each `VPADDD` half
is four independent 32-bit additions modulo 2³². Use the checked-memory
helper for loads and stores. Check the DBT's fallback counter so a run
through that helper establishes only helper coverage for those forms.
Stage memory-source `VPADDD` and aligned moves separately. Reject masked
moves, gathers, cross-half permutations, floating-point forms, FMA, EVEX
and guest extended-state instructions in the initial slice. AMD64 bytes
remain guest data. All host execution uses native ARM64 code or checked
Rust helpers.
## Memory, faults and instruction budget
`VMOVDQU` permits unaligned operands. Check the complete 16- or 32-byte
guest span before publishing a load result or writing a store. A split
span across adjacent permitted mappings succeeds. A missing or protected
mapping produces the existing guest memory fault at the first inaccessible
byte. For a later `VMOVDQA` form, a memory operand must be aligned to its
width (16 or 32 bytes), with a misaligned operand raising
`GeneralProtection`. [Intel SDM Vol. 2B, MOVDQU and MOVDQA][sdm-2b].
Intel's Type 4 rules for `VMOVDQU` specify `#SS(0)` when a memory reference
through the stack segment (SS) has a noncanonical address and `#GP(0)`
for other noncanonical references. The initial BetterXen profile uses the
[existing 48-bit guest address check](../../crates/loader/src/x86_exec.rs)
and reports `GeneralProtection` for either segment case, including a span
whose first byte is canonical and whose last byte is noncanonical. Check
canonicality before guest memory lookup and before committing the move.
Distinct stack-segment exception reporting remains outside this profile.
[Intel SDM Vol. 2A, Table 2-21, Type 4 exceptions][sdm-2a].
Before adding masked moves, use a separate per-lane access contract. For
`VPMASKMOVD`, only lanes with the high mask bit set may access memory or
report a memory fault. A clear bit zeroes a load lane and leaves a store
lane untouched. A test with lane 4 on an unmapped page must pass with that
lane disabled and fault with it enabled. A full-width span check would
incorrectly reject the disabled case. Specify store commit behavior before
admitting that form. [Intel SDM Vol. 2C, VPMASKMOV][sdm-2c].
Require interpreter and DBT parity for the exit reason, fault address when
reported, RIP, instruction count and complete guest register and memory
state. A rejected move or add has no partial destination update and does
not retire. A successful 256-bit instruction consumes one guest step even
when the DBT emits two halves. With an exhausted budget, stop at the next
guest RIP before decoding or executing that instruction. Check cold and warm
DBT paths and resume in the middle of the same sequence.
## Feature exposure
Run the initial forms only in explicitly enabled synthetic test cases.
Keep normal guest `CPUID` and extended-state behavior at the current baseline.
Before guest-visible AVX support, the guest OS model needs coherent reporting
for `CPUID.1:ECX` bits 26 (XSAVE), 27 (OSXSAVE) and 28 (AVX), and `XGETBV`
with `ECX=0` must report both XMM and YMM state enabled in `XCR0[2:1]`. The
extended-state layout reported by `CPUID.0Dh`, save and restore behavior,
and per-thread ownership must agree. Verify the exception behavior for
disabled state and invalid `XGETBV` selectors before exposing the facility.
AVX2 separately requires `CPUID.(7,0):EBX[5]` and the same OS state. Gate
each advertised feature on its full instruction and state contract,
with probes for enabled and disabled combinations. [Intel SDM Vol. 1,
§14.3, AVX detection][sdm-avx]. [Intel SDM Vol. 1, §14.7.1, AVX2 detection][sdm-avx2].
[Intel SDM Vol. 2A, CPUID][sdm-2a]. [Intel SDM Vol. 2D, XGETBV, XSAVE and XRSTOR][sdm-2d].
[sdm-ymm]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=376
[sdm-avx]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=359
[sdm-avx2]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=375
[sdm-2a]: https://cdrdv2-public.intel.com/929353/253666-093-sdm-vol-2a.pdf
[sdm-2b]: https://cdrdv2-public.intel.com/929354/253667-093-sdm-vol-2b.pdf
[sdm-2c]: https://cdrdv2-public.intel.com/929355/326018-093-sdm-vol-2c.pdf
[sdm-2d]: https://cdrdv2-public.intel.com/929356/334569-093-sdm-vol-2d.pdf
+25
View File
@@ -141,6 +141,31 @@ pages count toward the 256 MiB mapping budget of one image, which is checked
before anything is mapped. `ParsedPe::parse` does not make these checks, so
static inspection of a file is unchanged.
`betterxen run --experimental --pe <trusted-fixture> --startup-report <path>`
writes a versioned JSON summary after the worker stops. The supervisor creates the new report path before launching the worker.
The report is optional and uses the same exact-byte fixture admission, startup
observer and wall deadline as an ordinary run.
Schema version 1 lists the observed stages in order in `stages` and copies
the last valid stage to `last_completed_stage` (null if none). The order is
`parsed`, `mapped`, `relocated`, `imports_bound`, `tls_completed`, `entry`,
`exit`, and `framebuffer`. `entry` records the handoff to guest entry.
`exit` records the fixture halt, and `framebuffer` records verification of its
offscreen readback. The supervisor reports an `outcome` of `verified`,
`stage_failure`, `early_exit`, `timeout`, or `unknown`. It includes the
worker exit code when available, termination detail when applicable, and the
original reported error when available. Errors are capped at 2 KiB of UTF-8
and carry an `error_truncated` flag.
The supervisor reads at most 8 KiB plus one byte from the worker journal.
`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized`,
`unreadable`, or `unwritable`. Worker exit codes 124 and 125 are reserved for
its watchdog and journal I/O errors, respectively. `--startup-journal` is an
internal worker option. Only the valid ordered prefix counts toward progress. A
complete journal may still contain only a partial startup if the worker
stopped between records. These records describe runtime observations from
the trusted fixtures.
`betterxen probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. Without `--report` it writes to `diagnostics/probe`,
where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
+3
View File
@@ -12,6 +12,9 @@ The workspace is GPL-3.0-or-later. The following is the lead's preliminary compa
| bitflags | 2.13.2, `80ce9b545acb0bd42150695fc351889cac1d8eb4` | MIT from MIT OR Apache-2.0 | Runtime transitive dependency |
| AMD RDNA 2 ISA XML | 2026-02-20, schema 1.1.1 | MIT | Source for generated decoder constants |
| LLVM AMDGPU tools | 23.1.6 | Apache-2.0 WITH LLVM-exception | External fixture tool, not linked |
| llvm-mingw | 20261117 (sha256 `98d340bb…446aa`) | Apache-2.0 WITH LLVM-exception, plus component licences in its LICENSE.TXT (mingw-w64 runtime and headers have their own terms; not audited line by line) | External build tool for original Windows test programs, not linked, not distributed |
| victory-shader (vendored) | victory-mac `22b3f8e45a59`, directory snapshot | GPL-3.0 (same as BetterXen's GPL-3.0-or-later); Mesa-derived opcode table MIT | GFX10-to-DXIL shader recompiler; see its UPSTREAM.md |
| thiserror, zlib-rs, windows, windows-sys | 2.0.21, 0.6.8, 0.62.2, 0.61.2 | MIT OR Apache-2.0; Zlib; MIT OR Apache-2.0 | Dependencies of victory-shader; licences from each crate's metadata, not independently audited |
| Xcode and Metal tools | Xcode 27.2 | Apple proprietary terms | External host tools, not distributed |
## Runtime redistribution review
+11
View File
@@ -0,0 +1,11 @@
# Project board setup
Status: **not configured, and not an engineering blocker.** The token used so far lacks the GitHub `project` scope, and GitHub's API cannot create views. Tracked by [#346](https://github.com/MacosPorters/betterxen/issues/346).
One simple board for active work only:
1. `gh auth refresh -s project`, then create a project named "BetterXen Development".
2. Status (single select): Backlog, Ready, In Progress, In Review, Blocked, Done.
3. Fields: Priority (p1, p2, p3), Area (text), and the built-in Milestone, Assignees and Status. No other custom fields.
4. Add the open issues and pull requests (`gh project item-add`). Closed native issues stay out; they are indexed in [the native issue archive](../research/native-issue-archive.md).
5. Optional view in the web UI: a table filtered to the current milestone and sorted by Priority. No phase views and no native board.
+31
View File
@@ -0,0 +1,31 @@
# Component reuse matrix
Companion to the [upstream registry](upstream-registry.md); same evidence limits (class D, nothing run, not legal advice). "External" means installed or supplied by the user and invoked, never bundled or copied. GPL-3.0-or-later is BetterXen's license.
| Need | Candidate | Decision | Reason and condition |
| --- | --- | --- | --- |
| Windows runtime APIs | CrossOver (Wine-based) | **Adopt as external dependency** (strategic decision, ADR 0005) | Proprietary product; do not bundle or redistribute. Capabilities and interfaces unverified (#348, #350). |
| Windows runtime APIs | Upstream Wine | Reference; source may be consulted | LGPL 2.1. Copying source would need per-file review and a recorded pin. Not needed for the current plan. |
| x86-64 on ARM64 | Rosetta 2 | **Permitted where Apple supports it**; external | Apple component; support lifetime unknown (#349). BetterXen's own code stays ARM64. |
| x86-64 on ARM64 | FEX | **Not applicable now** | README targets ARM64 Linux. Re-check only if a macOS host path appears. |
| Direct3D 12 to Metal | D3DMetal | **Evaluate as external**, subject to license | Not in CodeWeavers' FOSS list; terms and availability to verify (#349, #354). Not redistributable until proven. |
| Direct3D 11/10 to Metal | DXMT | **Evaluate** as external binary or build | LGPL 2.1-or-later; usable as a separate process or library under LGPL terms; linking or copying needs legal review (#354). |
| Direct3D to Vulkan | DXVK | **Evaluate** only together with MoltenVK | zlib/libpng is permissive and GPL-compatible. Value on macOS unknown. |
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
| Vulkan on Metal | MoltenVK | **Evaluate** | Apache-2.0 (compatible with GPLv3). Subset of Vulkan; coverage vs consumers unknown. |
| Shader compiler / runtime | VIctory, VIctory-macOS | **Rejected for reuse** | Built for a specific commercial game's Xbox Series build whose provenance is not established as authorized. Ideas only. |
| Project discovery | PortWatch VI | Reference only | Editorial tracker; not engineering evidence; nothing imported. |
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
| Host receipt, frame statistics, cross-toolchain probe | `crates/hybrid` | **Build** (original Rust, public system interfaces) | ossover and Whisky are Swift references; no code adapted. See [audit](upstream-integration-audit.md). |
| Metal HUD log parsing | ossover `MetalHUDLog` | **Reference only** | Log format is documented only by third-party observation; implement after a real trace is captured (#145). |
| Bottle and bundle internals (`cxbottle.conf`, SharedSupport layout) | ossover and others | **Do not depend** | Undocumented, derived from reverse engineering; #350 decides. |
| Game-specific XCL layers | MacBox, ScarlettMac | **Rejected** | GPL-2.0-only and game-specific. |
| Memory-pressure guard for workloads | skakwy/victory-mac `mac/run-victory.sh` | **Adapted** into `crates/hybrid/src/memory.rs` | Contributor-authored, GPL-3.0, permission granted; reimplemented in Rust. |
| Windows cross-linker wrapper | skakwy/victory-mac `tools/macos/gnullvm-cc.sh` | **Not used** | Failed with Homebrew `llvm@17`; llvm-mingw covers the need. |
| Windows cross toolchain | llvm-mingw 20261117 | **External dependency**, not vendored | Apache-2.0 with LLVM exceptions; checksum recorded in [hybrid-toolchain.md](hybrid-toolchain.md). |
| Zero-copy Metal swizzle, D3DMetal state fixes | skakwy/victory-mac `mac/unixlib`, `PROGRESS.md` | **Rejected** | Act on D3DMetal internals; Apple licence forbids reverse engineering. |
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
@@ -0,0 +1,59 @@
# CrossOver baseline on the M4 reference machine (2026-11-25)
Evidence class: observed runs on one machine by one person (class B in the sense of [claims.toml](../claims.toml)); **not independently reproduced**, so #355 and #353 stay open. Every result is for original BetterXen workloads, never for a game. Nothing here shows Xbox compatibility.
## Environment
| Item | Value (source) |
| --- | --- |
| Machine | Apple M4, 10 cores (4 performance, 6 efficiency), 24 GiB, macOS 27.0 build 26A428 (`betterxen-hybrid host`) |
| CrossOver | `/Applications/CrossOver.app`, 26.3, build 26.3.0.39832, bundle id `com.codeweavers.CrossOver`, main executable universal (x86_64, arm64) (`betterxen-hybrid crossover`). Licence or trial state not inspected; runs worked |
| Wine host binaries | `wineloader` and `wineserver` are **x86_64 only** (`lipo -archs`), so CrossOver's Wine runs under Rosetta 2 on this Mac. `arch -x86_64 /usr/bin/true` executes |
| Bottle | `betterxen-test`, template `win11_64`, created in 18.7 s with `cxbottle --bottle betterxen-test --create --template win11_64` |
| Launch interface | `bin/wine --bottle B program` and `bin/wineserver -k`. `cxbottle --help` and `cxstart --help` exist in the bundle. **None of these command-line interfaces is documented by CodeWeavers for macOS**: the [Mac user guide](https://support.codeweavers.com/en_US/crossover-mac-user-guide) and [advanced configuration page](https://support.codeweavers.com/advanced-crossover-mac-configuration) cover the GUI and hook variables only. They are used here as observed vendor behaviour of this build |
| Backend selection | `CX_GRAPHICS_BACKEND=<name>` in the environment. Undocumented (see #350). An unknown value (`bogus`) was **accepted silently** and gave the same result as the default |
| Toolchain | llvm-mingw 20261117, Rust 1.100.0; see [hybrid-toolchain.md](hybrid-toolchain.md) |
| Host noise | CrossOver's antivirus helper prints `LibClamAV Error` and `Can't open file or directory` because Homebrew's ClamAV has no database in `/opt/homebrew/var/lib/clamav`. Harmless to results; the run record reports it as a diagnostic |
## Workloads executed
Run with `betterxen-hybrid run --bottle betterxen-test --expect PASS -- <exe>`, default backend.
| Workload | x86-64 result | ARM64 result |
| --- | --- | --- |
| C self-check (CRC-32, four threads) | passed, exit 0, 1.4 s | `cannot_execute` |
| Rust self-check (threads, TLS) | passed, exit 0, 0.6 s | `cannot_execute` |
| D3D11 clear and readback | passed, exit 0, 1.1 s | `cannot_execute` |
| D3D11 indexed triangle, shaders, frame loop | passed, exit 0, 0.8 s | `cannot_execute` |
CrossOver 26.3 here **rejects Windows ARM64 executables** with `winewrapper.exe:error: cannot execute`. The ARM64 builds exist and have the correct PE type, but cannot be run in this environment. Process memory sampled while running was about 325 MB (CrossOver's persistent processes, identical across workloads, so it says nothing about the workloads themselves); minimum system free memory stayed at 64 to 68 %.
Negative controls (#365): `d3d11-clear --negative-control` and `d3d11-frameloop --negative-control` expect a deliberately wrong colour and exit 1; the normal runs exit 0.
### Defects found in BetterXen's own workloads, not in CrossOver
1. **Clear test required exact bytes.** The first run read green as 127 where the program expected 128 (0.5 × 255 = 127.5, an exact tie). Re-derived from the primary source ([Direct3D data conversion rules](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-data-conversion)): the ideal conversion adds 0.5 and drops the fraction (128), but implementations are permitted a tolerance of 0.6 unit-last-place on the integer side (`D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP (0.6f)` in the mingw-w64 header; the D3D11 constant is described by the same page). 127 is 0.5 from 127.5 and is within tolerance. The workload now checks that tolerance and prints how many pixels differ from the ideal. This was a correction to match the specification, not a loosening to get a pass: the negative control still fails.
2. **Triangle was culled.** The first frame-loop run left the centre black. The index order was counter-clockwise, which Direct3D 11 culls by default. Fixed to clockwise; the centre then read (51, 102, 204, 255) exactly.
## Graphics backend comparison
`betterxen-hybrid bench --backends default,d3dmetal,dxmt,dxvk,wined3d --repeat 5`, 2000 frames per run, workload `d3d11-frameloop`: a 640x360 offscreen RGBA8 target, one indexed triangle with a vertex and a pixel shader, an event query waited on every frame. **No window and no presentation.** All 25 runs passed. Medians across five runs:
| Backend (detected from workload output) | Adapter reported | Median frame | p95 | p99 | Frame rate | Startup + run, median |
| --- | --- | --- | --- | --- | --- | --- |
| default | AMD Compatibility Mode | 0.281 ms | 0.448 ms | 0.929 ms | 3153 | 1.42 s |
| d3dmetal | AMD Compatibility Mode | 0.282 ms | 0.558 ms | 1.805 ms | 2898 | 1.44 s |
| dxmt | Apple M4 | 0.158 ms | 0.239 ms | 0.382 ms | 5896 | 1.13 s |
| dxvk (via MoltenVK, "cxaddon-1.10.3") | Apple M4 | 0.150 ms | 0.263 ms | 0.478 ms | 5835 | 1.13 s |
| wined3d | Apple M4 | 0.150 ms | 0.256 ms | 0.419 ms | 5788 | 1.13 s |
Observations, with their limits:
- **The default behaved like D3DMetal** (same adapter identity, same timings) for a bottle made from `win11_64` and an unknown executable. CodeWeavers' Advanced Settings page, as recorded in [primary-source-verification](primary-source-verification-2026-11-25.md), says Auto falls back to wined3d without a per-game database entry. The observation disagrees with that reading; why was not investigated.
- D3DMetal's median per-frame submit-and-wait time was about 1.8 times that of the other three, with a larger tail. This is the cost of a trivial draw plus synchronisation, **not rendering throughput**, and shows nothing about real scenes. It identifies a candidate for investigation, not a bottleneck.
- Sustained run, 200,000 frames: D3DMetal 64.1 s, median 0.283 ms, p99 0.987 ms, p99.9 2.07 ms, maximum 20.3 ms; DXMT 29.6 s, median 0.135 ms, p99 0.339 ms, p99.9 0.48 ms, maximum 7.4 ms. No failure, no hang, and free memory did not trend downward (minimum 64 % and 66 %).
- Not measured: GPU utilization (no unprivileged documented source on this host), memory use of the workload itself, thermal behaviour under load (pmset reported no thermal, performance or CPU-power warning before and after; the workload loads the GPU too lightly for that to mean anything), presentation and frame pacing, texture sampling, depth testing, and Direct3D 12.
## What this does and does not establish
Established on this machine and build: CrossOver 26.3 runs original x86-64 console, threaded, Direct3D 11 clear and triangle programs under four graphics backends with correct pixels; it does not run ARM64 Windows programs; BetterXen can detect, supervise, classify and record such runs. Not established: anything about Direct3D 12, real-scene performance, other macOS or CrossOver versions, other machines, or any game. A second contributor still has to reproduce this.
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more