mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-30 02:21:12 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e52d5b0df7 | ||
|
|
0dae988c7c | ||
|
|
ba24aed650 | ||
|
|
5c3d4df8cf | ||
|
|
56783a31b1 | ||
|
|
2567d87a65 | ||
|
|
b0b4f82f1d |
No files matched your search
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **Current stage: Picture** (`docs/roadmap.md`), by the repository owner's decision on 2026-11-30. Boot is marked as left without its ten-run gate having been run under the run protocol. The first frames and the menus are reached, and the open work is translation, textures and stability. The new pinned ladder issue carries the live status. The repository owner also accepted the LLVM-generated opcode table and test vectors of `gfx10-translate` (`docs/research/upstream-registry.md`).
|
||||
- **`CONTRIBUTING.md` is a short entry point for new members, consistent with AGENTS.md.** It covers the hard requirements (the target build, the GDK and the Ghidra results, distributed among members), setup (`setup --find`, `preflight`), the current way of working (pick order, checking for existing work, draft pull request claims with the 3-day rule, tests, Section 8), and running the target build with its diagnostic switches. The outdated workflow is removed: issue-comment claims, the 7-day rule and the Wave 1 backlog. The licensing, sign-off and merge sections are unchanged.
|
||||
- **Check for existing work before investigating any problem the game shows** (AGENTS.md Section 0 Step 3 and Section 7, `docs/process/working-method.md`). Every problem met while running the game, not only the picked blocker, is searched for in open and merged pull requests and open issues by its log event, stub symbol, error code and files. An open pull request that covers it is checked out and worked on, never duplicated. Prompted by a duplicate fix for physical-page DirectStorage requests made alongside #707.
|
||||
- **The Ghidra results of the target build are required to work on the repository**, like the target build and the GDK (AGENTS.md Section 0, `docs/process/working-method.md`). An agent that lacks any of the three does not work on the repository. `bx-cli preflight` adds a `Ghidra results` row: present, and covering the configured target build's executable. `bx-cli setup --ghidra-results <dir>` saves them, and `setup --find` finds them by layout (`RUN_REPORT.md`, `decompiled/`, `exports/*/manifest.json` naming the program, `functions.csv`). `BX_GHIDRA_RESULTS` overrides the setting for one command. Unit tests cover an unset setting, a folder that isn't a results folder, results for another program, and results covering the target.
|
||||
- **Roadmap, Picture stage: BetterXen writes its own shader translator** (repository owner's decision, 2026-11-29). The step that said to vendor the upstream GFX10-to-DXIL translator now describes a translator of our own in `shader-transpiler/`: one rule per instruction, control flow as numbered blocks, each rule checked against the console compiler.
|
||||
@@ -29,6 +31,15 @@ remains unsupported.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- **`shader-transpiler/crates/gfx10-translate`: BetterXen's GFX10.3 shader translator on `main`** (roadmap, Picture stage). It replaces the experiment-branch Python prototype, which moves to `scripts/console-shader/translate.py` as the reference.
|
||||
- **Pieces:** console container reader (zlib ported from `zlib_inflate.cpp`); a decoder for every encoding format, with SDWA/DPP extension words; HLSL translation of every prototype rule through family tables; and coverage. `bx-cli shader translate <vs> <ps> --out <dir>` and `bx-cli shader coverage <dir>` run it.
|
||||
- **Opcode table:** generated from the public LLVM disassembler by `scripts/console-shader/gen_opcodes.py` (gfx1030, gaps from gfx1010, whose GFX10.1 multiply-adds the console compiler emits). Facts only; recorded in the upstream registry.
|
||||
- **Tests:** 127 instructions decode to exactly the text `llvm-mc` prints (`tests/llvm_vectors.txt`). Three shader pairs of our own, assembled by `llvm-mc`, translate to exactly the prototype's HLSL and layout (`tests/goldens/`). Plus refusals, the multiply-add family, wave32 mask bookkeeping and half compressed exports, and FNV-1a against the published vectors.
|
||||
- **Measured locally on the target build's 4,331 vertex and pixel shaders** (they stay local):
|
||||
- every one decodes; the scan takes 3.6 s, against about 10 minutes through `llvm-mc`;
|
||||
- 703 (16.2%) translate on their own, against 491 for the prototype's rules alone;
|
||||
- all 214 pipeline pairs the prototype translated give identical HLSL and layout.
|
||||
- **Differences from the prototype** are listed in the crate README. Among them: `s_movk_i32` sign-extends, and cache keys use standard FNV-1a (the prototype's offset basis is missing a digit).
|
||||
- **Unattended runs get past input screens and continuable asserts** (`docs/testing/target-build-review.md`, Diagnostics).
|
||||
- **`GameInput.dll`:** `BX_INPUT_SCRIPT=A@40,DOWN@50.5,...` presses gamepad buttons at given seconds after the first reading, each for 300 ms, without window focus. Each press, and each entry it cannot read, is logged (`input_script`).
|
||||
- **`bx_runtime_veh.dll`:** `BX_CONTINUE_ASSERTS=1` steps over an `int3` in the title's own executable instead of letting it reach the crash reporter, and logs each address once (`assert_continued`). An `int3` anywhere else is left alone.
|
||||
|
||||
+41
-22
@@ -1,35 +1,53 @@
|
||||
# Contributing to BetterXen
|
||||
|
||||
BetterXen is a modular, CrossOver-based Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS. Contributions are organized into **6 parallel tracks** so 5–8+ human contributors and coding agents can work simultaneously without merge conflicts.
|
||||
BetterXen runs a project-authorized Xbox Series title on Apple Silicon Macs, through CrossOver, Rosetta 2 and D3DMetal plus BetterXen's own shims. Members work by pointing a coding agent at this repository and saying **"work"**; the agent follows [AGENTS.md](AGENTS.md). This page is the short version for a person joining.
|
||||
|
||||
## Active Work & Track Ownership
|
||||
## What you need
|
||||
|
||||
The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones M0–M6), supported by [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and the ready-to-claim Wave 1 issues in [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md). The earlier native-first workspace was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently at Git tag `native-first-final`.
|
||||
These are a **hard requirement**. Without every one of them you, and your agent, do not work on the repository:
|
||||
|
||||
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
|
||||
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
|
||||
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
|
||||
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
|
||||
- an Apple Silicon Mac with CrossOver 26.3+ (licensed separately, never bundled), D3DMetal, and at least 10 GiB free;
|
||||
- **the project-authorized target build**;
|
||||
- **the GDK**, under the project's authorization;
|
||||
- **the Ghidra results of the target build** (its static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`).
|
||||
|
||||
## Development & Verification
|
||||
The target build, the GDK and the Ghidra results are distributed among members. Ask a maintainer for them; never get them anywhere else, and never commit, upload or post anything from them (paths, file names, hashes or bytes).
|
||||
|
||||
Requirements on Apple Silicon macOS: Rust 1.85+ (`aarch64-apple-darwin`), `mingw-w64` & `cmake` (`brew install mingw-w64 cmake`), Python 3.11+, Rosetta 2, and CrossOver 26.3+ (externally installed, never bundled).
|
||||
|
||||
Run these checks before opening a PR:
|
||||
## Getting started
|
||||
|
||||
```sh
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli
|
||||
scripts/build-shims.sh
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
git clone https://github.com/MacosPorters/betterxen.git && cd betterxen
|
||||
brew install mingw-w64 cmake gh # Rust 1.85+ and Python 3.11+ are also needed
|
||||
cargo build --locked -p bx-cli
|
||||
target/debug/bx-cli setup --find # finds the build, the GDK and the Ghidra results in your home folder
|
||||
target/debug/bx-cli preflight # must print: Ready to work.
|
||||
```
|
||||
|
||||
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
|
||||
`setup` saves the three locations in `~/.config/betterxen/local.conf`, outside the repository, once per machine. If `--find` finds more than one distinct build, choose with `bx-cli setup --target-exe <path>`.
|
||||
|
||||
Then tell your agent **"work"**. If you work by hand, follow the same steps yourself: [AGENTS.md](AGENTS.md) Section 0.
|
||||
|
||||
## How work is organised
|
||||
|
||||
The full process is [AGENTS.md](AGENTS.md) Section 0 and [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md). In short:
|
||||
|
||||
1. **Pick one thing**, in this order: your own pull requests that need attention; a review of someone else's; a `handoff` issue of the current stage (named on the pinned `ladder` issue); or the first thing the target build stops on.
|
||||
2. **Check for existing work first.** Before investigating any problem the game shows, search open and merged pull requests and open issues for it. If an open pull request covers it, check that branch out and work there.
|
||||
3. **Claim it with a draft pull request** titled `[<Stage>] <signature>`, before writing the fix. A draft with no push for 3 days may be taken over.
|
||||
4. **Evidence, smallest fix, test.** Every contract the fix introduces gets a conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row with it.
|
||||
5. **Verify** with [AGENTS.md](AGENTS.md) Section 8, fill in the five-part description (Blocker, Contract, Fix, Test, Proof), and mark it ready.
|
||||
|
||||
Something you can't finish goes into a `handoff` issue instead, with what you saw, tried and still don't know.
|
||||
|
||||
## Running the target build
|
||||
|
||||
Runs are made offline, inside a sandbox that blocks outbound network: [docs/testing/target-build-review.md](docs/testing/target-build-review.md) has the procedure and the diagnostic switches. Three switches matter for getting through the title unattended:
|
||||
|
||||
- `BX_INPUT_SCRIPT=A@40,A@50` presses buttons;
|
||||
- `BX_CONTINUE_ASSERTS=1` steps over the title's continuable asserts;
|
||||
- `BX_PRESENT_DUMP=<folder>` saves frames.
|
||||
|
||||
`bx-cli run` stages the GDK's texture libraries for the target build automatically ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)). `bx-cli report <log.jsonl>...` turns run logs into the report and the blocker signatures that pull requests are titled with.
|
||||
|
||||
## Licensing & Provenance Policy
|
||||
|
||||
@@ -39,9 +57,10 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
|
||||
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
|
||||
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
|
||||
|
||||
|
||||
## Pull Requests & DCO Sign-Off
|
||||
|
||||
- Branch from `main`, keep changes focused inside your track scope, link the issue with `Closes #<number>`, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
|
||||
- Branch from `main`, keep changes focused inside your track scope, link any related issue (`Closes #<number>` for a handoff it finishes), update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
|
||||
- Disclose material AI assistance and personally review generated changes. Never include secrets, personal paths, or credentials in patches or logs.
|
||||
- Sign off every commit under the [Developer Certificate of Origin](https://developercertificate.org/):
|
||||
|
||||
|
||||
Generated
+5
@@ -9,6 +9,7 @@ dependencies = [
|
||||
"bx-probe",
|
||||
"bx-telemetry",
|
||||
"dxbc-accc",
|
||||
"gfx10-translate",
|
||||
"libc",
|
||||
]
|
||||
|
||||
@@ -31,6 +32,10 @@ dependencies = [
|
||||
name = "dxbc-accc"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "gfx10-translate"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
|
||||
@@ -5,6 +5,7 @@ members = [
|
||||
"launcher/crates/bx-telemetry",
|
||||
"shader-transpiler/crates/d3dmetal-harness",
|
||||
"shader-transpiler/crates/dxbc-accc",
|
||||
"shader-transpiler/crates/gfx10-translate",
|
||||
]
|
||||
exclude = ["legacy-native"]
|
||||
resolver = "3"
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [gfx10-translate](../shader-transpiler/crates/gfx10-translate/README.md) — BetterXen's GFX10.3 console shader translator: container reader, decoder with an LLVM-generated opcode table, HLSL translation ported from the Python prototype, coverage over local shaders, and how to add an instruction.
|
||||
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
|
||||
|
||||
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
|
||||
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
|
||||
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
|
||||
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
|
||||
| LLVM (AMDGPU target) | [llvm/llvm-project](https://github.com/llvm/llvm-project) | Homebrew LLVM 23.1.6 (`llvm-mc`) | Apache-2.0 WITH LLVM-exception | Source of the generated GFX10.3 opcode table and decoder test vectors (`shader-transpiler/crates/gfx10-translate`) | Run locally by `scripts/console-shader/gen_opcodes.py` and `gen_llvm_vectors.py`. Only facts are committed (opcode number to mnemonic, instruction words to text); no LLVM code or tables are copied. Accepted by the repository owner on 2026-11-30 (AGENTS.md Section 4). |
|
||||
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
|
||||
|
||||
## Built and run for M1-D2 (#417)
|
||||
|
||||
+2
-2
@@ -53,8 +53,8 @@ Every gate below is measured the same way ([working method](process/working-meth
|
||||
|
||||
| Stage | The target build… | Exit gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
|
||||
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **Left** (repository owner's decision, 2026-11-30; the gate was not run under the run protocol) |
|
||||
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | **Current** (since 2026-11-30) |
|
||||
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
|
||||
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
|
||||
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
|
||||
|
||||
@@ -13,6 +13,7 @@ path = "src/main.rs"
|
||||
bx-probe = { path = "../bx-probe" }
|
||||
bx-telemetry = { path = "../bx-telemetry" }
|
||||
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
|
||||
gfx10-translate = { path = "../../../shader-transpiler/crates/gfx10-translate" }
|
||||
# POSIX signals and process groups for `run` supervision.
|
||||
libc = "=0.2.191"
|
||||
|
||||
|
||||
@@ -69,6 +69,8 @@ fn usage_text() -> &'static str {
|
||||
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
|
||||
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
|
||||
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
|
||||
bx-cli shader translate <vs> <ps> --out <dir> Translate a console VS/PS pair to HLSL (gfx10-translate)\n\
|
||||
bx-cli shader coverage <dir> Rank what blocks translation across a folder of *_VS.* / *_PS.* shaders\n\
|
||||
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] Remember where the target build, the GDK and the target build's Ghidra results are on this machine (saved outside the repository); --find searches the home folder for them\n\
|
||||
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, the Ghidra results, disk space. Fails if anything is missing\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
@@ -1990,6 +1992,85 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
})
|
||||
}
|
||||
|
||||
/// `bx-cli shader translate <vs> <ps> --out <dir>`: translates a console VS/PS pair (containers
|
||||
/// or raw code blobs) with the gfx10-translate crate. Writes `<vs key>_<ps key>.vs.hlsl`,
|
||||
/// `.ps.hlsl` and `.il` (the host pipeline's input layout and resources), keyed by FNV-1a of each
|
||||
/// blob as the shim's shader cache expects. Compile the HLSL with the public DXC (vs_6_0/ps_6_0).
|
||||
fn cmd_shader_translate(args: &[String]) -> ExitCode {
|
||||
let (vs_path, ps_path, out) = match args {
|
||||
[vs, ps, flag, out] if flag == "--out" => (vs, ps, out),
|
||||
_ => {
|
||||
eprintln!("usage: bx-cli shader translate <vs container> <ps container> --out <dir>");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let (vs, ps) = match (fs::read(vs_path), fs::read(ps_path)) {
|
||||
(Ok(vs), Ok(ps)) => (vs, ps),
|
||||
(Err(e), _) | (_, Err(e)) => {
|
||||
eprintln!("error: cannot read the shaders: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let t = match gfx10_translate::translate_blobs(&vs, &ps) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
eprintln!("unsupported: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let key = format!(
|
||||
"{}_{}",
|
||||
gfx10_translate::translate::fnv1a(&vs),
|
||||
gfx10_translate::translate::fnv1a(&ps)
|
||||
);
|
||||
let base = Path::new(out).join(&key);
|
||||
let write = |ext: &str, text: &str| fs::write(base.with_extension(ext), text);
|
||||
let written = fs::create_dir_all(out)
|
||||
.and_then(|()| write("vs.hlsl", &t.vs_hlsl))
|
||||
.and_then(|()| write("ps.hlsl", &t.ps_hlsl))
|
||||
.and_then(|()| write("il", &t.layout));
|
||||
match written {
|
||||
Ok(()) => {
|
||||
println!("{key}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("error: cannot write to {out}: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `bx-cli shader coverage <dir>`: how many of the console shaders in a local folder (`*_VS.*`,
|
||||
/// `*_PS.*`) translate, and what blocks the rest, most frequent first.
|
||||
fn cmd_shader_coverage(args: &[String]) -> ExitCode {
|
||||
let [dir] = args else {
|
||||
eprintln!("usage: bx-cli shader coverage <folder of *_VS.* / *_PS.* shaders>");
|
||||
return ExitCode::FAILURE;
|
||||
};
|
||||
let cov = match gfx10_translate::coverage::scan(Path::new(dir)) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("error: cannot scan {dir}: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let pct = if cov.shaders == 0 {
|
||||
0.0
|
||||
} else {
|
||||
100.0 * cov.translated as f64 / cov.shaders as f64
|
||||
};
|
||||
println!(
|
||||
"shaders: {} translated: {} ({pct:.1}%)",
|
||||
cov.shaders, cov.translated
|
||||
);
|
||||
println!("blockers (shaders stopped, reason):");
|
||||
for (key, n) in cov.ranked().into_iter().take(40) {
|
||||
println!(" {n:6} {key}");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn cmd_shader(path: &str) -> ExitCode {
|
||||
let data = match fs::read(path) {
|
||||
Ok(d) => d,
|
||||
@@ -2076,6 +2157,10 @@ fn main() -> ExitCode {
|
||||
"setup" => cmd_setup(&args[1..]),
|
||||
"preflight" => cmd_preflight(),
|
||||
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
|
||||
"shader" if args.len() >= 2 && args[1] == "translate" => {
|
||||
cmd_shader_translate(&args[2..])
|
||||
}
|
||||
"shader" if args.len() >= 2 && args[1] == "coverage" => cmd_shader_coverage(&args[2..]),
|
||||
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
|
||||
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
|
||||
"report" if args.len() >= 2 => cmd_report(&args[1..]),
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generates shader-transpiler/crates/gfx10-translate/tests/llvm_vectors.txt: instruction
|
||||
encodings and their canonical text from the public LLVM AMDGPU assembler (llvm-mc, gfx1030).
|
||||
|
||||
Each line is `<hex words> | <text>`. The decoder test decodes the words and requires the same
|
||||
text, so the decoder is checked against an implementation independent of BetterXen.
|
||||
|
||||
usage: gen_llvm_vectors.py [--llvm-mc PATH] > shader-transpiler/crates/gfx10-translate/tests/llvm_vectors.txt
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
# Every shape the translator handles, and common instructions of each format.
|
||||
INSTRUCTIONS = """
|
||||
s_add_u32 s0, s1, s2
|
||||
s_add_u32 s3, s1, 0x12345678
|
||||
s_or_b32 s0, s1, 7
|
||||
s_and_b32 s4, s5, -1
|
||||
s_xor_b32 s0, s1, s2
|
||||
s_mul_i32 s0, s1, s2
|
||||
s_sub_u32 s0, s1, 64
|
||||
s_lshr_b32 s0, s1, 4
|
||||
s_lshl_b32 s0, s1, 2
|
||||
s_min_u32 s0, s1, s2
|
||||
s_max_u32 s0, s1, s2
|
||||
s_bfe_u32 s0, s1, 0x100000
|
||||
s_mov_b32 s0, s1
|
||||
s_mov_b32 s0, 0x3f800000
|
||||
s_mov_b32 m0, s1
|
||||
s_mov_b64 s[0:1], s[2:3]
|
||||
s_mov_b64 s[0:1], exec
|
||||
s_and_b64 exec, exec, s[2:3]
|
||||
s_wqm_b64 exec, exec
|
||||
s_brev_b32 s0, s1
|
||||
s_swappc_b64 s[4:5], s[4:5]
|
||||
s_movk_i32 s0, 0x1234
|
||||
s_cmp_eq_u32 s0, s1
|
||||
s_cbranch_scc0 4
|
||||
s_endpgm
|
||||
s_load_dwordx4 s[0:3], s[4:5], 0x10
|
||||
s_load_dwordx8 s[8:15], s[4:5], 0x20
|
||||
s_load_dwordx4 s[0:3], s[4:5], 0x0
|
||||
s_buffer_load_dword s0, s[4:7], 0x0
|
||||
s_buffer_load_dwordx2 s[0:1], s[4:7], 0x8
|
||||
s_buffer_load_dwordx4 s[8:11], s[4:7], 0x10
|
||||
s_buffer_load_dwordx8 s[8:15], s[4:7], 0x20
|
||||
s_buffer_load_dwordx16 s[16:31], s[4:7], 0x40
|
||||
v_mov_b32_e32 v0, v1
|
||||
v_mov_b32_e32 v0, s2
|
||||
v_mov_b32_e32 v0, 0x40490fdb
|
||||
v_mov_b32_e32 v0, 1.0
|
||||
v_mov_b32_e32 v0, -4.0
|
||||
v_mov_b32_e32 v0, 0.15915494
|
||||
v_mov_b32_e32 v0, 17
|
||||
v_mov_b32_e32 v0, -3
|
||||
v_add_f32_e32 v0, v1, v2
|
||||
v_add_f32_e32 v0, 0.5, v1
|
||||
v_mul_f32_e32 v0, 0x3e800000, v1
|
||||
v_sub_f32_e32 v0, v1, v2
|
||||
v_subrev_f32_e32 v0, v1, v2
|
||||
v_max_f32_e32 v0, v1, v2
|
||||
v_min_f32_e32 v0, v1, v2
|
||||
v_fmac_f32_e32 v0, v1, v2
|
||||
v_mul_legacy_f32_e32 v0, v1, v2
|
||||
v_cvt_pkrtz_f16_f32_e32 v0, v1, v2
|
||||
v_lshlrev_b32_e32 v0, 2, v1
|
||||
v_lshrrev_b32_e32 v0, 16, v1
|
||||
v_ashrrev_i32_e32 v0, 16, v1
|
||||
v_and_b32_e32 v0, 0xff, v1
|
||||
v_or_b32_e32 v0, v1, v2
|
||||
v_xor_b32_e32 v0, v1, v2
|
||||
v_sub_nc_u32_e32 v0, v1, v2
|
||||
v_subrev_nc_u32_e32 v0, v1, v2
|
||||
v_add_nc_u32_e32 v0, s2, v1
|
||||
v_mul_u32_u24_e32 v0, v1, v2
|
||||
v_min_u32_e32 v0, v1, v2
|
||||
v_max_u32_e32 v0, v1, v2
|
||||
v_rcp_f32_e32 v0, v1
|
||||
v_rsq_f32_e32 v0, v1
|
||||
v_sqrt_f32_e32 v0, v1
|
||||
v_floor_f32_e32 v0, v1
|
||||
v_fract_f32_e32 v0, v1
|
||||
v_exp_f32_e32 v0, v1
|
||||
v_log_f32_e32 v0, v1
|
||||
v_trunc_f32_e32 v0, v1
|
||||
v_rndne_f32_e32 v0, v1
|
||||
v_ceil_f32_e32 v0, v1
|
||||
v_cvt_f32_u32_e32 v0, v1
|
||||
v_cvt_f32_i32_e32 v0, v1
|
||||
v_cvt_i32_f32_e32 v0, v1
|
||||
v_sin_f32_e32 v0, v1
|
||||
v_cos_f32_e32 v0, v1
|
||||
v_add_f32_e64 v0, v1, v2
|
||||
v_mul_f32_e64 v0, -v1, v2
|
||||
v_mul_f32_e64 v0, v1, -v2
|
||||
v_mul_f32_e64 v0, -v1, |v2|
|
||||
v_add_f32_e64 v0, v1, v2 clamp
|
||||
v_mul_f32_e64 v0, v1, v2 mul:2
|
||||
v_max_f32_e64 v0, v1, s2
|
||||
v_sub_f32_e64 v0, v1, v2
|
||||
v_rcp_f32_e64 v0, -v1
|
||||
v_lshlrev_b32_e64 v0, s2, v1
|
||||
v_mul_lo_u32 v0, v1, v2
|
||||
v_mul_hi_u32 v0, v1, v2
|
||||
v_fma_f32 v0, v1, v2, v3
|
||||
v_fma_f32 v0, -v1, v2, 1.0
|
||||
v_med3_f32 v0, v1, 0, 1.0
|
||||
v_bfe_u32 v0, v1, 8, 8
|
||||
v_cmp_lt_f32_e32 vcc_lo, v1, v2
|
||||
v_cmpx_eq_u32_e32 v1, v2
|
||||
v_cndmask_b32_e32 v0, v1, v2, vcc_lo
|
||||
v_interp_p1_f32_e32 v2, v0, attr0.x
|
||||
v_interp_p2_f32_e32 v2, v1, attr0.x
|
||||
v_interp_p2_f32_e32 v3, v1, attr3.w
|
||||
v_interp_mov_f32_e32 v0, p0, attr2.y
|
||||
v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]
|
||||
v_fma_mixhi_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]
|
||||
buffer_load_dword v0, v1, s[4:7], 0 idxen
|
||||
buffer_load_dword v0, v1, s[4:7], 0 idxen offset:12
|
||||
buffer_load_dwordx2 v[0:1], v2, s[4:7], 0 idxen
|
||||
buffer_load_dwordx3 v[0:2], v3, s[4:7], 0 idxen offset:4
|
||||
buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 idxen
|
||||
buffer_load_dword v0, v1, s[4:7], 0 offen
|
||||
buffer_load_dword v0, off, s[4:7], s2 offset:16
|
||||
tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen
|
||||
tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] idxen offset:8
|
||||
image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
|
||||
image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
|
||||
exp pos0, v0, v1, v2, v3 done
|
||||
exp mrt0, v0, v1, v2, v3 done vm
|
||||
exp mrt0, v0, off, off, off
|
||||
exp param3, v4, v5, v6, v7
|
||||
exp mrt0, v0, v0, v1, v1 done compr vm
|
||||
v_fmaak_f32 v0, v1, v2, 0x3f800000
|
||||
v_fmamk_f32 v0, v1, 0x40000000, v2
|
||||
gfx1010 v_mac_f32_e32 v0, v1, v2
|
||||
gfx1010 v_mac_f32_e64 v0, -v1, v2
|
||||
gfx1010 v_mad_f32 v0, v1, v2, v3
|
||||
gfx1010 v_madak_f32 v0, v1, v2, 0x3f800000
|
||||
gfx1010 v_madmk_f32 v0, v1, 0x40000000, v2
|
||||
"""
|
||||
# Lines starting with a target name are assembled for that target: the console compiler emits a
|
||||
# few GFX10.1 instructions (v_mac_f32, v_mad_f32, v_madak/madmk_f32) that LLVM knows only there.
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
|
||||
a = ap.parse_args()
|
||||
lines = [l.strip() for l in INSTRUCTIONS.strip().splitlines() if l.strip()]
|
||||
version = subprocess.run([a.llvm_mc, "--version"], capture_output=True, text=True).stdout.split("\n")
|
||||
version = next((v.strip() for v in version if "version" in v.lower()), "unknown")
|
||||
print("# @generated by scripts/console-shader/gen_llvm_vectors.py from %s (gfx1030)." % version)
|
||||
print("# <instruction words> | <llvm-mc's text for them>")
|
||||
for line in lines:
|
||||
mcpu = "gfx1030"
|
||||
if line.startswith("gfx"):
|
||||
mcpu, line = line.split(" ", 1)
|
||||
r = subprocess.run([a.llvm_mc, "-arch=amdgcn", "-mcpu=" + mcpu, "-show-encoding"], input=line,
|
||||
capture_output=True, text=True)
|
||||
enc = next(l for l in r.stdout.splitlines() if "encoding:" in l)
|
||||
data = bytes(int(b, 16) for b in enc.split("encoding:")[1].strip().strip("[]").split(","))
|
||||
words = " ".join("%08x" % int.from_bytes(data[i:i + 4], "little") for i in range(0, len(data), 4))
|
||||
# The canonical text is what the disassembler prints for these bytes.
|
||||
d = subprocess.run([a.llvm_mc, "--disassemble", "-arch=amdgcn", "-mcpu=" + mcpu],
|
||||
input=" ".join("0x%02x" % b for b in data), capture_output=True, text=True)
|
||||
text = next(l.strip() for l in d.stdout.splitlines() if l.strip() and not l.strip().startswith("."))
|
||||
print("%s | %s" % (words, text))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generates shader-transpiler/crates/gfx10-translate/src/opcodes.rs: the GFX10.3 (gfx1030)
|
||||
instruction names for every opcode value of every encoding format the decoder handles.
|
||||
|
||||
The names come from the public LLVM AMDGPU disassembler (llvm-mc, Apache-2.0 WITH
|
||||
LLVM-exception): for each format, an instruction word is built with each opcode value and
|
||||
fixed, valid operand fields, and llvm-mc names it or rejects it. Only the resulting facts (opcode
|
||||
number -> mnemonic) are committed; LLVM itself is not.
|
||||
|
||||
usage: gen_opcodes.py [--llvm-mc PATH] > shader-transpiler/crates/gfx10-translate/src/opcodes.rs
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# (name, opcode bits, word builder, mask of word 0's format and opcode bits) per format.
|
||||
# Builders place `op` in the format's opcode field; the other fields hold valid registers.
|
||||
# Layouts: AMD "RDNA 2" instruction set reference.
|
||||
FORMATS = [
|
||||
# SOP2 opcodes from 0x60 and VOP2 opcodes from 0x3E are the prefixes of other formats.
|
||||
("SOP2", 7, lambda op: [0x80000000 | (op << 23) | (2 << 8) | 1] if op < 0x60 else None, 0xFF800000),
|
||||
("SOPK", 5, lambda op: [[0xB0000000 | (op << 23) | 0x10], [0xB0000000 | (op << 23) | 0x1801, 0x1]], 0xFF800000),
|
||||
("SOP1", 8, lambda op: [0xBE800000 | (op << 8) | 2], 0xFF80FF00),
|
||||
("SOPC", 7, lambda op: [0xBF000000 | (op << 16) | (2 << 8) | 1], 0xFFFF0000),
|
||||
("SOPP", 7, lambda op: [0xBF800000 | (op << 16)], 0xFFFF0000),
|
||||
("SMEM", 8, lambda op: [0xF4000000 | (op << 18) | 2, 0xFA000010], 0xFFFC0000),
|
||||
# v_madmk/madak/fmamk/fmaak carry a literal constant after the instruction word.
|
||||
("VOP2", 6, lambda op: [[(op << 25) | (2 << 9) | 0x101], [(op << 25) | (2 << 9) | 0x101, 0x3F800000]] if op < 0x3E else None,
|
||||
0xFE000000),
|
||||
("VOP1", 8, lambda op: [0x7E000000 | (op << 9) | 0x101], 0xFE01FE00),
|
||||
("VOPC", 8, lambda op: [0x7C000000 | (op << 17) | (2 << 9) | 0x101], 0xFFFE0000),
|
||||
("VOP3", 10, lambda op: [0xD4000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFFFF0000),
|
||||
("VOP3P", 7, lambda op: [0xCC000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFC7F0000),
|
||||
("VINTRP", 2, lambda op: [0xC8000000 | (op << 16) | 1], 0xFC030000),
|
||||
("DS", 8, lambda op: [[0xD8000000 | (op << 18), w] for w in (0x00000201, 0x00000001, 0x00030201)], 0xFFFC0000),
|
||||
("MUBUF", 7, lambda op: [0xE0000000 | ((op & 0x7F) << 18) | 0x2000, 0x80010001], 0xFDFC0000),
|
||||
("MTBUF", 4, lambda op: [0xE8000000 | (op & 7) << 16 | (22 << 19) | 0x2000, 0x80010001 | ((op >> 3) << 21)], 0xFC070000),
|
||||
("MIMG", 8, lambda op: [[0xF0000000 | ((op & 0x7F) << 18) | ((op >> 7) << 0) | (1 << 3) | (0xF << 8), w]
|
||||
for w in (0x00820004, 0x00020004)], 0xFDFC0001),
|
||||
("FLAT", 7, lambda op: [0xDC000000 | (op << 18), 0x007D0001], 0xFDFCC000),
|
||||
("GLOBAL", 7, lambda op: [0xDC008000 | (op << 18), 0x007D0001], 0xFDFCC000),
|
||||
]
|
||||
|
||||
|
||||
def name_of(llvm_mc, words, mask, mcpu):
|
||||
"""The mnemonic llvm-mc gives `words`, or None. A name counts only when llvm-mc reports no
|
||||
invalid encoding and its first instruction is as long as `words` with the same format and
|
||||
opcode bits (`mask`): for an invalid opcode, llvm-mc skips a word and decodes the next one as
|
||||
an instruction of its own. Operand fields may be re-encoded, so they are not compared."""
|
||||
data = b"".join(w.to_bytes(4, "little") for w in words)
|
||||
text = " ".join("0x%02x" % b for b in data)
|
||||
r = subprocess.run([llvm_mc, "--disassemble", "-show-encoding", "-arch=amdgcn", "-mcpu=" + mcpu], input=text,
|
||||
capture_output=True, text=True)
|
||||
if "invalid instruction encoding" in r.stderr:
|
||||
return None
|
||||
for line in r.stdout.splitlines():
|
||||
if "encoding:" not in line:
|
||||
continue
|
||||
asm, enc = line.split("; encoding:")
|
||||
encoded = bytes(int(b, 16) for b in enc.strip().strip("[]").split(","))
|
||||
same = len(encoded) == len(data) and (int.from_bytes(encoded[:4], "little") & mask) == (words[0] & mask)
|
||||
return asm.split()[0] if same else None
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
|
||||
a = ap.parse_args()
|
||||
version = subprocess.run([a.llvm_mc, "--version"], capture_output=True, text=True).stdout.split("\n")
|
||||
version = next((v.strip() for v in version if "version" in v.lower()), "unknown")
|
||||
jobs = [(fmt, op, build(op), mask) for fmt, bits, build, mask in FORMATS for op in range(1 << bits)]
|
||||
|
||||
def first_name(job):
|
||||
# A builder gives one word list, or several variants of the operand fields to try in turn
|
||||
# (llvm-mc rejects some opcodes unless their unused fields are zero).
|
||||
if job[2] is None:
|
||||
return None
|
||||
variants = job[2] if isinstance(job[2][0], list) else [job[2]]
|
||||
# gfx1030 first; the console compiler also emits a few GFX10.1 instructions that LLVM
|
||||
# knows only for gfx1010 (v_mac_f32), so gaps are filled from there.
|
||||
for mcpu in ("gfx1030", "gfx1010"):
|
||||
for v in variants:
|
||||
n = name_of(a.llvm_mc, v, job[3], mcpu)
|
||||
if n:
|
||||
return n
|
||||
return None
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
names = list(pool.map(first_name, jobs))
|
||||
out = ["// @generated by scripts/console-shader/gen_opcodes.py from %s (gfx1030, gaps from gfx1010)." % version,
|
||||
"// Do not edit. Facts only: opcode number -> mnemonic, per encoding format, as named by the",
|
||||
"// public LLVM AMDGPU disassembler (Apache-2.0 WITH LLVM-exception).", "",
|
||||
"/// (opcode, mnemonic) pairs of one encoding format, sorted by opcode.", "pub type Table = &'static [(u16, &'static str)];", ""]
|
||||
for fmt, _, _, _ in FORMATS:
|
||||
rows = [(op, n) for (f, op, _, _), n in zip(jobs, names) if f == fmt and n]
|
||||
out.append("pub static %s: Table = &[" % fmt)
|
||||
for op, n in rows:
|
||||
out.append(" (%d, \"%s\")," % (op, n))
|
||||
out.append("];")
|
||||
out.append("")
|
||||
print("%s: %d opcodes" % (fmt, len(rows)), file=sys.stderr)
|
||||
# MTBUF unified buffer formats (word 0 bits 25:19), named by the disassembler as format:[NAME].
|
||||
def format_name(value):
|
||||
words = [0xE8000000 | (value << 19) | (3 << 16) | 0x2000, 0x80000000]
|
||||
text = " ".join("0x%02x" % b for w in words for b in w.to_bytes(4, "little"))
|
||||
r = subprocess.run([a.llvm_mc, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
|
||||
capture_output=True, text=True)
|
||||
if "invalid instruction encoding" in r.stderr or "format:[" not in r.stdout:
|
||||
return None
|
||||
return r.stdout.split("format:[")[1].split("]")[0]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
formats = list(pool.map(format_name, range(128)))
|
||||
out.append("/// MTBUF unified buffer formats: (value, name), as `format:[NAME]` prints them.")
|
||||
out.append("pub static BUF_FORMATS: Table = &[")
|
||||
for value, name in enumerate(formats):
|
||||
if name and not name.isdigit():
|
||||
out.append(" (%d, \"%s\")," % (value, name))
|
||||
out.append("];")
|
||||
out.append("")
|
||||
print("BUF_FORMATS: %d" % sum(1 for f in formats if f and not f.isdigit()), file=sys.stderr)
|
||||
sys.stdout.write("\n".join(out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generates the translator's golden files: small VS/PS pairs written in GFX10.3 assembly,
|
||||
assembled by the public LLVM assembler (llvm-mc), and translated by the Python prototype
|
||||
(translate.py, the reference). The Rust translator must produce the same HLSL and layout.
|
||||
|
||||
Writes shader-transpiler/crates/gfx10-translate/tests/goldens/<case>.{vs,ps}.hex (instruction
|
||||
words), .vs.hlsl, .ps.hlsl and .il. The programs are BetterXen's own, written for these tests.
|
||||
|
||||
usage: gen_translate_goldens.py [--llvm-mc PATH]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import translate # noqa: E402 (the prototype)
|
||||
|
||||
OUT = os.path.join(HERE, "..", "..", "shader-transpiler", "crates", "gfx10-translate", "tests", "goldens")
|
||||
|
||||
# VS reading a fetch-subroutine input and a constant buffer; PS sampling a texture.
|
||||
TEXTURED_VS = """
|
||||
s_swappc_b64 s[4:5], s[4:5]
|
||||
s_load_dwordx4 s[12:15], s[8:9], 0x0
|
||||
s_waitcnt lgkmcnt(0)
|
||||
s_buffer_load_dwordx4 s[16:19], s[12:15], 0x0
|
||||
s_waitcnt lgkmcnt(0)
|
||||
v_mul_f32_e32 v0, s16, v4
|
||||
v_fma_f32 v1, s17, v5, s19
|
||||
v_mov_b32_e32 v2, 0
|
||||
v_mov_b32_e32 v3, 1.0
|
||||
exp pos0, v0, v1, v2, v3 done
|
||||
exp param0, v6, v7, v2, v3
|
||||
s_endpgm
|
||||
"""
|
||||
TEXTURED_PS = """
|
||||
s_mov_b64 s[10:11], exec
|
||||
s_wqm_b64 exec, exec
|
||||
s_mov_b32 m0, s2
|
||||
v_interp_p1_f32_e32 v2, v0, attr0.x
|
||||
v_interp_p2_f32_e32 v2, v1, attr0.x
|
||||
v_interp_p1_f32_e32 v3, v0, attr0.y
|
||||
v_interp_p2_f32_e32 v3, v1, attr0.y
|
||||
s_load_dwordx8 s[0:7], s[8:9], 0x20
|
||||
s_load_dwordx4 s[12:15], s[20:21], 0x0
|
||||
s_and_b64 exec, exec, s[10:11]
|
||||
s_waitcnt lgkmcnt(0)
|
||||
image_sample v[4:7], v[2:3], s[0:7], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
s_waitcnt vmcnt(0)
|
||||
v_mul_f32_e32 v4, v4, v4
|
||||
exp mrt0, v4, v5, v6, v7 done vm
|
||||
s_endpgm
|
||||
"""
|
||||
|
||||
# The ALU families and single rules, in a PS.
|
||||
ALU_VS = """
|
||||
s_swappc_b64 s[4:5], s[4:5]
|
||||
exp pos0, v4, v5, v6, v7 done
|
||||
exp param0, v8, v9, v10, v11
|
||||
s_endpgm
|
||||
"""
|
||||
ALU_PS = """
|
||||
v_interp_p1_f32_e32 v2, v0, attr0.x
|
||||
v_interp_p2_f32_e32 v2, v1, attr0.x
|
||||
v_interp_mov_f32_e32 v3, p0, attr0.y
|
||||
s_movk_i32 s20, 0x1234
|
||||
s_mov_b32 s21, 0x3f800000
|
||||
s_lshl_b32 s22, s20, 2
|
||||
s_or_b32 s23, s22, 7
|
||||
s_and_b32 s23, s23, s21
|
||||
s_xor_b32 s23, s23, s20
|
||||
s_mul_i32 s23, s23, s22
|
||||
s_add_u32 s23, s23, 64
|
||||
s_sub_u32 s23, s23, s20
|
||||
s_lshr_b32 s23, s23, 4
|
||||
s_min_u32 s24, s23, s22
|
||||
s_max_u32 s24, s24, s20
|
||||
s_brev_b32 s25, s24
|
||||
s_bfe_u32 s26, s25, 0x100000
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 3
|
||||
v_lshlrev_b32_e32 v4, 2, v2
|
||||
v_lshrrev_b32_e32 v4, 16, v4
|
||||
v_ashrrev_i32_e32 v4, 1, v4
|
||||
v_and_b32_e32 v4, 0xff, v4
|
||||
v_or_b32_e32 v4, v4, v3
|
||||
v_xor_b32_e32 v4, v4, v2
|
||||
v_sub_nc_u32_e32 v4, v4, v3
|
||||
v_subrev_nc_u32_e32 v4, v4, v2
|
||||
v_mul_u32_u24_e32 v4, v4, v3
|
||||
v_min_u32_e32 v4, v4, v2
|
||||
v_max_u32_e32 v4, v4, v3
|
||||
v_mul_lo_u32 v4, v4, v2
|
||||
v_mul_hi_u32 v4, v4, s25
|
||||
v_lshlrev_b32_e64 v4, s24, v4
|
||||
v_add_f32_e32 v5, 0.5, v2
|
||||
v_mul_f32_e32 v5, 0x3e800000, v5
|
||||
v_sub_f32_e32 v5, v5, v3
|
||||
v_subrev_f32_e32 v5, v5, v3
|
||||
v_max_f32_e32 v5, v5, v2
|
||||
v_min_f32_e32 v5, v5, v3
|
||||
v_add_f32_e64 v5, v5, -v2
|
||||
v_mul_f32_e64 v5, -v5, v3
|
||||
v_sub_f32_e64 v5, v5, v2
|
||||
v_max_f32_e64 v5, v5, s21
|
||||
v_fmac_f32_e32 v5, v2, v3
|
||||
v_rcp_f32_e32 v6, v5
|
||||
v_rsq_f32_e32 v6, v6
|
||||
v_sqrt_f32_e32 v6, v6
|
||||
v_floor_f32_e32 v6, v6
|
||||
v_fract_f32_e32 v6, v6
|
||||
v_exp_f32_e32 v6, v6
|
||||
v_log_f32_e32 v6, v6
|
||||
v_trunc_f32_e32 v6, v6
|
||||
v_rndne_f32_e32 v6, v6
|
||||
v_ceil_f32_e32 v6, v6
|
||||
v_sin_f32_e32 v6, v6
|
||||
v_cos_f32_e32 v6, v6
|
||||
v_rcp_f32_e64 v6, -v6
|
||||
v_cvt_f32_u32_e32 v7, v4
|
||||
v_cvt_f32_i32_e32 v7, v4
|
||||
v_cvt_i32_f32_e32 v8, v7
|
||||
v_med3_f32 v7, v7, 0, 1.0
|
||||
v_fma_f32 v7, -v7, v2, 1.0
|
||||
v_mul_legacy_f32_e32 v7, v7, v3
|
||||
v_cvt_pkrtz_f16_f32_e32 v9, v7, v6
|
||||
v_fma_mixlo_f16 v10, v9, v2, v3 op_sel_hi:[1,0,0]
|
||||
v_fma_mixhi_f16 v10, v9, v9, v10 op_sel_hi:[1,1,1]
|
||||
v_mov_b32_e32 v11, s23
|
||||
v_add_nc_u32_e32 v11, v11, v8
|
||||
exp mrt0, v9, v9, v10, v10 done compr vm
|
||||
s_endpgm
|
||||
"""
|
||||
|
||||
# A VS without the fetch subroutine: vertex buffers through s[0:1], typed buffer loads, and an
|
||||
# indexed load from a buffer bound through the root table.
|
||||
BUFFERS_VS = """
|
||||
s_load_dwordx4 s[12:15], s[0:1], 0x0
|
||||
s_load_dwordx4 s[16:19], s[0:1], 0x10
|
||||
s_load_dwordx4 s[20:23], s[8:9], 0x20
|
||||
v_add_nc_u32_e32 v1, s2, v0
|
||||
s_waitcnt lgkmcnt(0)
|
||||
buffer_load_dwordx2 v[2:3], v1, s[12:15], 0 idxen
|
||||
tbuffer_load_format_xyzw v[4:7], v1, s[16:19], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen offset:8
|
||||
buffer_load_dwordx3 v[8:10], v1, s[12:15], 0 idxen offset:8
|
||||
buffer_load_dwordx4 v[12:15], v0, s[20:23], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
v_mov_b32_e32 v11, 1.0
|
||||
exp pos0, v2, v3, v8, v11 done
|
||||
exp param0, v4, v5, v6, v7
|
||||
exp param1, v12, v13, v14, v15
|
||||
s_endpgm
|
||||
"""
|
||||
BUFFERS_PS = """
|
||||
v_interp_mov_f32_e32 v2, p0, attr1.x
|
||||
v_interp_mov_f32_e32 v3, p0, attr1.w
|
||||
v_interp_p1_f32_e32 v4, v0, attr0.z
|
||||
v_interp_p2_f32_e32 v4, v1, attr0.z
|
||||
exp mrt0, v2, v3, v4, off done vm
|
||||
s_endpgm
|
||||
"""
|
||||
|
||||
CASES = [("textured", TEXTURED_VS, TEXTURED_PS), ("alu", ALU_VS, ALU_PS), ("buffers", BUFFERS_VS, BUFFERS_PS)]
|
||||
|
||||
|
||||
def assemble(llvm_mc, text):
|
||||
r = subprocess.run([llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "-show-encoding"], input=text,
|
||||
capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
sys.exit("llvm-mc failed:\n" + r.stderr)
|
||||
data = bytearray()
|
||||
for line in r.stdout.splitlines():
|
||||
if "encoding:" in line:
|
||||
data += bytes(int(b, 16) for b in line.split("encoding:")[1].strip().strip("[]").split(","))
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
|
||||
a = ap.parse_args()
|
||||
translate.LLVM_MC = a.llvm_mc
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
for name, vs_asm, ps_asm in CASES:
|
||||
vs, ps = assemble(a.llvm_mc, vs_asm), assemble(a.llvm_mc, ps_asm)
|
||||
vt, pt = translate.Translator("vs"), translate.Translator("ps")
|
||||
vt.run(translate.disassemble(vs))
|
||||
pt.run(translate.disassemble(ps))
|
||||
vs_src, params = translate.build_vs(vt)
|
||||
ps_src = translate.build_ps(pt, params)
|
||||
il = ""
|
||||
if vt.fetch_call:
|
||||
il += "FETCH %d\n" % (max(vt.fetch_attrs) + 1 if vt.fetch_attrs else 0)
|
||||
for sem, fmt, slot, off, n, kind in vt.inputs:
|
||||
il += "ATTR %d %d %d %d\n" % (sem, translate.DXGI[fmt], slot, off)
|
||||
for cb in sorted(vt.cbs | pt.cbs):
|
||||
il += "USE CB %d\n" % cb
|
||||
for tex in sorted(vt.textures | pt.textures):
|
||||
il += "USE TEX %d\n" % tex
|
||||
base = os.path.join(OUT, name)
|
||||
for suffix, blob in ((".vs.hex", vs), (".ps.hex", ps)):
|
||||
words = [int.from_bytes(blob[i:i + 4], "little") for i in range(0, len(blob), 4)]
|
||||
open(base + suffix, "w").write(" ".join("%08x" % w for w in words) + "\n")
|
||||
open(base + ".vs.hlsl", "w").write(vs_src)
|
||||
open(base + ".ps.hlsl", "w").write(ps_src)
|
||||
open(base + ".il", "w").write(il)
|
||||
print("%s: VS %d words, PS %d words" % (name, len(vs) // 4, len(ps) // 4))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,930 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Experimental RDNA 2 (gfx1030) -> HLSL translator for straight-line console VS/PS pairs.
|
||||
|
||||
Input: the VS and PS of a console graphics pipeline, each either a raw GPU instruction blob
|
||||
(from a deserialized pipeline) or a console shader container (DXBC with an XBCH record).
|
||||
Output, in --out: <vs>_<ps>.vs.hlsl / .ps.hlsl, compiled .vs.dxil / .ps.dxil (when --dxc is
|
||||
given), and <vs>_<ps>.il, the input layout the shim creates the host pipeline with.
|
||||
|
||||
Reference implementation for shader-transpiler/crates/gfx10-translate, which replaces it: the
|
||||
crate's golden tests compare against this script's output (see that crate's README).
|
||||
|
||||
Model (inferences from the console compiler's listings and the target build's code, AGENTS.md
|
||||
section 6):
|
||||
* Code starts after a header of 12-byte `v_nop` + literal records (VOP3 word top half 0xD580).
|
||||
* VS user data: s[0:1] = vertex-buffer descriptor table (16-byte V#s), s2 = base vertex.
|
||||
Both stages: s8 = 32-bit pointer to root parameter 0's descriptor table (32-byte entries).
|
||||
* A buffer V# loaded from the root table is a constant buffer; an 8-dword T# is a texture.
|
||||
* PS v0:v1 are barycentrics; `v_interp_p1/p2 ... attrN.c` is attribute N, component c.
|
||||
* VS `exp paramN` pairs with PS `attrN`; `exp pos0` is the position.
|
||||
HLSL resources use register space 100 (+ root parameter index); the shim widens each title root
|
||||
signature with overlapping ranges in that space so table entry k is register k.
|
||||
|
||||
Only straight-line code with the instructions below is accepted; anything else fails loudly.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import zlib
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
LLVM_MC = os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc")
|
||||
|
||||
DXGI = {"R32_UINT": 42, "R32G32_UINT": 17, "R32G32B32_UINT": 7, "R32G32B32A32_UINT": 3,
|
||||
"R8G8B8A8_UNORM": 28, "R16G16_FLOAT": 34, "R16G16B16A16_FLOAT": 10, "R32G32_FLOAT": 16}
|
||||
TBUF_FMT = {"BUF_FMT_8_8_8_8_UNORM": ("R8G8B8A8_UNORM", 4, "float"),
|
||||
"BUF_FMT_16_16_FLOAT": ("R16G16_FLOAT", 2, "float"),
|
||||
"BUF_FMT_16_16_16_16_FLOAT": ("R16G16B16A16_FLOAT", 4, "float"),
|
||||
"BUF_FMT_32_32_FLOAT": ("R32G32_FLOAT", 2, "float")}
|
||||
|
||||
|
||||
class Unsupported(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def container_code(blob):
|
||||
"""The GPU code of one stage from a console shader container.
|
||||
|
||||
A container is a DXBC file whose DXIL part carries no bitcode; the console code is in an
|
||||
`XBCH` record: magic, version, compressed size (u64), uncompressed size (u64), then a zlib
|
||||
stream. It inflates to an `FSSM` block: a 16-byte header (magic, version, size), then
|
||||
offsets relative to the end of that header. One of the per-stage slots at 0x18..0x78 is not
|
||||
0xDEADBEEF filler and locates the stage record, whose first two u64 fields are the code
|
||||
offset and the code size. (Layout inferred from containers of a project-authorized build.)
|
||||
"""
|
||||
at = blob.find(b"XBCH")
|
||||
if at < 0:
|
||||
raise Unsupported("container has no XBCH record")
|
||||
csize, usize = struct.unpack_from("<QQ", blob, at + 8)
|
||||
fssm = zlib.decompress(blob[at + 24:at + 24 + csize])
|
||||
if len(fssm) != usize or fssm[:4] != b"FSSM":
|
||||
raise Unsupported("XBCH record does not inflate to an FSSM block")
|
||||
base = 16
|
||||
record = None
|
||||
for slot in range(0x18, 0x78, 8):
|
||||
(v,) = struct.unpack_from("<Q", fssm, slot)
|
||||
if v != 0xDEADBEEFDEADBEEF:
|
||||
record = base + v
|
||||
break
|
||||
if record is None:
|
||||
raise Unsupported("FSSM block has no stage record")
|
||||
code_off, code_size = struct.unpack_from("<QQ", fssm, record)
|
||||
code = fssm[base + code_off:base + code_off + code_size]
|
||||
if len(code) < 12 or struct.unpack_from("<I", code, 0)[0] >> 16 != 0xD580:
|
||||
raise Unsupported("stage code does not start with the expected header records")
|
||||
return code
|
||||
|
||||
|
||||
def code_words(blob):
|
||||
if blob[:4] == b"DXBC":
|
||||
blob = container_code(blob)
|
||||
off = 0
|
||||
while off + 12 <= len(blob) and struct.unpack_from("<I", blob, off)[0] >> 16 == 0xD580:
|
||||
off += 12
|
||||
return blob[off:]
|
||||
|
||||
|
||||
def disassemble(blob):
|
||||
body = code_words(blob)
|
||||
text = " ".join("0x%02x" % b for b in body)
|
||||
r = subprocess.run([LLVM_MC, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
|
||||
capture_output=True, text=True)
|
||||
out = []
|
||||
for line in r.stdout.splitlines():
|
||||
line = line.split(";")[0].strip()
|
||||
if not line or line.startswith("."):
|
||||
continue
|
||||
out.append(line)
|
||||
if line == "s_endpgm":
|
||||
break
|
||||
if "s_endpgm" not in out:
|
||||
raise Unsupported("no s_endpgm in decoded code")
|
||||
return out
|
||||
|
||||
|
||||
def split_ops(rest):
|
||||
ops, depth, cur = [], 0, ""
|
||||
for ch in rest:
|
||||
if ch in "[(":
|
||||
depth += 1
|
||||
elif ch in "])":
|
||||
depth -= 1
|
||||
if ch == "," and depth == 0:
|
||||
ops.append(cur.strip())
|
||||
cur = ""
|
||||
else:
|
||||
cur += ch
|
||||
if cur.strip():
|
||||
ops.append(cur.strip())
|
||||
return ops
|
||||
|
||||
|
||||
def reg_range(op):
|
||||
m = re.fullmatch(r"([sv])\[(\d+):(\d+)\]", op)
|
||||
if m:
|
||||
return m.group(1), int(m.group(2)), int(m.group(3))
|
||||
m = re.fullmatch(r"([sv])(\d+)", op)
|
||||
if m:
|
||||
return m.group(1), int(m.group(2)), int(m.group(2))
|
||||
return None
|
||||
|
||||
|
||||
class Translator:
|
||||
def __init__(self, stage):
|
||||
self.stage = stage
|
||||
self.lines = []
|
||||
self.sprov = {} # sgpr -> provenance tuple
|
||||
self.cbs = set() # table indices used as constant buffers
|
||||
self.textures = set()
|
||||
self.inputs = [] # VS: (semantic index, fmt, slot, offset, ncomp, kind)
|
||||
self.attrs = set() # PS attribute indices read
|
||||
self.exports = {} # name -> list of 4 expressions
|
||||
self.used_v = set()
|
||||
self.used_s = set()
|
||||
self.written_v = set()
|
||||
self.fetch_call = False # VS: attributes arrive in v4.. from the vertex-fetch subroutine
|
||||
self.fetch_attrs = set() # attribute indices read that way
|
||||
self.nexp = 0
|
||||
self.ntmp = 0
|
||||
self.tmps = []
|
||||
|
||||
# ---- operands -------------------------------------------------------------
|
||||
def src(self, op, as_float=False):
|
||||
"""HLSL expression (uint) for a 32-bit source operand."""
|
||||
neg = False
|
||||
if op.startswith("-") and not re.fullmatch(r"-\d+(\.\d+)?", op):
|
||||
neg, op = True, op[1:]
|
||||
m = re.fullmatch(r"neg\((.+)\)", op)
|
||||
if m:
|
||||
neg, op = True, m.group(1)
|
||||
r = reg_range(op)
|
||||
if r and r[1] == r[2]:
|
||||
kind, n, _ = r
|
||||
(self.used_v if kind == "v" else self.used_s).add(n)
|
||||
if kind == "v" and self.fetch_call and n >= 4 and n not in self.written_v:
|
||||
self.fetch_attrs.add((n - 4) // 4)
|
||||
e = "%s%d" % (kind, n)
|
||||
elif re.fullmatch(r"-?\d+\.\d+", op):
|
||||
e = "asuint(%sf)" % op
|
||||
elif re.fullmatch(r"0x[0-9a-fA-F]+", op):
|
||||
e = "0x%xu" % int(op, 16)
|
||||
elif re.fullmatch(r"-?\d+", op):
|
||||
v = int(op)
|
||||
e = "%du" % (v & 0xFFFFFFFF)
|
||||
else:
|
||||
raise Unsupported("operand %r" % op)
|
||||
if neg:
|
||||
e = "(asuint(-asfloat(%s)))" % e
|
||||
return "asfloat(%s)" % e if as_float else e
|
||||
|
||||
def dst(self, op):
|
||||
r = reg_range(op)
|
||||
if not r or r[1] != r[2]:
|
||||
raise Unsupported("destination %r" % op)
|
||||
(self.used_v if r[0] == "v" else self.used_s).add(r[1])
|
||||
if r[0] == "v":
|
||||
self.written_v.add(r[1])
|
||||
return "%s%d" % (r[0], r[1])
|
||||
|
||||
def emit(self, s):
|
||||
self.lines.append(" " + s)
|
||||
|
||||
# ---- instructions -----------------------------------------------------------
|
||||
def run(self, insts):
|
||||
ignore = re.compile(r"^(s_waitcnt|s_clause|s_inst_prefetch|s_setprio|s_nop|s_wqm_b64|s_endpgm|v_nop)\b")
|
||||
for line in insts:
|
||||
if ignore.match(line):
|
||||
continue
|
||||
parts = line.split(None, 1)
|
||||
op, rest = parts[0], parts[1] if len(parts) > 1 else ""
|
||||
mods = ""
|
||||
ops = split_ops(rest)
|
||||
# modifiers after operands (e.g. "0 idxen offset:12", "dmask:0xf dim:...")
|
||||
if op.endswith("_e64") and re.search(r"\b(clamp|mul:|div:|op_sel|abs\()", rest):
|
||||
raise Unsupported("modifier in %r" % line)
|
||||
handler = getattr(self, "i_" + op, None)
|
||||
if handler is None:
|
||||
raise Unsupported("instruction %r" % line)
|
||||
handler(ops, line)
|
||||
|
||||
def exec_write(self, ops):
|
||||
return ops and ops[0].startswith("exec")
|
||||
|
||||
def i_s_mov_b32(self, ops, line):
|
||||
if ops[0] == "m0":
|
||||
return
|
||||
r = reg_range(ops[0])
|
||||
s = reg_range(ops[1])
|
||||
if s and s[0] == "s":
|
||||
self.sprov[r[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
|
||||
elif re.fullmatch(r"-?(0x[0-9a-fA-F]+|\d+)", ops[1]):
|
||||
self.sprov[r[1]] = ("imm", int(ops[1], 0) & 0xFFFFFFFF)
|
||||
else:
|
||||
self.sprov[r[1]] = ("unknown",)
|
||||
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
|
||||
|
||||
def i_s_swappc_b64(self, ops, line):
|
||||
# The call to the vertex-fetch subroutine the console runtime builds from the pipeline's
|
||||
# input layout: on return, input element k is in v[4+4k : 7+4k] (observed: three-element
|
||||
# layouts read v4..v15 in groups of four). The host input assembler does the fetch.
|
||||
if self.stage != "vs" or self.lines or ops != ["s[4:5]", "s[4:5]"]:
|
||||
raise Unsupported(line)
|
||||
self.fetch_call = True
|
||||
|
||||
def i_s_mov_b64(self, ops, line):
|
||||
if ops[0] == "exec" or ops[1] == "exec":
|
||||
return
|
||||
d = reg_range(ops[0])
|
||||
s = reg_range(ops[1])
|
||||
if s:
|
||||
self.sprov[d[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
|
||||
self.sprov[d[1] + 1] = self.sprov.get(s[1] + 1, ("sgpr", s[1] + 1))
|
||||
else:
|
||||
v = int(ops[1], 0)
|
||||
self.sprov[d[1]] = ("imm", v & 0xFFFFFFFF)
|
||||
self.sprov[d[1] + 1] = ("imm", (v >> 32) & 0xFFFFFFFF)
|
||||
|
||||
def i_s_and_b64(self, ops, line):
|
||||
# `s_and_b64 exec, exec, s[n:n+1]` restores the execution mask saved before s_wqm_b64
|
||||
# (helper-pixel bookkeeping); it has no HLSL counterpart.
|
||||
if ops[0] != "exec" or ops[1] != "exec":
|
||||
raise Unsupported(line)
|
||||
|
||||
def i_s_movk_i32(self, ops, line):
|
||||
r = reg_range(ops[0])
|
||||
self.sprov[r[1]] = ("imm", int(ops[1], 0) & 0xFFFFFFFF)
|
||||
self.emit("%s = %du;" % (self.dst(ops[0]), int(ops[1], 0) & 0xFFFFFFFF))
|
||||
|
||||
def i_s_lshl_b32(self, ops, line):
|
||||
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
|
||||
self.emit("%s = %s << (%s & 31u);" % (self.dst(ops[0]), self.src(ops[1]), self.src(ops[2])))
|
||||
|
||||
def i_s_bfe_u32(self, ops, line):
|
||||
pass # masks the high half of a copied table pointer; provenance is unchanged
|
||||
|
||||
def table_of(self, base):
|
||||
b = reg_range(base)
|
||||
p = self.sprov.get(b[1], ("sgpr", b[1]))
|
||||
if p == ("sgpr", 0) and self.stage == "vs":
|
||||
return "vbtable"
|
||||
if p == ("sgpr", 8):
|
||||
return "root0"
|
||||
raise Unsupported("descriptor load from %r (provenance %r)" % (base, p))
|
||||
|
||||
def smem_load(self, ops, line, ndw):
|
||||
d = reg_range(ops[0])
|
||||
try:
|
||||
table = self.table_of(ops[1])
|
||||
except Unsupported:
|
||||
if ndw != 4:
|
||||
raise
|
||||
for i in range(ndw):
|
||||
self.sprov[d[1] + i] = ("smp", ops[1])
|
||||
return
|
||||
off = 0 if ops[2] == "null" else int(ops[2], 0)
|
||||
if table == "vbtable":
|
||||
prov = ("vb", off // 16)
|
||||
elif ndw == 4:
|
||||
prov = ("cb", off // 32)
|
||||
elif ndw == 8:
|
||||
prov = ("tex", off // 32)
|
||||
else:
|
||||
raise Unsupported(line)
|
||||
for i in range(ndw):
|
||||
self.sprov[d[1] + i] = prov
|
||||
|
||||
def i_s_load_dwordx4(self, ops, line):
|
||||
self.smem_load(ops, line, 4)
|
||||
|
||||
def i_s_load_dwordx8(self, ops, line):
|
||||
self.smem_load(ops, line, 8)
|
||||
|
||||
def s_buffer_load(self, ops, line, ndw):
|
||||
d = reg_range(ops[0])
|
||||
desc = reg_range(ops[1])
|
||||
p = self.sprov.get(desc[1])
|
||||
if not p or p[0] != "cb":
|
||||
raise Unsupported("s_buffer_load from %r" % (p,))
|
||||
cb = p[1]
|
||||
self.cbs.add(cb)
|
||||
off = 0 if ops[2] == "null" else int(ops[2], 0)
|
||||
for i in range(ndw):
|
||||
word = off // 4 + i
|
||||
self.sprov[d[1] + i] = ("cbword", cb, word)
|
||||
self.emit("s%d = cb%d_word(%d);" % (d[1] + i, cb, word))
|
||||
self.used_s.add(d[1] + i)
|
||||
|
||||
def i_s_buffer_load_dword(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 1)
|
||||
|
||||
def i_s_buffer_load_dwordx2(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 2)
|
||||
|
||||
def i_s_buffer_load_dwordx4(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 4)
|
||||
|
||||
def i_s_buffer_load_dwordx8(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 8)
|
||||
|
||||
def i_s_buffer_load_dwordx16(self, ops, line):
|
||||
self.s_buffer_load(ops, line, 16)
|
||||
|
||||
# vertex fetch -> input layout element
|
||||
def vb_slot(self, op):
|
||||
p = self.sprov.get(reg_range(op)[1])
|
||||
if not p or p[0] != "vb":
|
||||
raise Unsupported("vertex fetch through %r" % (p,))
|
||||
return p[1]
|
||||
|
||||
def fetch(self, ops, line, ncomp, fmt, kind):
|
||||
if "idxen" not in line or "offen" in line:
|
||||
raise Unsupported(line)
|
||||
d = reg_range(ops[0])
|
||||
p = self.sprov.get(reg_range(ops[2])[1])
|
||||
if p and p[0] == "cb" and "offset:" not in line:
|
||||
# An indexed load from a buffer bound through the root table: element i is 16 bytes.
|
||||
cb = p[1]
|
||||
self.cbs.add(cb)
|
||||
idx = self.src(ops[1])
|
||||
for i in range(d[2] - d[1] + 1):
|
||||
self.emit("t%d_%d = cb%d[%s].%s;" % (self.ntmp, i, cb, idx, "xyzw"[i]))
|
||||
for i in range(d[2] - d[1] + 1):
|
||||
self.emit("%s = t%d_%d;" % (self.dst("v%d" % (d[1] + i)), self.ntmp, i))
|
||||
self.tmps.append((self.ntmp, d[2] - d[1] + 1))
|
||||
self.ntmp += 1
|
||||
return
|
||||
slot = self.vb_slot(ops[2])
|
||||
m = re.search(r"offset:(\d+)", line)
|
||||
off = int(m.group(1)) if m else 0
|
||||
sem = len(self.inputs)
|
||||
self.inputs.append((sem, fmt, slot, off, ncomp, kind))
|
||||
comps = "xyzw"
|
||||
for i in range(d[2] - d[1] + 1):
|
||||
src = "in%d.%s" % (sem, comps[i])
|
||||
self.emit("v%d = %s;" % (d[1] + i, "asuint(%s)" % src if kind == "float" else src))
|
||||
self.used_v.add(d[1] + i)
|
||||
|
||||
def i_buffer_load_dword(self, ops, line):
|
||||
self.fetch(ops, line, 1, "R32_UINT", "uint")
|
||||
|
||||
def i_buffer_load_dwordx2(self, ops, line):
|
||||
self.fetch(ops, line, 2, "R32G32_UINT", "uint")
|
||||
|
||||
def i_buffer_load_dwordx3(self, ops, line):
|
||||
self.fetch(ops, line, 3, "R32G32B32_UINT", "uint")
|
||||
|
||||
def i_buffer_load_dwordx4(self, ops, line):
|
||||
self.fetch(ops, line, 4, "R32G32B32A32_UINT", "uint")
|
||||
|
||||
def i_tbuffer_load_format_xyzw(self, ops, line):
|
||||
m = re.search(r"format:\[(\w+)\]", line)
|
||||
if not m or m.group(1) not in TBUF_FMT:
|
||||
raise Unsupported(line)
|
||||
fmt, n, kind = TBUF_FMT[m.group(1)]
|
||||
self.fetch(ops, line, 4, fmt, kind)
|
||||
|
||||
# ALU
|
||||
def vop2f(self, ops, expr):
|
||||
a, b = self.src(ops[1], True), self.src(ops[2], True)
|
||||
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr % (a, b)))
|
||||
|
||||
def i_v_mul_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "%s * %s")
|
||||
|
||||
i_v_mul_f32_e64 = i_v_mul_f32_e32
|
||||
|
||||
def i_v_add_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "%s + %s")
|
||||
|
||||
i_v_add_f32_e64 = i_v_add_f32_e32
|
||||
|
||||
def i_v_sub_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "%s - %s")
|
||||
|
||||
def i_v_max_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "max(%s, %s)")
|
||||
|
||||
def i_v_min_f32_e32(self, ops, line):
|
||||
self.vop2f(ops, "min(%s, %s)")
|
||||
|
||||
def i_v_fmac_f32_e32(self, ops, line):
|
||||
d = self.dst(ops[0])
|
||||
self.emit("%s = asuint(mad(%s, %s, asfloat(%s)));" % (d, self.src(ops[1], True), self.src(ops[2], True), d))
|
||||
|
||||
# ---- simple ALU, generated from (name, expression) tables ---------------------------------
|
||||
def _vop2u(self, ops, expr):
|
||||
a, b = self.src(ops[1]), self.src(ops[2])
|
||||
self.emit("%s = %s;" % (self.dst(ops[0]), expr.format(a=a, b=b)))
|
||||
|
||||
def _vop2f(self, ops, expr):
|
||||
a, b = self.src(ops[1], True), self.src(ops[2], True)
|
||||
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr.format(a=a, b=b)))
|
||||
|
||||
def _vop1f(self, ops, expr):
|
||||
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr.format(a=self.src(ops[1], True))))
|
||||
|
||||
def _sop2(self, ops, expr):
|
||||
a, b = self.src(ops[1]), self.src(ops[2])
|
||||
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
|
||||
self.emit("%s = %s;" % (self.dst(ops[0]), expr.format(a=a, b=b)))
|
||||
|
||||
def i_v_lshlrev_b32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({b} << ({a} & 31u))')
|
||||
|
||||
def i_v_lshlrev_b32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({b} << ({a} & 31u))')
|
||||
|
||||
def i_v_lshlrev_b32(self, ops, line):
|
||||
self._vop2u(ops, '({b} << ({a} & 31u))')
|
||||
|
||||
def i_v_lshrrev_b32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({b} >> ({a} & 31u))')
|
||||
|
||||
def i_v_lshrrev_b32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({b} >> ({a} & 31u))')
|
||||
|
||||
def i_v_lshrrev_b32(self, ops, line):
|
||||
self._vop2u(ops, '({b} >> ({a} & 31u))')
|
||||
|
||||
def i_v_ashrrev_i32_e32(self, ops, line):
|
||||
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
|
||||
|
||||
def i_v_ashrrev_i32_e64(self, ops, line):
|
||||
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
|
||||
|
||||
def i_v_ashrrev_i32(self, ops, line):
|
||||
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
|
||||
|
||||
def i_v_and_b32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({a} & {b})')
|
||||
|
||||
def i_v_and_b32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({a} & {b})')
|
||||
|
||||
def i_v_and_b32(self, ops, line):
|
||||
self._vop2u(ops, '({a} & {b})')
|
||||
|
||||
def i_v_or_b32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({a} | {b})')
|
||||
|
||||
def i_v_or_b32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({a} | {b})')
|
||||
|
||||
def i_v_or_b32(self, ops, line):
|
||||
self._vop2u(ops, '({a} | {b})')
|
||||
|
||||
def i_v_xor_b32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({a} ^ {b})')
|
||||
|
||||
def i_v_xor_b32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({a} ^ {b})')
|
||||
|
||||
def i_v_xor_b32(self, ops, line):
|
||||
self._vop2u(ops, '({a} ^ {b})')
|
||||
|
||||
def i_v_sub_nc_u32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({a} - {b})')
|
||||
|
||||
def i_v_sub_nc_u32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({a} - {b})')
|
||||
|
||||
def i_v_sub_nc_u32(self, ops, line):
|
||||
self._vop2u(ops, '({a} - {b})')
|
||||
|
||||
def i_v_subrev_nc_u32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({b} - {a})')
|
||||
|
||||
def i_v_subrev_nc_u32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({b} - {a})')
|
||||
|
||||
def i_v_subrev_nc_u32(self, ops, line):
|
||||
self._vop2u(ops, '({b} - {a})')
|
||||
|
||||
def i_v_mul_u32_u24_e32(self, ops, line):
|
||||
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
|
||||
|
||||
def i_v_mul_u32_u24_e64(self, ops, line):
|
||||
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
|
||||
|
||||
def i_v_mul_u32_u24(self, ops, line):
|
||||
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
|
||||
|
||||
def i_v_min_u32_e32(self, ops, line):
|
||||
self._vop2u(ops, 'min({a}, {b})')
|
||||
|
||||
def i_v_min_u32_e64(self, ops, line):
|
||||
self._vop2u(ops, 'min({a}, {b})')
|
||||
|
||||
def i_v_min_u32(self, ops, line):
|
||||
self._vop2u(ops, 'min({a}, {b})')
|
||||
|
||||
def i_v_max_u32_e32(self, ops, line):
|
||||
self._vop2u(ops, 'max({a}, {b})')
|
||||
|
||||
def i_v_max_u32_e64(self, ops, line):
|
||||
self._vop2u(ops, 'max({a}, {b})')
|
||||
|
||||
def i_v_max_u32(self, ops, line):
|
||||
self._vop2u(ops, 'max({a}, {b})')
|
||||
|
||||
def i_v_mul_lo_u32_e32(self, ops, line):
|
||||
self._vop2u(ops, '({a} * {b})')
|
||||
|
||||
def i_v_mul_lo_u32_e64(self, ops, line):
|
||||
self._vop2u(ops, '({a} * {b})')
|
||||
|
||||
def i_v_mul_lo_u32(self, ops, line):
|
||||
self._vop2u(ops, '({a} * {b})')
|
||||
|
||||
def i_v_mul_hi_u32_e32(self, ops, line):
|
||||
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
|
||||
|
||||
def i_v_mul_hi_u32_e64(self, ops, line):
|
||||
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
|
||||
|
||||
def i_v_mul_hi_u32(self, ops, line):
|
||||
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
|
||||
|
||||
def i_v_max_f32_e64(self, ops, line):
|
||||
self._vop2f(ops, 'max({a}, {b})')
|
||||
|
||||
def i_v_min_f32_e64(self, ops, line):
|
||||
self._vop2f(ops, 'min({a}, {b})')
|
||||
|
||||
def i_v_sub_f32_e64(self, ops, line):
|
||||
self._vop2f(ops, '({a} - {b})')
|
||||
|
||||
def i_v_subrev_f32_e32(self, ops, line):
|
||||
self._vop2f(ops, '({b} - {a})')
|
||||
|
||||
def i_v_subrev_f32_e64(self, ops, line):
|
||||
self._vop2f(ops, '({b} - {a})')
|
||||
|
||||
def i_v_rcp_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, '(1.0f / {a})')
|
||||
|
||||
def i_v_rcp_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, '(1.0f / {a})')
|
||||
|
||||
def i_v_rsq_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'rsqrt({a})')
|
||||
|
||||
def i_v_rsq_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'rsqrt({a})')
|
||||
|
||||
def i_v_sqrt_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'sqrt({a})')
|
||||
|
||||
def i_v_sqrt_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'sqrt({a})')
|
||||
|
||||
def i_v_floor_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'floor({a})')
|
||||
|
||||
def i_v_floor_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'floor({a})')
|
||||
|
||||
def i_v_fract_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'frac({a})')
|
||||
|
||||
def i_v_fract_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'frac({a})')
|
||||
|
||||
def i_v_exp_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'exp2({a})')
|
||||
|
||||
def i_v_exp_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'exp2({a})')
|
||||
|
||||
def i_v_log_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'log2({a})')
|
||||
|
||||
def i_v_log_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'log2({a})')
|
||||
|
||||
def i_v_trunc_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'trunc({a})')
|
||||
|
||||
def i_v_trunc_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'trunc({a})')
|
||||
|
||||
def i_v_rndne_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'round({a})')
|
||||
|
||||
def i_v_rndne_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'round({a})')
|
||||
|
||||
def i_v_ceil_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'ceil({a})')
|
||||
|
||||
def i_v_ceil_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'ceil({a})')
|
||||
|
||||
def i_v_cvt_f32_u32_e32(self, ops, line):
|
||||
self._vop1f(ops, '(float)asuint({a})')
|
||||
|
||||
def i_v_cvt_f32_u32_e64(self, ops, line):
|
||||
self._vop1f(ops, '(float)asuint({a})')
|
||||
|
||||
def i_v_cvt_f32_i32_e32(self, ops, line):
|
||||
self._vop1f(ops, '(float)asint({a})')
|
||||
|
||||
def i_v_cvt_f32_i32_e64(self, ops, line):
|
||||
self._vop1f(ops, '(float)asint({a})')
|
||||
|
||||
def i_v_sin_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'sin({a} * 6.2831853f)')
|
||||
|
||||
def i_v_sin_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'sin({a} * 6.2831853f)')
|
||||
|
||||
def i_v_cos_f32_e32(self, ops, line):
|
||||
self._vop1f(ops, 'cos({a} * 6.2831853f)')
|
||||
|
||||
def i_v_cos_f32_e64(self, ops, line):
|
||||
self._vop1f(ops, 'cos({a} * 6.2831853f)')
|
||||
|
||||
def i_s_or_b32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, '({a} | {b})')
|
||||
|
||||
def i_s_and_b32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, '({a} & {b})')
|
||||
|
||||
def i_s_xor_b32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, '({a} ^ {b})')
|
||||
|
||||
def i_s_mul_i32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, '({a} * {b})')
|
||||
|
||||
def i_s_add_u32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, '({a} + {b})')
|
||||
|
||||
def i_s_sub_u32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, '({a} - {b})')
|
||||
|
||||
def i_s_lshr_b32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, '({a} >> ({b} & 31u))')
|
||||
|
||||
def i_s_min_u32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, 'min({a}, {b})')
|
||||
|
||||
def i_s_max_u32(self, ops, line):
|
||||
if ops[0].startswith('exec'):
|
||||
raise Unsupported(line)
|
||||
self._sop2(ops, 'max({a}, {b})')
|
||||
|
||||
def i_s_brev_b32(self, ops, line):
|
||||
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
|
||||
self.emit("%s = reversebits(%s);" % (self.dst(ops[0]), self.src(ops[1])))
|
||||
|
||||
def i_s_setreg_imm32_b32(self, ops, line):
|
||||
pass # mode register (rounding, denormals): the host defaults are used
|
||||
|
||||
def i_v_cvt_i32_f32_e32(self, ops, line):
|
||||
self.emit("%s = (uint)(int)%s;" % (self.dst(ops[0]), self.src(ops[1], True)))
|
||||
|
||||
def i_v_med3_f32(self, ops, line):
|
||||
a, b, c = (self.src(o, True) for o in ops[1:4])
|
||||
self.emit("%s = asuint(max(min(%s, %s), min(max(%s, %s), %s)));" % (self.dst(ops[0]), a, b, a, b, c))
|
||||
|
||||
def i_v_mul_legacy_f32_e32(self, ops, line):
|
||||
a, b = self.src(ops[1], True), self.src(ops[2], True)
|
||||
self.emit("%s = asuint((%s == 0.0f || %s == 0.0f) ? 0.0f : %s * %s);" % (self.dst(ops[0]), a, b, a, b))
|
||||
|
||||
i_v_mul_legacy_f32_e64 = i_v_mul_legacy_f32_e32
|
||||
|
||||
def i_v_cvt_pkrtz_f16_f32_e32(self, ops, line):
|
||||
a, b = self.src(ops[1], True), self.src(ops[2], True)
|
||||
self.emit("%s = f32tof16(%s) | (f32tof16(%s) << 16);" % (self.dst(ops[0]), a, b))
|
||||
|
||||
i_v_cvt_pkrtz_f16_f32_e64 = i_v_cvt_pkrtz_f16_f32_e32
|
||||
|
||||
def i_v_interp_mov_f32_e32(self, ops, line):
|
||||
m = re.fullmatch(r"attr(\d+)\.([xyzw])", ops[2])
|
||||
if not m:
|
||||
raise Unsupported(line)
|
||||
n = int(m.group(1))
|
||||
self.attrs.add(n)
|
||||
self.emit("%s = asuint(attr%d.%s);" % (self.dst(ops[0]), n, m.group(2)))
|
||||
|
||||
def i_v_fma_f32(self, ops, line):
|
||||
self.emit("%s = asuint(mad(%s, %s, %s));" % (self.dst(ops[0]), self.src(ops[1], True),
|
||||
self.src(ops[2], True), self.src(ops[3], True)))
|
||||
|
||||
def i_v_mov_b32_e32(self, ops, line):
|
||||
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
|
||||
|
||||
def i_v_add_nc_u32_e32(self, ops, line):
|
||||
# only the vertex-index computation uses it here; the index itself is the IA's job
|
||||
if self.stage == "vs":
|
||||
return
|
||||
self.emit("%s = %s + %s;" % (self.dst(ops[0]), self.src(ops[1]), self.src(ops[2])))
|
||||
|
||||
def fma_mix(self, ops, line, hi):
|
||||
m = re.search(r"op_sel_hi:\[(\d),(\d),(\d)\]", line)
|
||||
if "op_sel:" in line or not m:
|
||||
raise Unsupported(line)
|
||||
srcs = []
|
||||
for i, sel in enumerate(m.groups()):
|
||||
o = ops[1 + i].split()[0]
|
||||
neg = False
|
||||
mm = re.fullmatch(r"neg\((.+)\)", o)
|
||||
if mm:
|
||||
neg, o = True, mm.group(1)
|
||||
e = self.src(o)
|
||||
f = "f16tof32(%s & 0xffffu)" % e if sel == "1" else "asfloat(%s)" % e
|
||||
srcs.append("(-%s)" % f if neg else f)
|
||||
d = self.dst(ops[0])
|
||||
val = "f32tof16(mad(%s, %s, %s))" % tuple(srcs)
|
||||
if hi:
|
||||
self.emit("%s = (%s & 0xffffu) | (%s << 16);" % (d, d, val))
|
||||
else:
|
||||
self.emit("%s = (%s & 0xffff0000u) | %s;" % (d, d, val))
|
||||
|
||||
def i_v_fma_mixlo_f16(self, ops, line):
|
||||
self.fma_mix(ops, line, False)
|
||||
|
||||
def i_v_fma_mixhi_f16(self, ops, line):
|
||||
self.fma_mix(ops, line, True)
|
||||
|
||||
# PS interpolation
|
||||
def i_v_interp_p1_f32_e32(self, ops, line):
|
||||
pass
|
||||
|
||||
def i_v_interp_p2_f32_e32(self, ops, line):
|
||||
m = re.fullmatch(r"attr(\d+)\.([xyzw])", ops[2])
|
||||
if not m:
|
||||
raise Unsupported(line)
|
||||
n = int(m.group(1))
|
||||
self.attrs.add(n)
|
||||
self.emit("%s = asuint(attr%d.%s);" % (self.dst(ops[0]), n, m.group(2)))
|
||||
|
||||
def i_image_sample(self, ops, line):
|
||||
d = reg_range(ops[0])
|
||||
c = reg_range(ops[1])
|
||||
t = self.sprov.get(reg_range(ops[2])[1])
|
||||
m = re.search(r"dmask:(0x[0-9a-f]+)", line)
|
||||
if not t or t[0] != "tex" or "dim:SQ_RSRC_IMG_2D" not in line or not m:
|
||||
raise Unsupported(line)
|
||||
mask = int(m.group(1), 16)
|
||||
comps = [c_ for i, c_ in enumerate("xyzw") if mask & (1 << i)]
|
||||
if len(comps) != d[2] - d[1] + 1:
|
||||
raise Unsupported("dmask and destination size differ: " + line)
|
||||
self.textures.add(t[1])
|
||||
self.used_v.update([c[1], c[1] + 1])
|
||||
fn = "SampleLevel(smp0, float2(asfloat(v%d), asfloat(v%d)), 0)" if line.startswith("image_sample_lz") else \
|
||||
"Sample(smp0, float2(asfloat(v%d), asfloat(v%d)))"
|
||||
self.emit("{ float4 r = tex%d.%s;" % (t[1], fn % (c[1], c[1] + 1)))
|
||||
for i, comp in enumerate(comps):
|
||||
self.emit(" v%d = asuint(r.%s);" % (d[1] + i, comp))
|
||||
self.used_v.add(d[1] + i)
|
||||
self.emit("}")
|
||||
|
||||
i_image_sample_lz = i_image_sample
|
||||
|
||||
def i_exp(self, ops, line):
|
||||
target = ops[0]
|
||||
vals = [o.split()[0] for o in ops[1:5]]
|
||||
compr = " compr" in line
|
||||
if compr:
|
||||
a, b = self.src(vals[0]), self.src(vals[2])
|
||||
ex = ["f16tof32(%s & 0xffffu)" % a, "f16tof32(%s >> 16)" % a,
|
||||
"f16tof32(%s & 0xffffu)" % b, "f16tof32(%s >> 16)" % b]
|
||||
else:
|
||||
ex = ["0.0f" if v == "off" else self.src(v, True) for v in vals]
|
||||
# registers are reused after an export: take the values now
|
||||
name = "exp%d_%s" % (self.nexp, target)
|
||||
self.nexp += 1
|
||||
self.emit("float4 %s = float4(%s);" % (name, ", ".join(ex)))
|
||||
self.exports[target] = ["%s.%s" % (name, c) for c in "xyzw"]
|
||||
|
||||
# ---- output -----------------------------------------------------------------
|
||||
def resources(self):
|
||||
out = []
|
||||
for cb in sorted(self.cbs):
|
||||
out.append("cbuffer CB%d : register(b%d, space100) { uint4 cb%d[4096]; };" % (cb, cb, cb))
|
||||
out.append("uint cb%d_word(uint w) { return cb%d[w >> 2][w & 3]; }" % (cb, cb))
|
||||
for t in sorted(self.textures):
|
||||
out.append("Texture2D<float4> tex%d : register(t%d, space100);" % (t, t))
|
||||
if self.textures:
|
||||
out.append("SamplerState smp0 : register(s0, space100);")
|
||||
return out
|
||||
|
||||
def regs(self):
|
||||
decl = []
|
||||
for n in sorted(self.used_v):
|
||||
k = (n - 4) // 4
|
||||
if self.fetch_call and n >= 4 and k in self.fetch_attrs:
|
||||
decl.append("uint v%d = asuint(a%d.%s);" % (n, k, "xyzw"[(n - 4) % 4]))
|
||||
else:
|
||||
decl.append("uint v%d = 0;" % n)
|
||||
decl += ["uint s%d = 0;" % n for n in sorted(self.used_s)]
|
||||
for n, count in self.tmps:
|
||||
decl += ["uint t%d_%d = 0;" % (n, i) for i in range(count)]
|
||||
return [" " + d for d in decl]
|
||||
|
||||
|
||||
def build_vs(t):
|
||||
ins = ["float4 a%d : ATTR%d" % (k, k) for k in sorted(t.fetch_attrs)]
|
||||
for sem, fmt, slot, off, n, kind in t.inputs:
|
||||
ty = ("float%d" if kind == "float" else "uint%d") % n if n > 1 else ("float" if kind == "float" else "uint")
|
||||
ins.append("%s in%d : ATTR%d" % (ty, sem, sem))
|
||||
params = sorted(k for k in t.exports if k.startswith("param"))
|
||||
outs = ["float4 pos : SV_Position"] + ["float4 %s : PARAM%s" % (p, p[5:]) for p in params]
|
||||
src = t.resources()
|
||||
src.append("struct VSOut { %s; };" % "; ".join(outs))
|
||||
src.append("VSOut main(%s) {" % ", ".join(ins))
|
||||
src += t.regs() + t.lines
|
||||
src.append(" VSOut o;")
|
||||
pos = t.exports.get("pos0")
|
||||
if not pos:
|
||||
raise Unsupported("VS exports no position")
|
||||
src.append(" o.pos = float4(%s);" % ", ".join(pos))
|
||||
for p in params:
|
||||
src.append(" o.%s = float4(%s);" % (p, ", ".join(t.exports[p])))
|
||||
src.append(" return o;\n}")
|
||||
return "\n".join(src) + "\n", params
|
||||
|
||||
|
||||
def build_ps(t, vs_params):
|
||||
for a in t.attrs:
|
||||
if "param%d" % a not in vs_params:
|
||||
raise Unsupported("PS reads attr%d that the VS does not export" % a)
|
||||
ins = ["float4 pos : SV_Position"] + ["float4 attr%s : PARAM%s" % (p[5:], p[5:]) for p in vs_params]
|
||||
if "mrt0" not in t.exports:
|
||||
raise Unsupported("PS exports no mrt0")
|
||||
src = t.resources()
|
||||
src.append("float4 main(%s) : SV_Target0 {" % ", ".join(ins))
|
||||
src += t.regs() + t.lines
|
||||
src.append(" return float4(%s);\n}" % ", ".join(t.exports["mrt0"]))
|
||||
return "\n".join(src) + "\n"
|
||||
|
||||
|
||||
def fnv1a(data):
|
||||
h = 1469598103934665603
|
||||
for b in data:
|
||||
h = ((h ^ b) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
|
||||
return "%016x" % h
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("vs")
|
||||
ap.add_argument("ps")
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--dxc", help="command prefix that runs a Windows dxc.exe (e.g. a wine wrapper)")
|
||||
a = ap.parse_args()
|
||||
vsb, psb = open(a.vs, "rb").read(), open(a.ps, "rb").read()
|
||||
key = "%s_%s" % (fnv1a(vsb), fnv1a(psb))
|
||||
vt, pt = Translator("vs"), Translator("ps")
|
||||
vt.run(disassemble(vsb))
|
||||
pt.run(disassemble(psb))
|
||||
vs_src, params = build_vs(vt)
|
||||
ps_src = build_ps(pt, params)
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
base = os.path.join(a.out, key)
|
||||
open(base + ".vs.hlsl", "w").write(vs_src)
|
||||
open(base + ".ps.hlsl", "w").write(ps_src)
|
||||
with open(base + ".il", "w") as f:
|
||||
if vt.fetch_call:
|
||||
f.write("FETCH %d\n" % (max(vt.fetch_attrs) + 1 if vt.fetch_attrs else 0))
|
||||
for sem, fmt, slot, off, n, kind in vt.inputs:
|
||||
f.write("ATTR %d %d %d %d\n" % (sem, DXGI[fmt], slot, off))
|
||||
for cb in sorted(vt.cbs | pt.cbs):
|
||||
f.write("USE CB %d\n" % cb)
|
||||
for tex in sorted(vt.textures | pt.textures):
|
||||
f.write("USE TEX %d\n" % tex)
|
||||
if a.dxc:
|
||||
for st, prof in (("vs", "vs_6_0"), ("ps", "ps_6_0")):
|
||||
cmd = a.dxc.split() + ["-T", prof, "-E", "main", "-Fo", base + ".%s.dxil" % st, base + ".%s.hlsl" % st]
|
||||
r = subprocess.run(cmd, capture_output=True, text=True)
|
||||
err = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if "fixme" not in l)
|
||||
if r.returncode or not os.path.exists(base + ".%s.dxil" % st):
|
||||
sys.exit("dxc failed for %s:\n%s" % (st, err))
|
||||
print(key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Unsupported as e:
|
||||
sys.exit("unsupported: %s" % e)
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "gfx10-translate"
|
||||
description = "BetterXen's GFX10.3 (RDNA 2) console shader translator: decoder, HLSL translation, coverage"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,48 @@
|
||||
# gfx10-translate
|
||||
|
||||
BetterXen's own translator for console shaders (roadmap, Picture stage): GFX10.3 (RDNA 2) machine code to HLSL, which the public DXC compiles to DXIL for D3DMetal. It is mechanical: one rule per instruction, registers as variables. Control flow is not translated yet.
|
||||
|
||||
| Module | Job |
|
||||
| --- | --- |
|
||||
| `container` | The stage code inside a console shader container (`XBCH` → `FSSM` → stage record). |
|
||||
| `inflate` | zlib, ported from BetterXen's own `shims/xcrdapi/zlib_inflate.cpp` (no third-party dependency). |
|
||||
| `decode` | Instruction words → instructions with structured operands, printed as LLVM-style text. |
|
||||
| `opcodes` | **Generated.** Opcode → mnemonic per encoding format, and the buffer formats. |
|
||||
| `translate` | Instructions → HLSL and the host input layout, through family tables and specific rules. |
|
||||
| `coverage` | What blocks translation across a local folder of shaders, ranked. |
|
||||
|
||||
## Use
|
||||
|
||||
```sh
|
||||
bx-cli shader coverage <folder> # *_VS.* / *_PS.* console shaders, on your machine
|
||||
bx-cli shader translate <vs> <ps> --out <dir> # <vs key>_<ps key>.vs.hlsl / .ps.hlsl / .il
|
||||
cargo run -p gfx10-translate --example listing -- <shader> # decoded listing
|
||||
cargo run -p gfx10-translate --example why -- PS <shader>... # why each shader is refused
|
||||
```
|
||||
|
||||
Game shaders stay on your machine: never commit a shader, a listing, or anything else from the target build (AGENTS.md Section 6).
|
||||
|
||||
## Adding an instruction
|
||||
|
||||
1. Run `bx-cli shader coverage` on your shaders and take the top blocker no open pull request covers (AGENTS.md Section 0, Step 3).
|
||||
2. If it fits a family (`VOP2_UINT`, `VOP2_FLOAT`, `VOP1_FLOAT`, `SOP2_UINT` in `src/translate.rs`), add one row. Otherwise add an arm in `Translator::step`.
|
||||
3. Write the expected HLSL from the instruction's definition, not from your code, and add a test in `tests/translate.rs` with the instruction words from `llvm-mc -show-encoding`.
|
||||
4. Check the instruction's semantics against the console compiler's listing for a shader of our own (`shader-transpiler/corpus/`, source rank 2) where the ISA reference is unclear.
|
||||
|
||||
## Where the facts come from
|
||||
|
||||
- **Opcode names and buffer formats:** `scripts/console-shader/gen_opcodes.py` asks the public LLVM disassembler (`llvm-mc`, Apache-2.0 WITH LLVM-exception) to name every opcode value of every format: gfx1030 first, gaps filled from gfx1010. The console compiler also emits a few GFX10.1 instructions (`v_mac_f32`, `v_mad_f32`, `v_madak_f32`, `v_madmk_f32`) that LLVM knows only there. Only the facts are committed; LLVM is not.
|
||||
- **Encoding layouts:** AMD's public RDNA 2 instruction set reference. `tests/llvm_vectors.txt` (from `scripts/console-shader/gen_llvm_vectors.py`) holds 127 instructions encoded and printed by `llvm-mc`. The decoder must print the same text for each.
|
||||
- **Translation rules:** a port of the Python prototype `scripts/console-shader/translate.py`, kept as the reference. `tests/goldens/` holds small shaders of our own, assembled by `llvm-mc` and translated by the prototype (`scripts/console-shader/gen_translate_goldens.py`). The Rust output must be identical.
|
||||
- **Container layout and the shader model:** inferences from the target build (module comments), AGENTS.md Section 6.
|
||||
|
||||
## Differences from the prototype
|
||||
|
||||
- `s_movk_i32` sign-extends its 16-bit immediate. The prototype read it unsigned.
|
||||
- Output modifiers (`clamp`, `mul:`/`div:`, `op_sel`, `abs`) are refused on every VOP3 instruction, not only on `_e64` forms.
|
||||
- `v_fma_mix*` with `op_sel_hi` all zero (all 32-bit sources) is accepted. The prototype refused it.
|
||||
- **New rules:**
|
||||
- the multiply-add family (`v_mac_f32`, `v_mad_f32`, `v_madak/madmk_f32`, `v_fmaak/fmamk_f32`);
|
||||
- 32-lane execution-mask bookkeeping (`s_mov_b32 sN, exec_lo`, `s_wqm_b32`, `s_and_b32 exec_lo, exec_lo, sN`);
|
||||
- compressed exports with a disabled half.
|
||||
- **Cache keys use standard FNV-1a 64.** The prototype's offset basis is missing its last digit (`1469598103934665603`), so its keys differ. The shim's cache lookup must use the same function as this crate when translation moves into `bx_shader_bridge.dll`.
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Prints the decoded listing of a shader: word index, words, and LLVM-style text.
|
||||
//! usage: cargo run -p gfx10-translate --example listing -- <shader>
|
||||
use gfx10_translate::container::code_words;
|
||||
use gfx10_translate::decode::decode_one;
|
||||
|
||||
fn main() {
|
||||
let path = std::env::args().nth(1).expect("usage: listing <shader>");
|
||||
let words = code_words(&std::fs::read(&path).expect("read")).expect("container");
|
||||
let mut at = 0;
|
||||
while at < words.len() {
|
||||
match decode_one(&words, at) {
|
||||
Ok(inst) => {
|
||||
let hex: Vec<String> = inst.words.iter().map(|w| format!("{w:08x}")).collect();
|
||||
println!("{at:5} {:<26} {inst}", hex.join(" "));
|
||||
at += inst.words.len();
|
||||
if inst.name == "s_endpgm" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{at:5} {:08x} error: {e}", words[at]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Prints why each given shader does not translate, with the instruction words involved.
|
||||
//! usage: cargo run -p gfx10-translate --example why -- <VS|PS> <shader>...
|
||||
use gfx10_translate::container::code_words;
|
||||
use gfx10_translate::decode::{DecodeError, decode};
|
||||
use gfx10_translate::translate::{Stage, Translator};
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let stage = if args.first().map(String::as_str) == Some("VS") {
|
||||
Stage::Vertex
|
||||
} else {
|
||||
Stage::Pixel
|
||||
};
|
||||
for path in &args[1..] {
|
||||
let Ok(blob) = std::fs::read(path) else {
|
||||
continue;
|
||||
};
|
||||
let words = match code_words(&blob) {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
println!("{path}: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match decode(&words) {
|
||||
Err(e) => {
|
||||
let at = match e {
|
||||
DecodeError::UnknownOpcode { at, .. }
|
||||
| DecodeError::UnknownEncoding { at, .. }
|
||||
| DecodeError::Truncated { at } => at,
|
||||
DecodeError::NoEndProgram => 0,
|
||||
};
|
||||
let around: Vec<String> = words
|
||||
.iter()
|
||||
.skip(at)
|
||||
.take(3)
|
||||
.map(|w| format!("{w:08x}"))
|
||||
.collect();
|
||||
println!("{path}: {e}: {}", around.join(" "));
|
||||
}
|
||||
Ok(insts) => {
|
||||
if let Err(e) = Translator::new(stage).run(&insts) {
|
||||
println!("{path}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! The GPU code of one stage from a console shader container.
|
||||
//!
|
||||
//! A console container is a DXBC file whose DXIL part carries no bitcode. The console code is in
|
||||
//! an `XBCH` record: magic, version, compressed size (u64), uncompressed size (u64), then a zlib
|
||||
//! stream. It inflates to an `FSSM` block: a 16-byte header (magic, version, size), then offsets
|
||||
//! relative to the end of that header. One of the per-stage slots at 0x18..0x78 is not
|
||||
//! 0xDEADBEEF filler and locates the stage record, whose first two u64 fields are the code offset
|
||||
//! and size. The code starts with 12-byte header records (a VOP3 word whose top half is 0xD580,
|
||||
//! `v_nop` with a literal) before the first instruction.
|
||||
//!
|
||||
//! These are inferences from containers of the project-authorized target build (AGENTS.md
|
||||
//! section 6), checked by the synthetic container in the tests below.
|
||||
|
||||
use crate::inflate::zlib_inflate;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ContainerError {
|
||||
NoXbch,
|
||||
BadXbch(&'static str),
|
||||
NoStageRecord,
|
||||
BadCode(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for ContainerError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NoXbch => write!(f, "container has no XBCH record"),
|
||||
Self::BadXbch(why) => write!(f, "XBCH record: {why}"),
|
||||
Self::NoStageRecord => write!(f, "FSSM block has no stage record"),
|
||||
Self::BadCode(why) => write!(f, "stage code: {why}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ContainerError {}
|
||||
|
||||
const HEADER_RECORD_TOP: u32 = 0xD580;
|
||||
const FILLER: u64 = 0xDEAD_BEEF_DEAD_BEEF;
|
||||
const MAX_FSSM: usize = 64 << 20;
|
||||
|
||||
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(b.get(at..at + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn u64_at(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_le_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// The stage code inside a console container, header records included.
|
||||
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
let at = blob
|
||||
.windows(4)
|
||||
.position(|w| w == b"XBCH")
|
||||
.ok_or(ContainerError::NoXbch)?;
|
||||
let csize = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
|
||||
let usize_ = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
|
||||
let stream = blob
|
||||
.get(at + 24..at.saturating_add(24).saturating_add(csize))
|
||||
.ok_or(ContainerError::BadXbch("compressed size past the end"))?;
|
||||
let fssm = zlib_inflate(stream, usize_.min(MAX_FSSM))
|
||||
.map_err(|_| ContainerError::BadXbch("zlib stream"))?;
|
||||
if fssm.len() != usize_ || fssm.get(..4) != Some(b"FSSM") {
|
||||
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
|
||||
}
|
||||
const BASE: usize = 16;
|
||||
let record = (0x18..0x78)
|
||||
.step_by(8)
|
||||
.filter_map(|slot| u64_at(&fssm, slot))
|
||||
.find(|&v| v != FILLER)
|
||||
.ok_or(ContainerError::NoStageRecord)? as usize
|
||||
+ BASE;
|
||||
let offset = u64_at(&fssm, record).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let size = u64_at(&fssm, record + 8).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let code = fssm
|
||||
.get(BASE + offset..BASE + offset + size)
|
||||
.ok_or(ContainerError::BadCode("outside the FSSM block"))?;
|
||||
if code.len() < 12 || u32_at(code, 0).map(|w| w >> 16) != Some(HEADER_RECORD_TOP) {
|
||||
return Err(ContainerError::BadCode(
|
||||
"does not start with the expected header records",
|
||||
));
|
||||
}
|
||||
Ok(code.to_vec())
|
||||
}
|
||||
|
||||
/// The instruction words of a stage: from a console container (`DXBC` magic) or a raw code blob,
|
||||
/// with the leading 12-byte header records skipped.
|
||||
pub fn code_words(blob: &[u8]) -> Result<Vec<u32>, ContainerError> {
|
||||
let code = if blob.get(..4) == Some(b"DXBC") {
|
||||
container_code(blob)?
|
||||
} else {
|
||||
blob.to_vec()
|
||||
};
|
||||
let mut at = 0;
|
||||
while at + 12 <= code.len() && u32_at(&code, at).map(|w| w >> 16) == Some(HEADER_RECORD_TOP) {
|
||||
at += 12;
|
||||
}
|
||||
Ok(code[at..]
|
||||
.chunks_exact(4)
|
||||
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn adler32(data: &[u8]) -> u32 {
|
||||
let (mut a, mut b) = (1u32, 0u32);
|
||||
for &byte in data {
|
||||
a = (a + u32::from(byte)) % 65521;
|
||||
b = (b + a) % 65521;
|
||||
}
|
||||
(b << 16) | a
|
||||
}
|
||||
|
||||
/// zlib stream with one stored block (no compression), built by hand.
|
||||
fn stored(data: &[u8]) -> Vec<u8> {
|
||||
let len = data.len() as u16;
|
||||
let mut s = vec![0x78, 0x01, 0x01];
|
||||
s.extend_from_slice(&len.to_le_bytes());
|
||||
s.extend_from_slice(&(!len).to_le_bytes());
|
||||
s.extend_from_slice(data);
|
||||
s.extend_from_slice(&adler32(data).to_be_bytes());
|
||||
s
|
||||
}
|
||||
|
||||
/// A container laid out as the module comment describes: one header record, then two
|
||||
/// instruction words, the stage record in slot 0x30.
|
||||
fn container(code_words_after_header: &[u32]) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&0xD580_0000u32.to_le_bytes());
|
||||
code.extend_from_slice(&[0u8; 8]);
|
||||
for w in code_words_after_header {
|
||||
code.extend_from_slice(&w.to_le_bytes());
|
||||
}
|
||||
let mut fssm = vec![0u8; 0x100];
|
||||
fssm[..4].copy_from_slice(b"FSSM");
|
||||
for slot in (0x18..0x78).step_by(8) {
|
||||
fssm[slot..slot + 8].copy_from_slice(&FILLER.to_le_bytes());
|
||||
}
|
||||
let record = 0x80usize; // relative to byte 16
|
||||
fssm[0x30..0x38].copy_from_slice(&(record as u64).to_le_bytes());
|
||||
let code_offset = 0xA0u64;
|
||||
fssm[16 + record..16 + record + 8].copy_from_slice(&code_offset.to_le_bytes());
|
||||
fssm[16 + record + 8..16 + record + 16].copy_from_slice(&(code.len() as u64).to_le_bytes());
|
||||
fssm.resize(16 + code_offset as usize, 0);
|
||||
fssm.extend_from_slice(&code);
|
||||
let stream = stored(&fssm);
|
||||
let mut blob = b"DXBC".to_vec();
|
||||
blob.extend_from_slice(&[0u8; 28]);
|
||||
blob.extend_from_slice(b"XBCH");
|
||||
blob.extend_from_slice(&1u32.to_le_bytes());
|
||||
blob.extend_from_slice(&(stream.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&(fssm.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&stream);
|
||||
blob
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_stage_code_and_skips_header_records() {
|
||||
let blob = container(&[0xBF81_0000, 0x1234_5678]);
|
||||
assert_eq!(code_words(&blob).unwrap(), vec![0xBF81_0000, 0x1234_5678]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_code_blobs_pass_through() {
|
||||
let mut raw = 0xD580_0000u32.to_le_bytes().to_vec();
|
||||
raw.extend_from_slice(&[0u8; 8]);
|
||||
raw.extend_from_slice(&0xBF81_0000u32.to_le_bytes());
|
||||
assert_eq!(code_words(&raw).unwrap(), vec![0xBF81_0000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_what_is_missing() {
|
||||
assert_eq!(
|
||||
code_words(b"DXBC without a record"),
|
||||
Err(ContainerError::NoXbch)
|
||||
);
|
||||
let mut blob = container(&[0xBF81_0000]);
|
||||
let at = blob.windows(4).position(|w| w == b"XBCH").unwrap();
|
||||
blob[at + 24] = 0; // break the zlib header
|
||||
assert!(matches!(code_words(&blob), Err(ContainerError::BadXbch(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Translator coverage over a local folder of console shaders.
|
||||
//!
|
||||
//! Each file is one stage: a console container or a raw code blob, named `*_VS.*` or `*_PS.*`
|
||||
//! (other files are skipped). Every shader is decoded and translated on its own; the first
|
||||
//! reason it is refused counts as its blocker. The ranked list says which instruction or feature
|
||||
//! to add next. Shaders come from a collaborator's own runs and stay on their machine.
|
||||
|
||||
use crate::container::code_words;
|
||||
use crate::decode::decode;
|
||||
use crate::translate::{Stage, Translator};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct Coverage {
|
||||
pub shaders: usize,
|
||||
pub translated: usize,
|
||||
/// Blocker -> shaders it stops.
|
||||
pub blockers: BTreeMap<String, usize>,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
/// Blockers, most frequent first.
|
||||
pub fn ranked(&self) -> Vec<(&str, usize)> {
|
||||
let mut v: Vec<(&str, usize)> = self
|
||||
.blockers
|
||||
.iter()
|
||||
.map(|(k, n)| (k.as_str(), *n))
|
||||
.collect();
|
||||
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// The blocker key of a refusal: the instruction name when one was refused, else the reason
|
||||
/// with register numbers and constants folded so similar cases count together.
|
||||
pub fn blocker_key(reason: &str) -> String {
|
||||
if let Some(rest) = reason.strip_prefix("instruction '") {
|
||||
return rest.split([' ', '\'']).next().unwrap_or(rest).to_string();
|
||||
}
|
||||
let mut out = String::new();
|
||||
let mut chars = reason.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c.is_ascii_digit() {
|
||||
while chars.peek().is_some_and(|d| d.is_ascii_alphanumeric()) {
|
||||
chars.next();
|
||||
}
|
||||
out.push('#');
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out.chars().take(80).collect()
|
||||
}
|
||||
|
||||
/// Why one stage does not translate, or `None` when it does.
|
||||
pub fn stage_blocker(blob: &[u8], stage: Stage) -> Option<String> {
|
||||
let words = match code_words(blob) {
|
||||
Ok(w) => w,
|
||||
Err(e) => return Some(format!("container: {e}")),
|
||||
};
|
||||
let insts = match decode(&words) {
|
||||
Ok(i) => i,
|
||||
Err(e) => return Some(blocker_key(&format!("decode: {e}"))),
|
||||
};
|
||||
let mut t = Translator::new(stage);
|
||||
t.run(&insts).err().map(|e| blocker_key(&e.0))
|
||||
}
|
||||
|
||||
pub fn scan(dir: &Path) -> io::Result<Coverage> {
|
||||
let mut cov = Coverage::default();
|
||||
let mut paths: Vec<_> = fs::read_dir(dir)?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file())
|
||||
.collect();
|
||||
paths.sort();
|
||||
for path in paths {
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let stage = if name.contains("_VS.") {
|
||||
Stage::Vertex
|
||||
} else if name.contains("_PS.") {
|
||||
Stage::Pixel
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let blob = fs::read(&path)?;
|
||||
cov.shaders += 1;
|
||||
match stage_blocker(&blob, stage) {
|
||||
None => cov.translated += 1,
|
||||
Some(key) => *cov.blockers.entry(key).or_default() += 1,
|
||||
}
|
||||
}
|
||||
Ok(cov)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blocker_keys_group_similar_reasons() {
|
||||
assert_eq!(
|
||||
blocker_key("instruction 'v_cmp_lt_f32_e32 vcc_lo, v1, v2'"),
|
||||
"v_cmp_lt_f32_e32"
|
||||
);
|
||||
assert_eq!(
|
||||
blocker_key("descriptor load from 's[12:13]' (provenance Sgpr(12))"),
|
||||
"descriptor load from 's[#:#]' (provenance Sgpr(#))"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,381 @@
|
||||
//! zlib (RFC 1950) / deflate (RFC 1951) decoder for console shader containers.
|
||||
//!
|
||||
//! A port of BetterXen's own `shims/xcrdapi/zlib_inflate.cpp`, so the crate needs no third-party
|
||||
//! dependency. It decodes a whole stream into a growing buffer and checks the Adler-32 trailer.
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum InflateError {
|
||||
BadHeader,
|
||||
BadData,
|
||||
Truncated,
|
||||
BadChecksum,
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
struct Bits<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
buffer: u32,
|
||||
count: u32,
|
||||
overrun: bool,
|
||||
}
|
||||
|
||||
impl Bits<'_> {
|
||||
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
|
||||
fn get(&mut self, n: u32) -> u32 {
|
||||
while self.count < n {
|
||||
let Some(&byte) = self.data.get(self.pos) else {
|
||||
self.overrun = true;
|
||||
return 0;
|
||||
};
|
||||
self.pos += 1;
|
||||
self.buffer |= u32::from(byte) << self.count;
|
||||
self.count += 8;
|
||||
}
|
||||
let value = if n == 32 {
|
||||
self.buffer
|
||||
} else {
|
||||
self.buffer & ((1u32 << n) - 1)
|
||||
};
|
||||
self.buffer = if n == 32 { 0 } else { self.buffer >> n };
|
||||
self.count -= n;
|
||||
value
|
||||
}
|
||||
|
||||
fn align_to_byte(&mut self) {
|
||||
self.buffer >>= self.count & 7;
|
||||
self.count -= self.count & 7;
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_BITS: usize = 15;
|
||||
|
||||
/// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length, symbols sorted by code.
|
||||
struct Huffman {
|
||||
counts: [u16; MAX_BITS + 1],
|
||||
symbols: [u16; 320],
|
||||
}
|
||||
|
||||
impl Huffman {
|
||||
/// `None` for an over-subscribed set of lengths. An incomplete set is allowed (a single
|
||||
/// distance code is legal); decoding an unassigned code then fails.
|
||||
fn build(lengths: &[u8]) -> Option<Self> {
|
||||
let mut h = Huffman {
|
||||
counts: [0; MAX_BITS + 1],
|
||||
symbols: [0; 320],
|
||||
};
|
||||
for &len in lengths {
|
||||
h.counts[usize::from(len)] += 1;
|
||||
}
|
||||
h.counts[0] = 0;
|
||||
let mut left: i32 = 1;
|
||||
for &count in &h.counts[1..] {
|
||||
left = (left << 1) - i32::from(count);
|
||||
if left < 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut offsets = [0u16; MAX_BITS + 2];
|
||||
for len in 1..=MAX_BITS {
|
||||
offsets[len + 1] = offsets[len] + h.counts[len];
|
||||
}
|
||||
for (symbol, &len) in lengths.iter().enumerate() {
|
||||
if len != 0 {
|
||||
let slot = &mut offsets[usize::from(len)];
|
||||
h.symbols[usize::from(*slot)] = symbol as u16;
|
||||
*slot += 1;
|
||||
}
|
||||
}
|
||||
Some(h)
|
||||
}
|
||||
|
||||
// Huffman codes are packed most significant bit first, one bit at a time.
|
||||
fn decode(&self, input: &mut Bits) -> Option<usize> {
|
||||
let (mut code, mut first, mut index) = (0i32, 0i32, 0i32);
|
||||
for len in 1..=MAX_BITS {
|
||||
code |= input.get(1) as i32;
|
||||
if input.overrun {
|
||||
return None;
|
||||
}
|
||||
let count = i32::from(self.counts[len]);
|
||||
if code - first < count {
|
||||
return Some(usize::from(self.symbols[(index + code - first) as usize]));
|
||||
}
|
||||
index += count;
|
||||
first = (first + count) << 1;
|
||||
code <<= 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 1951 3.2.5 length and distance tables.
|
||||
const LENGTH_BASE: [u16; 29] = [
|
||||
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131,
|
||||
163, 195, 227, 258,
|
||||
];
|
||||
const LENGTH_EXTRA: [u8; 29] = [
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
|
||||
];
|
||||
const DIST_BASE: [u16; 30] = [
|
||||
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
|
||||
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
|
||||
];
|
||||
const DIST_EXTRA: [u8; 30] = [
|
||||
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,
|
||||
13,
|
||||
];
|
||||
|
||||
fn codes(
|
||||
input: &mut Bits,
|
||||
out: &mut Vec<u8>,
|
||||
limit: usize,
|
||||
lit: &Huffman,
|
||||
dist: &Huffman,
|
||||
) -> Result<(), InflateError> {
|
||||
let fail = |input: &Bits| {
|
||||
if input.overrun {
|
||||
InflateError::Truncated
|
||||
} else {
|
||||
InflateError::BadData
|
||||
}
|
||||
};
|
||||
loop {
|
||||
let symbol = lit.decode(input).ok_or_else(|| fail(input))?;
|
||||
if symbol < 256 {
|
||||
if out.len() >= limit {
|
||||
return Err(InflateError::TooLarge);
|
||||
}
|
||||
out.push(symbol as u8);
|
||||
continue;
|
||||
}
|
||||
if symbol == 256 {
|
||||
return Ok(());
|
||||
}
|
||||
let li = symbol - 257;
|
||||
if li >= 29 {
|
||||
return Err(InflateError::BadData);
|
||||
}
|
||||
let length = usize::from(LENGTH_BASE[li]) + input.get(u32::from(LENGTH_EXTRA[li])) as usize;
|
||||
let ds = dist.decode(input).ok_or_else(|| fail(input))?;
|
||||
if ds >= 30 {
|
||||
return Err(InflateError::BadData);
|
||||
}
|
||||
let distance = usize::from(DIST_BASE[ds]) + input.get(u32::from(DIST_EXTRA[ds])) as usize;
|
||||
if input.overrun {
|
||||
return Err(InflateError::Truncated);
|
||||
}
|
||||
if distance > out.len() {
|
||||
return Err(InflateError::BadData);
|
||||
}
|
||||
if length > limit - out.len() {
|
||||
return Err(InflateError::TooLarge);
|
||||
}
|
||||
for _ in 0..length {
|
||||
let byte = out[out.len() - distance];
|
||||
out.push(byte);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dynamic_tables(input: &mut Bits) -> Result<(Huffman, Huffman), InflateError> {
|
||||
let hlit = input.get(5) as usize + 257;
|
||||
let hdist = input.get(5) as usize + 1;
|
||||
let hclen = input.get(4) as usize + 4;
|
||||
if input.overrun {
|
||||
return Err(InflateError::Truncated);
|
||||
}
|
||||
if hlit > 286 || hdist > 30 {
|
||||
return Err(InflateError::BadData);
|
||||
}
|
||||
const ORDER: [usize; 19] = [
|
||||
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
|
||||
];
|
||||
let mut lengths = [0u8; 320];
|
||||
for &slot in &ORDER[..hclen] {
|
||||
lengths[slot] = input.get(3) as u8;
|
||||
}
|
||||
if input.overrun {
|
||||
return Err(InflateError::Truncated);
|
||||
}
|
||||
let code_lengths = Huffman::build(&lengths[..19]).ok_or(InflateError::BadData)?;
|
||||
lengths = [0u8; 320];
|
||||
let mut index = 0;
|
||||
while index < hlit + hdist {
|
||||
let symbol = code_lengths.decode(input).ok_or(if input.overrun {
|
||||
InflateError::Truncated
|
||||
} else {
|
||||
InflateError::BadData
|
||||
})?;
|
||||
if symbol < 16 {
|
||||
lengths[index] = symbol as u8;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
let (value, repeat) = match symbol {
|
||||
16 => {
|
||||
if index == 0 {
|
||||
return Err(InflateError::BadData);
|
||||
}
|
||||
(lengths[index - 1], 3 + input.get(2) as usize)
|
||||
}
|
||||
17 => (0, 3 + input.get(3) as usize),
|
||||
_ => (0, 11 + input.get(7) as usize),
|
||||
};
|
||||
if input.overrun {
|
||||
return Err(InflateError::Truncated);
|
||||
}
|
||||
if index + repeat > hlit + hdist {
|
||||
return Err(InflateError::BadData);
|
||||
}
|
||||
lengths[index..index + repeat].fill(value);
|
||||
index += repeat;
|
||||
}
|
||||
if lengths[256] == 0 {
|
||||
return Err(InflateError::BadData); // no end-of-block code
|
||||
}
|
||||
let lit = Huffman::build(&lengths[..hlit]).ok_or(InflateError::BadData)?;
|
||||
let dist = Huffman::build(&lengths[hlit..hlit + hdist]).ok_or(InflateError::BadData)?;
|
||||
Ok((lit, dist))
|
||||
}
|
||||
|
||||
fn adler32(data: &[u8]) -> u32 {
|
||||
let (mut a, mut b) = (1u32, 0u32);
|
||||
for chunk in data.chunks(5552) {
|
||||
for &byte in chunk {
|
||||
a += u32::from(byte);
|
||||
b += a;
|
||||
}
|
||||
a %= 65521;
|
||||
b %= 65521;
|
||||
}
|
||||
(b << 16) | a
|
||||
}
|
||||
|
||||
/// Decodes a whole zlib stream, producing at most `limit` bytes.
|
||||
pub fn zlib_inflate(input: &[u8], limit: usize) -> Result<Vec<u8>, InflateError> {
|
||||
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
|
||||
if input.len() < 6 {
|
||||
return Err(InflateError::BadHeader);
|
||||
}
|
||||
let (cmf, flg) = (input[0], input[1]);
|
||||
if cmf & 0x0F != 8
|
||||
|| cmf >> 4 > 7
|
||||
|| ((u32::from(cmf) << 8) | u32::from(flg)) % 31 != 0
|
||||
|| flg & 0x20 != 0
|
||||
{
|
||||
return Err(InflateError::BadHeader);
|
||||
}
|
||||
let mut bits = Bits {
|
||||
data: &input[2..],
|
||||
pos: 0,
|
||||
buffer: 0,
|
||||
count: 0,
|
||||
overrun: false,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let final_block = bits.get(1);
|
||||
let kind = bits.get(2);
|
||||
if bits.overrun {
|
||||
return Err(InflateError::Truncated);
|
||||
}
|
||||
match kind {
|
||||
0 => {
|
||||
bits.align_to_byte();
|
||||
let len = bits.get(16) as usize;
|
||||
let nlen = bits.get(16) as usize;
|
||||
if bits.overrun {
|
||||
return Err(InflateError::Truncated);
|
||||
}
|
||||
if len ^ 0xFFFF != nlen {
|
||||
return Err(InflateError::BadData);
|
||||
}
|
||||
// After aligning, the bit buffer is empty: copy straight from the byte stream.
|
||||
let stored = bits
|
||||
.data
|
||||
.get(bits.pos..bits.pos + len)
|
||||
.ok_or(InflateError::Truncated)?;
|
||||
if len > limit - out.len() {
|
||||
return Err(InflateError::TooLarge);
|
||||
}
|
||||
out.extend_from_slice(stored);
|
||||
bits.pos += len;
|
||||
}
|
||||
1 => {
|
||||
let mut lengths = [0u8; 288];
|
||||
lengths[..144].fill(8);
|
||||
lengths[144..256].fill(9);
|
||||
lengths[256..280].fill(7);
|
||||
lengths[280..].fill(8);
|
||||
let lit = Huffman::build(&lengths).ok_or(InflateError::BadData)?;
|
||||
let dist = Huffman::build(&[5u8; 30]).ok_or(InflateError::BadData)?;
|
||||
codes(&mut bits, &mut out, limit, &lit, &dist)?;
|
||||
}
|
||||
2 => {
|
||||
let (lit, dist) = dynamic_tables(&mut bits)?;
|
||||
codes(&mut bits, &mut out, limit, &lit, &dist)?;
|
||||
}
|
||||
_ => return Err(InflateError::BadData),
|
||||
}
|
||||
if final_block != 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
|
||||
bits.align_to_byte();
|
||||
let trailer = bits.pos - (bits.count / 8) as usize;
|
||||
let t = bits
|
||||
.data
|
||||
.get(trailer..trailer + 4)
|
||||
.ok_or(InflateError::Truncated)?;
|
||||
if adler32(&out) != u32::from_be_bytes([t[0], t[1], t[2], t[3]]) {
|
||||
return Err(InflateError::BadChecksum);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// zlib.compress(b"hello hello hello hello, compressed by CPython zlib " * 3, 9), made with CPython,
|
||||
// independently of this code: dynamic Huffman codes and back-references.
|
||||
const HELLO: [u8; 49] = [
|
||||
0x78, 0xda, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0xc8, 0x40, 0x27, 0x75, 0x14, 0x92, 0xf3,
|
||||
0x73, 0x0b, 0x8a, 0x52, 0x8b, 0x8b, 0x53, 0x53, 0x14, 0x92, 0x2a, 0x15, 0x9c, 0x03, 0x2a,
|
||||
0x4b, 0x32, 0xf2, 0xf3, 0x14, 0xaa, 0x72, 0x32, 0x93, 0x30, 0x55, 0xd3, 0x48, 0x0f, 0x00,
|
||||
0x91, 0x2d, 0x39, 0x07,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn inflates_a_cpython_stream() {
|
||||
let expected = b"hello hello hello hello, compressed by CPython zlib ".repeat(3);
|
||||
assert_eq!(zlib_inflate(&HELLO, 4096).unwrap(), expected);
|
||||
assert_eq!(
|
||||
zlib_inflate(&HELLO[..HELLO.len() - 3], 4096),
|
||||
Err(InflateError::Truncated)
|
||||
);
|
||||
assert_eq!(zlib_inflate(&HELLO, 10), Err(InflateError::TooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_what_is_not_zlib() {
|
||||
assert_eq!(
|
||||
zlib_inflate(b"\x00\x00\x00\x00\x00\x00", 64),
|
||||
Err(InflateError::BadHeader)
|
||||
);
|
||||
assert_eq!(zlib_inflate(b"x", 64), Err(InflateError::BadHeader));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_block_round_trip_and_checksum() {
|
||||
// A stored block holding "abc": header, final+type 0, LEN, NLEN, data, Adler-32.
|
||||
let mut s = vec![0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, b'a', b'b', b'c'];
|
||||
s.extend_from_slice(&adler32(b"abc").to_be_bytes());
|
||||
assert_eq!(zlib_inflate(&s, 64).unwrap(), b"abc");
|
||||
*s.last_mut().unwrap() ^= 1;
|
||||
assert_eq!(zlib_inflate(&s, 64), Err(InflateError::BadChecksum));
|
||||
assert_eq!(zlib_inflate(&s, 2), Err(InflateError::TooLarge));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Track D: BetterXen's own GFX10.3 (RDNA 2) shader translator (roadmap, Picture stage).
|
||||
//!
|
||||
//! Console vertex and pixel shaders carry RDNA 2 machine code; D3DMetal needs DXIL. This crate
|
||||
//! translates mechanically, one rule per instruction, with registers as variables:
|
||||
//!
|
||||
//! 1. [`container`]: the stage code inside a console container.
|
||||
//! 2. [`decode`]: code words to instructions, with names from the generated [`opcodes`] tables.
|
||||
//! 3. [`translate`]: instructions to HLSL, through family tables plus specific rules. The public
|
||||
//! DXC compiles that HLSL to DXIL.
|
||||
//! 4. [`coverage`]: which instructions block the most shaders in a local folder.
|
||||
//!
|
||||
//! The Python prototype it ports, `scripts/console-shader/translate.py`, stays as the reference
|
||||
//! for identical output. Next steps (handoff issues): more instruction families, control flow as
|
||||
//! numbered blocks, texture and sampler forms, and translation inside `bx_shader_bridge.dll` at
|
||||
//! first draw. See this crate's README.
|
||||
|
||||
pub mod container;
|
||||
pub mod coverage;
|
||||
pub mod decode;
|
||||
pub mod inflate;
|
||||
#[rustfmt::skip]
|
||||
pub mod opcodes;
|
||||
pub mod translate;
|
||||
|
||||
pub use decode::{Format, Inst, Operand, decode};
|
||||
pub use translate::{Stage, Translation, Unsupported, translate_pair};
|
||||
|
||||
/// Decodes and translates a VS/PS pair given as console containers or raw code blobs.
|
||||
pub fn translate_blobs(vs: &[u8], ps: &[u8]) -> Result<Translation, Unsupported> {
|
||||
let words = |blob: &[u8], what: &str| {
|
||||
container::code_words(blob).map_err(|e| Unsupported(format!("{what}: {e}")))
|
||||
};
|
||||
let vs = decode(&words(vs, "VS")?).map_err(|e| Unsupported(format!("VS decode: {e}")))?;
|
||||
let ps = decode(&words(ps, "PS")?).map_err(|e| Unsupported(format!("PS decode: {e}")))?;
|
||||
translate_pair(&vs, &ps)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
FETCH 2
|
||||
@@ -0,0 +1 @@
|
||||
c8080000 c8090001 c80e0102 b0141234 be9503f2 8f168214 88178716 87171517 89171417 93171617 8017c017 80971417 90178417 83981617 84981418 be990b18 939aff19 00100000 ba801801 00000003 34080482 2c080890 30080881 360808ff 000000ff 38080704 3a080504 4c080704 4e080504 16080704 26080504 28080704 d5690004 02020504 d56a0004 02003304 d51a0004 02020818 060a04f0 100a0aff 3e800000 080a0705 0a0a0705 200a0505 1e0a0705 d5030005 42020505 d5080005 22020705 d5040005 02020505 d5100005 02002b05 560a0702 7e0c5505 7e0c5d06 7e0c6706 7e0c4906 7e0c4106 7e0c4b06 7e0c4f06 7e0c4306 7e0c4706 7e0c4506 7e0c6b06 7e0c6d06 d5aa0006 22010106 7e0e0d04 7e0e0b04 7e101107 d5570007 03c90107 d54b0007 23ca0507 0e0e0707 5e120d07 cc21000a 0c0e0509 cc22400a 1c2a1309 7e160217 4a16110b f8001c0f 00000a09 bf810000
|
||||
@@ -0,0 +1,84 @@
|
||||
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0) : SV_Target0 {
|
||||
uint v2 = 0;
|
||||
uint v3 = 0;
|
||||
uint v4 = 0;
|
||||
uint v5 = 0;
|
||||
uint v6 = 0;
|
||||
uint v7 = 0;
|
||||
uint v8 = 0;
|
||||
uint v9 = 0;
|
||||
uint v10 = 0;
|
||||
uint v11 = 0;
|
||||
uint s20 = 0;
|
||||
uint s21 = 0;
|
||||
uint s22 = 0;
|
||||
uint s23 = 0;
|
||||
uint s24 = 0;
|
||||
uint s25 = 0;
|
||||
v2 = asuint(attr0.x);
|
||||
v3 = asuint(attr0.y);
|
||||
s20 = 4660u;
|
||||
s21 = asuint(1.0f);
|
||||
s22 = s20 << (2u & 31u);
|
||||
s23 = (s22 | 7u);
|
||||
s23 = (s23 & s21);
|
||||
s23 = (s23 ^ s20);
|
||||
s23 = (s23 * s22);
|
||||
s23 = (s23 + 64u);
|
||||
s23 = (s23 - s20);
|
||||
s23 = (s23 >> (4u & 31u));
|
||||
s24 = min(s23, s22);
|
||||
s24 = max(s24, s20);
|
||||
s25 = reversebits(s24);
|
||||
v4 = (v2 << (2u & 31u));
|
||||
v4 = (v4 >> (16u & 31u));
|
||||
v4 = (uint)((int)v4 >> (1u & 31u));
|
||||
v4 = (0xffu & v4);
|
||||
v4 = (v4 | v3);
|
||||
v4 = (v4 ^ v2);
|
||||
v4 = (v4 - v3);
|
||||
v4 = (v2 - v4);
|
||||
v4 = ((v4 & 0xffffffu) * (v3 & 0xffffffu));
|
||||
v4 = min(v4, v2);
|
||||
v4 = max(v4, v3);
|
||||
v4 = (v4 * v2);
|
||||
v4 = (uint)(((uint64_t)v4 * (uint64_t)s25) >> 32);
|
||||
v4 = (v4 << (s24 & 31u));
|
||||
v5 = asuint(asfloat(asuint(0.5f)) + asfloat(v2));
|
||||
v5 = asuint(asfloat(0x3e800000u) * asfloat(v5));
|
||||
v5 = asuint(asfloat(v5) - asfloat(v3));
|
||||
v5 = asuint((asfloat(v3) - asfloat(v5)));
|
||||
v5 = asuint(max(asfloat(v5), asfloat(v2)));
|
||||
v5 = asuint(min(asfloat(v5), asfloat(v3)));
|
||||
v5 = asuint(asfloat(v5) + asfloat((asuint(-asfloat(v2)))));
|
||||
v5 = asuint(asfloat((asuint(-asfloat(v5)))) * asfloat(v3));
|
||||
v5 = asuint((asfloat(v5) - asfloat(v2)));
|
||||
v5 = asuint(max(asfloat(v5), asfloat(s21)));
|
||||
v5 = asuint(mad(asfloat(v2), asfloat(v3), asfloat(v5)));
|
||||
v6 = asuint((1.0f / asfloat(v5)));
|
||||
v6 = asuint(rsqrt(asfloat(v6)));
|
||||
v6 = asuint(sqrt(asfloat(v6)));
|
||||
v6 = asuint(floor(asfloat(v6)));
|
||||
v6 = asuint(frac(asfloat(v6)));
|
||||
v6 = asuint(exp2(asfloat(v6)));
|
||||
v6 = asuint(log2(asfloat(v6)));
|
||||
v6 = asuint(trunc(asfloat(v6)));
|
||||
v6 = asuint(round(asfloat(v6)));
|
||||
v6 = asuint(ceil(asfloat(v6)));
|
||||
v6 = asuint(sin(asfloat(v6) * 6.2831853f));
|
||||
v6 = asuint(cos(asfloat(v6) * 6.2831853f));
|
||||
v6 = asuint((1.0f / asfloat((asuint(-asfloat(v6))))));
|
||||
v7 = asuint((float)asuint(asfloat(v4)));
|
||||
v7 = asuint((float)asint(asfloat(v4)));
|
||||
v8 = (uint)(int)asfloat(v7);
|
||||
v7 = asuint(max(min(asfloat(v7), asfloat(0u)), min(max(asfloat(v7), asfloat(0u)), asfloat(asuint(1.0f)))));
|
||||
v7 = asuint(mad(asfloat((asuint(-asfloat(v7)))), asfloat(v2), asfloat(asuint(1.0f))));
|
||||
v7 = asuint((asfloat(v7) == 0.0f || asfloat(v3) == 0.0f) ? 0.0f : asfloat(v7) * asfloat(v3));
|
||||
v9 = f32tof16(asfloat(v7)) | (f32tof16(asfloat(v6)) << 16);
|
||||
v10 = (v10 & 0xffff0000u) | f32tof16(mad(f16tof32(v9 & 0xffffu), asfloat(v2), asfloat(v3)));
|
||||
v10 = (v10 & 0xffffu) | (f32tof16(mad(f16tof32(v9 & 0xffffu), f16tof32(v9 & 0xffffu), f16tof32(v10 & 0xffffu))) << 16);
|
||||
v11 = s23;
|
||||
v11 = v11 + v8;
|
||||
float4 exp0_mrt0 = float4(f16tof32(v9 & 0xffffu), f16tof32(v9 >> 16), f16tof32(v10 & 0xffffu), f16tof32(v10 >> 16));
|
||||
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
be842104 f80008cf 07060504 f800020f 0b0a0908 bf810000
|
||||
@@ -0,0 +1,17 @@
|
||||
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; };
|
||||
VSOut main(float4 a0 : ATTR0, float4 a1 : ATTR1) {
|
||||
uint v4 = asuint(a0.x);
|
||||
uint v5 = asuint(a0.y);
|
||||
uint v6 = asuint(a0.z);
|
||||
uint v7 = asuint(a0.w);
|
||||
uint v8 = asuint(a1.x);
|
||||
uint v9 = asuint(a1.y);
|
||||
uint v10 = asuint(a1.z);
|
||||
uint v11 = asuint(a1.w);
|
||||
float4 exp0_pos0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
|
||||
float4 exp1_param0 = float4(asfloat(v8), asfloat(v9), asfloat(v10), asfloat(v11));
|
||||
VSOut o;
|
||||
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
|
||||
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
ATTR 0 17 0 0
|
||||
ATTR 1 28 1 8
|
||||
ATTR 2 7 0 8
|
||||
USE CB 1
|
||||
@@ -0,0 +1 @@
|
||||
c80a0402 c80e0702 c8100200 c8110201 f8001807 00040302 bf810000
|
||||
@@ -0,0 +1,10 @@
|
||||
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0, float4 attr1 : PARAM1) : SV_Target0 {
|
||||
uint v2 = 0;
|
||||
uint v3 = 0;
|
||||
uint v4 = 0;
|
||||
v2 = asuint(attr1.x);
|
||||
v3 = asuint(attr1.w);
|
||||
v4 = asuint(attr0.z);
|
||||
float4 exp0_mrt0 = float4(asfloat(v2), asfloat(v3), asfloat(v4), 0.0f);
|
||||
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
f4080300 fa000000 f4080400 fa000010 f4080504 fa000020 4a020002 bf8cc07f e0342000 80030201 e9c32008 80040401 e03c2008 80030801 e0382000 80050c00 bf8c3f70 7e1602f2 f80008cf 0b080302 f800020f 07060504 f800021f 0f0e0d0c bf810000
|
||||
@@ -0,0 +1,50 @@
|
||||
cbuffer CB1 : register(b1, space100) { uint4 cb1[4096]; };
|
||||
uint cb1_word(uint w) { return cb1[w >> 2][w & 3]; }
|
||||
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; float4 param1 : PARAM1; };
|
||||
VSOut main(uint2 in0 : ATTR0, float4 in1 : ATTR1, uint3 in2 : ATTR2) {
|
||||
uint v0 = 0;
|
||||
uint v2 = 0;
|
||||
uint v3 = 0;
|
||||
uint v4 = 0;
|
||||
uint v5 = 0;
|
||||
uint v6 = 0;
|
||||
uint v7 = 0;
|
||||
uint v8 = 0;
|
||||
uint v9 = 0;
|
||||
uint v10 = 0;
|
||||
uint v11 = 0;
|
||||
uint v12 = 0;
|
||||
uint v13 = 0;
|
||||
uint v14 = 0;
|
||||
uint v15 = 0;
|
||||
uint t0_0 = 0;
|
||||
uint t0_1 = 0;
|
||||
uint t0_2 = 0;
|
||||
uint t0_3 = 0;
|
||||
v2 = in0.x;
|
||||
v3 = in0.y;
|
||||
v4 = asuint(in1.x);
|
||||
v5 = asuint(in1.y);
|
||||
v6 = asuint(in1.z);
|
||||
v7 = asuint(in1.w);
|
||||
v8 = in2.x;
|
||||
v9 = in2.y;
|
||||
v10 = in2.z;
|
||||
t0_0 = cb1[v0].x;
|
||||
t0_1 = cb1[v0].y;
|
||||
t0_2 = cb1[v0].z;
|
||||
t0_3 = cb1[v0].w;
|
||||
v12 = t0_0;
|
||||
v13 = t0_1;
|
||||
v14 = t0_2;
|
||||
v15 = t0_3;
|
||||
v11 = asuint(1.0f);
|
||||
float4 exp0_pos0 = float4(asfloat(v2), asfloat(v3), asfloat(v8), asfloat(v11));
|
||||
float4 exp1_param0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
|
||||
float4 exp2_param1 = float4(asfloat(v12), asfloat(v13), asfloat(v14), asfloat(v15));
|
||||
VSOut o;
|
||||
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
|
||||
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
|
||||
o.param1 = float4(exp2_param1.x, exp2_param1.y, exp2_param1.z, exp2_param1.w);
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
FETCH 1
|
||||
USE CB 0
|
||||
USE TEX 1
|
||||
@@ -0,0 +1 @@
|
||||
be8a047e befe0a7e befc0302 c8080000 c8090001 c80c0100 c80d0101 f40c0004 fa000020 f408030a fa000000 87fe0a7e bf8cc07f f0800f08 00600402 bf8c3f70 10080904 f800180f 07060504 bf810000
|
||||
@@ -0,0 +1,21 @@
|
||||
Texture2D<float4> tex1 : register(t1, space100);
|
||||
SamplerState smp0 : register(s0, space100);
|
||||
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0) : SV_Target0 {
|
||||
uint v2 = 0;
|
||||
uint v3 = 0;
|
||||
uint v4 = 0;
|
||||
uint v5 = 0;
|
||||
uint v6 = 0;
|
||||
uint v7 = 0;
|
||||
v2 = asuint(attr0.x);
|
||||
v3 = asuint(attr0.y);
|
||||
{ float4 r = tex1.Sample(smp0, float2(asfloat(v2), asfloat(v3)));
|
||||
v4 = asuint(r.x);
|
||||
v5 = asuint(r.y);
|
||||
v6 = asuint(r.z);
|
||||
v7 = asuint(r.w);
|
||||
}
|
||||
v4 = asuint(asfloat(v4) * asfloat(v4));
|
||||
float4 exp0_mrt0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
|
||||
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
be842104 f4080304 fa000000 bf8cc07f f4280406 fa000000 bf8cc07f 10000810 d54b0001 004e0a11 7e040280 7e0602f2 f80008cf 03020100 f800020f 03020706 bf810000
|
||||
@@ -0,0 +1,31 @@
|
||||
cbuffer CB0 : register(b0, space100) { uint4 cb0[4096]; };
|
||||
uint cb0_word(uint w) { return cb0[w >> 2][w & 3]; }
|
||||
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; };
|
||||
VSOut main(float4 a0 : ATTR0) {
|
||||
uint v0 = 0;
|
||||
uint v1 = 0;
|
||||
uint v2 = 0;
|
||||
uint v3 = 0;
|
||||
uint v4 = asuint(a0.x);
|
||||
uint v5 = asuint(a0.y);
|
||||
uint v6 = asuint(a0.z);
|
||||
uint v7 = asuint(a0.w);
|
||||
uint s16 = 0;
|
||||
uint s17 = 0;
|
||||
uint s18 = 0;
|
||||
uint s19 = 0;
|
||||
s16 = cb0_word(0);
|
||||
s17 = cb0_word(1);
|
||||
s18 = cb0_word(2);
|
||||
s19 = cb0_word(3);
|
||||
v0 = asuint(asfloat(s16) * asfloat(v4));
|
||||
v1 = asuint(mad(asfloat(s17), asfloat(v5), asfloat(s19)));
|
||||
v2 = 0u;
|
||||
v3 = asuint(1.0f);
|
||||
float4 exp0_pos0 = float4(asfloat(v0), asfloat(v1), asfloat(v2), asfloat(v3));
|
||||
float4 exp1_param0 = float4(asfloat(v6), asfloat(v7), asfloat(v2), asfloat(v3));
|
||||
VSOut o;
|
||||
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
|
||||
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! The decoder against the public LLVM AMDGPU disassembler: every line of llvm_vectors.txt
|
||||
//! (generated by scripts/console-shader/gen_llvm_vectors.py) gives instruction words and the
|
||||
//! text llvm-mc prints for them. Decoding the words must give the same text and consume exactly
|
||||
//! those words.
|
||||
|
||||
use gfx10_translate::decode::decode_one;
|
||||
|
||||
#[test]
|
||||
fn decoder_matches_llvm() {
|
||||
let mut failures = Vec::new();
|
||||
let mut checked = 0;
|
||||
for line in include_str!("llvm_vectors.txt").lines() {
|
||||
if line.starts_with('#') || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (hex, expected) = line.split_once(" | ").expect("vector line");
|
||||
let words: Vec<u32> = hex
|
||||
.split_whitespace()
|
||||
.map(|w| u32::from_str_radix(w, 16).unwrap())
|
||||
.collect();
|
||||
checked += 1;
|
||||
match decode_one(&words, 0) {
|
||||
Ok(inst) if inst.words.len() != words.len() => failures.push(format!(
|
||||
"{expected}: consumed {} of {} words",
|
||||
inst.words.len(),
|
||||
words.len()
|
||||
)),
|
||||
Ok(inst) if inst.to_string() != expected => {
|
||||
failures.push(format!("{expected}\n got: {inst}"))
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => failures.push(format!("{expected}: {e}")),
|
||||
}
|
||||
}
|
||||
assert!(checked > 100, "only {checked} vectors");
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"{} of {checked} differ from llvm-mc:\n {}",
|
||||
failures.len(),
|
||||
failures.join("\n ")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
# @generated by scripts/console-shader/gen_llvm_vectors.py from Homebrew LLVM version 23.1.6 (gfx1030).
|
||||
# <instruction words> | <llvm-mc's text for them>
|
||||
80000201 | s_add_u32 s0, s1, s2
|
||||
8003ff01 12345678 | s_add_u32 s3, s1, 0x12345678
|
||||
88008701 | s_or_b32 s0, s1, 7
|
||||
8704c105 | s_and_b32 s4, s5, -1
|
||||
89000201 | s_xor_b32 s0, s1, s2
|
||||
93000201 | s_mul_i32 s0, s1, s2
|
||||
8080c001 | s_sub_u32 s0, s1, 64
|
||||
90008401 | s_lshr_b32 s0, s1, 4
|
||||
8f008201 | s_lshl_b32 s0, s1, 2
|
||||
83800201 | s_min_u32 s0, s1, s2
|
||||
84800201 | s_max_u32 s0, s1, s2
|
||||
9380ff01 00100000 | s_bfe_u32 s0, s1, 0x100000
|
||||
be800301 | s_mov_b32 s0, s1
|
||||
be8003f2 | s_mov_b32 s0, 1.0
|
||||
befc0301 | s_mov_b32 m0, s1
|
||||
be800402 | s_mov_b64 s[0:1], s[2:3]
|
||||
be80047e | s_mov_b64 s[0:1], exec
|
||||
87fe027e | s_and_b64 exec, exec, s[2:3]
|
||||
befe0a7e | s_wqm_b64 exec, exec
|
||||
be800b01 | s_brev_b32 s0, s1
|
||||
be842104 | s_swappc_b64 s[4:5], s[4:5]
|
||||
b0001234 | s_movk_i32 s0, 0x1234
|
||||
bf060100 | s_cmp_eq_u32 s0, s1
|
||||
bf840004 | s_cbranch_scc0 4
|
||||
bf810000 | s_endpgm
|
||||
f4080002 fa000010 | s_load_dwordx4 s[0:3], s[4:5], 0x10
|
||||
f40c0202 fa000020 | s_load_dwordx8 s[8:15], s[4:5], 0x20
|
||||
f4080002 fa000000 | s_load_dwordx4 s[0:3], s[4:5], null
|
||||
f4200002 fa000000 | s_buffer_load_dword s0, s[4:7], null
|
||||
f4240002 fa000008 | s_buffer_load_dwordx2 s[0:1], s[4:7], 0x8
|
||||
f4280202 fa000010 | s_buffer_load_dwordx4 s[8:11], s[4:7], 0x10
|
||||
f42c0202 fa000020 | s_buffer_load_dwordx8 s[8:15], s[4:7], 0x20
|
||||
f4300402 fa000040 | s_buffer_load_dwordx16 s[16:31], s[4:7], 0x40
|
||||
7e000301 | v_mov_b32_e32 v0, v1
|
||||
7e000202 | v_mov_b32_e32 v0, s2
|
||||
7e0002ff 40490fdb | v_mov_b32_e32 v0, 0x40490fdb
|
||||
7e0002f2 | v_mov_b32_e32 v0, 1.0
|
||||
7e0002f7 | v_mov_b32_e32 v0, -4.0
|
||||
7e0002f8 | v_mov_b32_e32 v0, 0.15915494
|
||||
7e000291 | v_mov_b32_e32 v0, 17
|
||||
7e0002c3 | v_mov_b32_e32 v0, -3
|
||||
06000501 | v_add_f32_e32 v0, v1, v2
|
||||
060002f0 | v_add_f32_e32 v0, 0.5, v1
|
||||
100002ff 3e800000 | v_mul_f32_e32 v0, 0x3e800000, v1
|
||||
08000501 | v_sub_f32_e32 v0, v1, v2
|
||||
0a000501 | v_subrev_f32_e32 v0, v1, v2
|
||||
20000501 | v_max_f32_e32 v0, v1, v2
|
||||
1e000501 | v_min_f32_e32 v0, v1, v2
|
||||
56000501 | v_fmac_f32_e32 v0, v1, v2
|
||||
0e000501 | v_mul_legacy_f32_e32 v0, v1, v2
|
||||
5e000501 | v_cvt_pkrtz_f16_f32_e32 v0, v1, v2
|
||||
34000282 | v_lshlrev_b32_e32 v0, 2, v1
|
||||
2c000290 | v_lshrrev_b32_e32 v0, 16, v1
|
||||
30000290 | v_ashrrev_i32_e32 v0, 16, v1
|
||||
360002ff 000000ff | v_and_b32_e32 v0, 0xff, v1
|
||||
38000501 | v_or_b32_e32 v0, v1, v2
|
||||
3a000501 | v_xor_b32_e32 v0, v1, v2
|
||||
4c000501 | v_sub_nc_u32_e32 v0, v1, v2
|
||||
4e000501 | v_subrev_nc_u32_e32 v0, v1, v2
|
||||
4a000202 | v_add_nc_u32_e32 v0, s2, v1
|
||||
16000501 | v_mul_u32_u24_e32 v0, v1, v2
|
||||
26000501 | v_min_u32_e32 v0, v1, v2
|
||||
28000501 | v_max_u32_e32 v0, v1, v2
|
||||
7e005501 | v_rcp_f32_e32 v0, v1
|
||||
7e005d01 | v_rsq_f32_e32 v0, v1
|
||||
7e006701 | v_sqrt_f32_e32 v0, v1
|
||||
7e004901 | v_floor_f32_e32 v0, v1
|
||||
7e004101 | v_fract_f32_e32 v0, v1
|
||||
7e004b01 | v_exp_f32_e32 v0, v1
|
||||
7e004f01 | v_log_f32_e32 v0, v1
|
||||
7e004301 | v_trunc_f32_e32 v0, v1
|
||||
7e004701 | v_rndne_f32_e32 v0, v1
|
||||
7e004501 | v_ceil_f32_e32 v0, v1
|
||||
7e000d01 | v_cvt_f32_u32_e32 v0, v1
|
||||
7e000b01 | v_cvt_f32_i32_e32 v0, v1
|
||||
7e001101 | v_cvt_i32_f32_e32 v0, v1
|
||||
7e006b01 | v_sin_f32_e32 v0, v1
|
||||
7e006d01 | v_cos_f32_e32 v0, v1
|
||||
d5030000 02020501 | v_add_f32_e64 v0, v1, v2
|
||||
d5080000 22020501 | v_mul_f32_e64 v0, -v1, v2
|
||||
d5080000 42020501 | v_mul_f32_e64 v0, v1, -v2
|
||||
d5080200 22020501 | v_mul_f32_e64 v0, -v1, |v2|
|
||||
d5038000 02020501 | v_add_f32_e64 v0, v1, v2 clamp
|
||||
d5080000 0a020501 | v_mul_f32_e64 v0, v1, v2 mul:2
|
||||
d5100000 02000501 | v_max_f32_e64 v0, v1, s2
|
||||
d5040000 02020501 | v_sub_f32_e64 v0, v1, v2
|
||||
d5aa0000 22010101 | v_rcp_f32_e64 v0, -v1
|
||||
d51a0000 02020202 | v_lshlrev_b32_e64 v0, s2, v1
|
||||
d5690000 02020501 | v_mul_lo_u32 v0, v1, v2
|
||||
d56a0000 02020501 | v_mul_hi_u32 v0, v1, v2
|
||||
d54b0000 040e0501 | v_fma_f32 v0, v1, v2, v3
|
||||
d54b0000 23ca0501 | v_fma_f32 v0, -v1, v2, 1.0
|
||||
d5570000 03c90101 | v_med3_f32 v0, v1, 0, 1.0
|
||||
d5480000 02211101 | v_bfe_u32 v0, v1, 8, 8
|
||||
7c020501 | v_cmp_lt_f32_e32 vcc_lo, v1, v2
|
||||
7da40501 | v_cmpx_eq_u32_e32 v1, v2
|
||||
02000501 | v_cndmask_b32_e32 v0, v1, v2, vcc_lo
|
||||
c8080000 | v_interp_p1_f32_e32 v2, v0, attr0.x
|
||||
c8090001 | v_interp_p2_f32_e32 v2, v1, attr0.x
|
||||
c80d0f01 | v_interp_p2_f32_e32 v3, v1, attr3.w
|
||||
c8020902 | v_interp_mov_f32_e32 v0, p0, attr2.y
|
||||
cc210000 1c0e0501 | v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]
|
||||
cc224000 1c0e0501 | v_fma_mixhi_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]
|
||||
e0302000 80010001 | buffer_load_dword v0, v1, s[4:7], 0 idxen
|
||||
e030200c 80010001 | buffer_load_dword v0, v1, s[4:7], 0 idxen offset:12
|
||||
e0342000 80010002 | buffer_load_dwordx2 v[0:1], v2, s[4:7], 0 idxen
|
||||
e03c2004 80010003 | buffer_load_dwordx3 v[0:2], v3, s[4:7], 0 idxen offset:4
|
||||
e0382000 80020004 | buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 idxen
|
||||
e0301000 80010001 | buffer_load_dword v0, v1, s[4:7], 0 offen
|
||||
e0300010 02010000 | buffer_load_dword v0, off, s[4:7], s2 offset:16
|
||||
e9c32000 80000004 | tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen
|
||||
e8eb2008 80000004 | tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] idxen offset:8
|
||||
f0800f08 00820004 | image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
f0800808 00820004 | image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
|
||||
f09c0308 00820002 | image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
|
||||
f80008cf 03020100 | exp pos0, v0, v1, v2, v3 done
|
||||
f800180f 03020100 | exp mrt0, v0, v1, v2, v3 done vm
|
||||
f8000001 00000000 | exp mrt0, v0, off, off, off
|
||||
f800023f 07060504 | exp param3, v4, v5, v6, v7
|
||||
f8001c0f 00000100 | exp mrt0, v0, v0, v1, v1 done compr vm
|
||||
5a000501 3f800000 | v_fmaak_f32 v0, v1, v2, 0x3f800000
|
||||
58000501 40000000 | v_fmamk_f32 v0, v1, 0x40000000, v2
|
||||
3e000501 | v_mac_f32_e32 v0, v1, v2
|
||||
d51f0000 22020501 | v_mac_f32_e64 v0, -v1, v2
|
||||
d5410000 040e0501 | v_mad_f32 v0, v1, v2, v3
|
||||
42000501 3f800000 | v_madak_f32 v0, v1, v2, 0x3f800000
|
||||
40000501 40000000 | v_madmk_f32 v0, v1, 0x40000000, v2
|
||||
@@ -0,0 +1,187 @@
|
||||
//! The translator against its reference. The golden files hold small VS/PS pairs written in
|
||||
//! GFX10.3 assembly, assembled by the public LLVM assembler, with the HLSL and input layout the
|
||||
//! Python prototype (scripts/console-shader/translate.py) produces for them; regenerate them
|
||||
//! with scripts/console-shader/gen_translate_goldens.py. Between them the cases use every rule
|
||||
//! the translator has. Refusals are checked separately.
|
||||
|
||||
use gfx10_translate::decode::decode;
|
||||
use gfx10_translate::translate::{Stage, Translator, translate_pair};
|
||||
|
||||
fn words(hex: &str) -> Vec<u32> {
|
||||
hex.split_whitespace()
|
||||
.map(|w| u32::from_str_radix(w, 16).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn golden(case: &str, vs: &str, ps: &str, vs_hlsl: &str, ps_hlsl: &str, il: &str) {
|
||||
let vs = decode(&words(vs)).unwrap_or_else(|e| panic!("{case} VS: {e}"));
|
||||
let ps = decode(&words(ps)).unwrap_or_else(|e| panic!("{case} PS: {e}"));
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{case}: {e}"));
|
||||
assert_eq!(t.vs_hlsl, vs_hlsl, "{case} VS HLSL");
|
||||
assert_eq!(t.ps_hlsl, ps_hlsl, "{case} PS HLSL");
|
||||
assert_eq!(t.layout, il, "{case} layout");
|
||||
}
|
||||
|
||||
macro_rules! golden_case {
|
||||
($test:ident, $name:literal) => {
|
||||
#[test]
|
||||
fn $test() {
|
||||
golden(
|
||||
$name,
|
||||
include_str!(concat!("goldens/", $name, ".vs.hex")),
|
||||
include_str!(concat!("goldens/", $name, ".ps.hex")),
|
||||
include_str!(concat!("goldens/", $name, ".vs.hlsl")),
|
||||
include_str!(concat!("goldens/", $name, ".ps.hlsl")),
|
||||
include_str!(concat!("goldens/", $name, ".il")),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
golden_case!(textured_pair_matches_the_prototype, "textured");
|
||||
golden_case!(alu_families_match_the_prototype, "alu");
|
||||
golden_case!(vertex_buffers_match_the_prototype, "buffers");
|
||||
|
||||
/// Translates one stage given as instruction words, returning the refusal if any.
|
||||
fn refusal(stage: Stage, hex: &str) -> Option<String> {
|
||||
let insts = decode(&words(hex)).unwrap();
|
||||
Translator::new(stage).run(&insts).err().map(|e| e.0)
|
||||
}
|
||||
|
||||
// Encodings from llvm-mc (gfx1030); each program ends in s_endpgm (bf810000).
|
||||
#[test]
|
||||
fn refuses_what_it_does_not_model() {
|
||||
// v_cmp_lt_f32_e32 vcc_lo, v1, v2: no rule for compares yet.
|
||||
assert!(
|
||||
refusal(Stage::Pixel, "7c020501 bf810000")
|
||||
.unwrap()
|
||||
.starts_with("instruction 'v_cmp_lt_f32_e32")
|
||||
);
|
||||
// v_add_f32_e64 v0, v1, v2 clamp: output modifiers are refused, not dropped.
|
||||
assert!(
|
||||
refusal(Stage::Pixel, "d5038000 02020501 bf810000")
|
||||
.unwrap()
|
||||
.starts_with("modifier in")
|
||||
);
|
||||
// v_mul_f32_e64 v0, v1, v2 mul:2
|
||||
assert!(
|
||||
refusal(Stage::Pixel, "d5080000 0a020501 bf810000")
|
||||
.unwrap()
|
||||
.starts_with("modifier in")
|
||||
);
|
||||
// s_load_dwordx8 s[8:15], s[4:5], 0x20: a texture from a descriptor table the model does not
|
||||
// know. (A 4-dword load from such a table is a sampler and is accepted.)
|
||||
assert!(
|
||||
refusal(Stage::Pixel, "f40c0202 fa000020 bf810000")
|
||||
.unwrap()
|
||||
.starts_with("descriptor load from")
|
||||
);
|
||||
assert_eq!(refusal(Stage::Pixel, "f4080002 fa000010 bf810000"), None);
|
||||
// s_swappc_b64 s[4:5], s[4:5] in a pixel shader.
|
||||
assert!(refusal(Stage::Pixel, "be842104 bf810000").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pixel_shader_reading_an_attribute_the_vertex_shader_does_not_export_is_refused() {
|
||||
// VS: s_swappc_b64 s[4:5], s[4:5]; exp pos0, v4, v5, v6, v7 done; s_endpgm
|
||||
// PS: v_interp_mov_f32_e32 v2, p0, attr1.x; exp mrt0, v2, off, off, off done; s_endpgm
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
let ps = decode(&words("c80a0402 f8000801 00000002 bf810000")).unwrap();
|
||||
let err = translate_pair(&vs, &ps).unwrap_err();
|
||||
assert_eq!(err.0, "PS reads attr1 that the VS does not export");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s_movk_sign_extends() {
|
||||
// s_movk_i32 s0, 0xffff; v_mov_b32_e32 v0, s0; exp mrt0, v0, off, off, off done; s_endpgm
|
||||
let insts = decode(&words("b000ffff 7e000200 f8000801 00000000 bf810000")).unwrap();
|
||||
let mut t = Translator::new(Stage::Pixel);
|
||||
t.run(&insts).unwrap();
|
||||
let (vs, params) = gfx10_translate::translate::build_vs(&{
|
||||
let mut v = Translator::new(Stage::Vertex);
|
||||
v.run(&decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap())
|
||||
.unwrap();
|
||||
v
|
||||
})
|
||||
.unwrap();
|
||||
let ps = gfx10_translate::translate::build_ps(&t, ¶ms).unwrap();
|
||||
assert!(vs.contains("o.pos"));
|
||||
assert!(ps.contains("s0 = 4294967295u;"), "{ps}");
|
||||
}
|
||||
|
||||
/// The multiply-add family (not in the prototype). Encodings from llvm-mc (v_mac/v_mad/v_madak/
|
||||
/// v_madmk for gfx1010, v_fmaak/v_fmamk for gfx1030); the expected HLSL follows the ISA's
|
||||
/// definitions (D = S0*S1 + D; S0*S1 + S2; S0*S1 + K; S0*K + S1), written out here.
|
||||
#[test]
|
||||
fn multiply_add_family() {
|
||||
let cases = [
|
||||
(
|
||||
"3e000501",
|
||||
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(v0)));",
|
||||
),
|
||||
(
|
||||
"d51f0000 22020501",
|
||||
"v0 = asuint(mad(asfloat((asuint(-asfloat(v1)))), asfloat(v2), asfloat(v0)));",
|
||||
),
|
||||
(
|
||||
"d5410000 040e0501",
|
||||
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(v3)));",
|
||||
),
|
||||
(
|
||||
"42000501 3f800000",
|
||||
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(0x3f800000u)));",
|
||||
),
|
||||
(
|
||||
"40000501 40000000",
|
||||
"v0 = asuint(mad(asfloat(v1), asfloat(0x40000000u), asfloat(v2)));",
|
||||
),
|
||||
(
|
||||
"5a000501 3f800000",
|
||||
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(0x3f800000u)));",
|
||||
),
|
||||
(
|
||||
"58000501 40000000",
|
||||
"v0 = asuint(mad(asfloat(v1), asfloat(0x40000000u), asfloat(v2)));",
|
||||
),
|
||||
];
|
||||
// VS: s_swappc_b64 s[4:5], s[4:5]; exp pos0, v4, v5, v6, v7 done; s_endpgm
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
for (hex, line) in cases {
|
||||
// PS: <instruction>; exp mrt0, v0, off, off, off done; s_endpgm
|
||||
let ps = decode(&words(&format!("{hex} f8000801 00000000 bf810000"))).unwrap();
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{hex}: {e}"));
|
||||
assert!(
|
||||
t.ps_hlsl.contains(&format!(" {line}\n")),
|
||||
"{hex}:\n{}",
|
||||
t.ps_hlsl
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions beyond the prototype: 32-lane execution-mask bookkeeping has no HLSL counterpart
|
||||
/// (as the 64-lane form), and a compressed export with its second half disabled exports zeros
|
||||
/// there. Encodings from llvm-mc (gfx1030, wave32).
|
||||
#[test]
|
||||
fn wave32_mask_bookkeeping_and_half_compressed_exports() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
// s_mov_b32 s94, exec_lo; s_wqm_b32 exec_lo, exec_lo; v_mov_b32_e32 v0, s2;
|
||||
// s_and_b32 exec_lo, exec_lo, s94; exp mrt0, v0, v0, off, off done compr vm; s_endpgm
|
||||
let ps = decode(&words(
|
||||
"bede037e befe097e 7e000202 877e5e7e f8001c03 00000000 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(t.ps_hlsl.contains(" v0 = s2;\n"), "{}", t.ps_hlsl);
|
||||
assert!(
|
||||
t.ps_hlsl.contains(
|
||||
"float4 exp0_mrt0 = float4(f16tof32(v0 & 0xffffu), f16tof32(v0 >> 16), 0.0f, 0.0f);"
|
||||
),
|
||||
"{}",
|
||||
t.ps_hlsl
|
||||
);
|
||||
assert!(
|
||||
!t.ps_hlsl.contains("s94 ="),
|
||||
"the mask copy must not be emitted:\n{}",
|
||||
t.ps_hlsl
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user