mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 06:32:50 +00:00
Compare commits
114
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4f45573cf | ||
|
|
0766307acc | ||
|
|
3c8b6bad97 | ||
|
|
d4c29cd7dd | ||
|
|
938cbd3028 | ||
|
|
c9505e53e2 | ||
|
|
02eb8046a1 | ||
|
|
4a0b5d4ded | ||
|
|
7c88e5d655 | ||
|
|
bb318ed2ba | ||
|
|
b1b57cf16a | ||
|
|
cdcc55c33e | ||
|
|
0730f4dbbf | ||
|
|
6f27da3ccc | ||
|
|
6236996f41 | ||
|
|
05f2526d27 | ||
|
|
5131de9cd6 | ||
|
|
fec13fa27a | ||
|
|
68503a674c | ||
|
|
82cb66e80f | ||
|
|
06dbe2946d | ||
|
|
14d5083f0f | ||
|
|
0115af5c04 | ||
|
|
5b7ffec90a | ||
|
|
48c5d20aa9 | ||
|
|
8049c36f51 | ||
|
|
94783fa603 | ||
|
|
c91036f879 | ||
|
|
c1cea65e17 | ||
|
|
223a754eb7 | ||
|
|
d195978903 | ||
|
|
823a5812a0 | ||
|
|
710a2e1e73 | ||
|
|
de92766b29 | ||
|
|
4d44765363 | ||
|
|
6de750b152 | ||
|
|
adf10db015 | ||
|
|
4e4a6b36be | ||
|
|
403a67747f | ||
|
|
dc3b02b62f | ||
|
|
d847d7ea6e | ||
|
|
0fdb995892 | ||
|
|
b55a4c24ef | ||
|
|
d7f7d586d3 | ||
|
|
d01627b3de | ||
|
|
291c9807ee | ||
|
|
1d363c3c34 | ||
|
|
e74ebbe30b | ||
|
|
26eba92b87 | ||
|
|
05143d6295 | ||
|
|
d6a65b2940 | ||
|
|
1cc7f01fec | ||
|
|
6a4fc7cce1 | ||
|
|
b5b24347e9 | ||
|
|
f8eb976102 | ||
|
|
bbb59324c0 | ||
|
|
34b16ca65c | ||
|
|
fd0e427c7b | ||
|
|
314d1f5874 | ||
|
|
7adb978683 | ||
|
|
9d5de05055 | ||
|
|
3348d34e6f | ||
|
|
8e9ec8b9d1 | ||
|
|
b54f5ef0aa | ||
|
|
4d5207afd8 | ||
|
|
27daa701c1 | ||
|
|
c985c3fa17 | ||
|
|
6ad1602a3d | ||
|
|
82cafe9664 | ||
|
|
bf2c279dc7 | ||
|
|
3521dca45b | ||
|
|
131c8669cf | ||
|
|
2c8c63cf65 | ||
|
|
da16b36499 | ||
|
|
061568a6ee | ||
|
|
a03188315d | ||
|
|
95f6b52d9f | ||
|
|
7499d6f6c3 | ||
|
|
3a3f0c52af | ||
|
|
989bb79d6c | ||
|
|
d157f802d3 | ||
|
|
fb0544652b | ||
|
|
61943d23b6 | ||
|
|
947d6e4eaf | ||
|
|
bdcdd57c55 | ||
|
|
5b894777ce | ||
|
|
dc44c5c64b | ||
|
|
b9f6985d57 | ||
|
|
db40a1307d | ||
|
|
b174b45bed | ||
|
|
7504a5d48d | ||
|
|
2b858ab7c6 | ||
|
|
076f3e52aa | ||
|
|
e17e3bfc63 | ||
|
|
1915e2374c | ||
|
|
6545a25b7b | ||
|
|
d5514aa9d8 | ||
|
|
7623fde0e7 | ||
|
|
f2e6db03a9 | ||
|
|
3a14bd98ab | ||
|
|
d31b8ef20c | ||
|
|
81cfe69143 | ||
|
|
91fe3f345b | ||
|
|
0a722d2e60 | ||
|
|
0cf4e8a9e9 | ||
|
|
d8c117cdd3 | ||
|
|
9ef9537540 | ||
|
|
081f9c9e06 | ||
|
|
fbe1d3c4d1 | ||
|
|
9e35434f63 | ||
|
|
6e64737021 | ||
|
|
8b0b62a771 | ||
|
|
9500ed17e5 | ||
|
|
547b10250d |
No files matched your search
@@ -41,6 +41,8 @@ jobs:
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
# The generated status check must not depend on the host locale encoding.
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
@@ -65,7 +67,7 @@ jobs:
|
||||
cargo test --locked --workspace
|
||||
cargo test --locked --manifest-path experiments/x1/Cargo.toml
|
||||
scripts/audit/dependencies.sh
|
||||
scripts/audit/claims.sh
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
|
||||
- name: Inspect native CLI
|
||||
run: |
|
||||
cargo build --locked -p xenora
|
||||
|
||||
+28
-1
@@ -10,12 +10,36 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
|
||||
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
|
||||
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
|
||||
### Added
|
||||
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
|
||||
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
|
||||
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
|
||||
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
|
||||
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
|
||||
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). Part of #215.
|
||||
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
|
||||
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
|
||||
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
|
||||
@@ -175,6 +199,8 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
|
||||
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
|
||||
@@ -183,6 +209,7 @@ remains unsupported.
|
||||
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
|
||||
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
|
||||
|
||||
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
|
||||
|
||||
|
||||
Generated
+1
@@ -204,6 +204,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
"xenora-texture",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -9,7 +9,7 @@ Xenora is an open-source project written primarily in Rust that builds and verif
|
||||
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
|
||||
|
||||
> [!CAUTION]
|
||||
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft, Rockstar Games, Take-Two Interactive, or any other publisher or platform holder.
|
||||
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft or any other publisher or platform holder.
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
|
||||
@@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
|
||||
@@ -454,10 +454,16 @@ fn run_imports_sync(
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
|
||||
let mut lines = csv_text.lines();
|
||||
let has_import_kind = lines
|
||||
.next()
|
||||
.is_some_and(|header| header.ends_with(",import_kind"));
|
||||
let header = lines.next().unwrap_or_default();
|
||||
let has_import_kind = header.ends_with(",import_kind");
|
||||
// Binding does not resolve delay-loaded imports, so the backlog omits them.
|
||||
let table_column = header
|
||||
.split(',')
|
||||
.position(|column| column == "import_table");
|
||||
for line in lines {
|
||||
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
|
||||
continue;
|
||||
}
|
||||
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
|
||||
// We re-query the live registry rather than trusting cached status.
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn backlog_leaves_out_delay_loaded_imports() {
|
||||
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
|
||||
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
|
||||
let xenora = |arguments: &[&str]| {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
|
||||
.args(arguments)
|
||||
.arg("--report")
|
||||
.arg(&report)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
};
|
||||
xenora(&["probe", "--pe", fixture]);
|
||||
xenora(&["imports", "sync"]);
|
||||
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
|
||||
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
|
||||
std::fs::remove_dir_all(report).unwrap();
|
||||
|
||||
assert_eq!(listed.matches(",delayed,").count(), 3);
|
||||
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
|
||||
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
|
||||
assert!(!backlog.contains("fixture-delay"), "{backlog}");
|
||||
}
|
||||
+131
-84
@@ -4,18 +4,18 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
VectorSource,
|
||||
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSource, VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
pub use xenora_isa::semantics::VectorBinary;
|
||||
use xenora_isa::semantics::{FORM_IDS, OperandRule};
|
||||
pub use xenora_isa::semantics::{VectorBinary, VectorLowering, VectorUnary, VectorVcc};
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
@@ -40,18 +40,11 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 10] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
@@ -317,30 +310,65 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
// AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8.
|
||||
if let Some(op) = VectorUnaryOp::from_word(first) {
|
||||
let dst = (first >> 17) as u8;
|
||||
let (src, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
return Ok((Instruction::VectorUnary { op, dst, src }, len));
|
||||
}
|
||||
if let Some(op) = VectorSwapOp::from_word(first) {
|
||||
if first & 0x100 == 0 {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
"expected a VGPR SRC0 for writeback",
|
||||
));
|
||||
}
|
||||
let dst = (first >> 17) as u8;
|
||||
let src = first as u8;
|
||||
return Ok((Instruction::VectorSwap { op, dst, src }, 4));
|
||||
}
|
||||
if let Some(op) = VectorCompareOp::from_word(first) {
|
||||
return vector_compare(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = VectorCompareVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
let sdst = first as u8;
|
||||
if sdst > VCC_LO {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
"expected a destination of s0-s105 or vcc_lo",
|
||||
));
|
||||
}
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
return Ok((
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
8,
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
return Ok((vop3_vgpr2(op, first, second)?, 8));
|
||||
}
|
||||
if S_MOV_B32.matches(first) {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if !matches!(dst, 0..=107 | 126..=127) {
|
||||
return Err(unsupported(
|
||||
"s_mov_b32",
|
||||
"expected a normal SGPR or EXEC/VCC destination",
|
||||
));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if let Some(op) = ScalarUnaryOp::from_word(first) {
|
||||
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
|
||||
let mnemonic = op.mnemonic();
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
match op.semantics().operands {
|
||||
OperandRule::Sop1Move if !matches!(dst, 0..=107 | 126..=127) => {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected a normal SGPR or EXEC/VCC destination",
|
||||
));
|
||||
}
|
||||
OperandRule::Sop1Sgpr if dst > 105 => {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
@@ -362,34 +390,45 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
if S_BRANCH.matches(first) {
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
if let Some(op) = ScalarImmediateOp::from_word(first) {
|
||||
// SOPK: SIMM16 in bits 0-15, SDST in bits 16-22; the word has no literal.
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(
|
||||
op.mnemonic(),
|
||||
"expected a normal SGPR destination",
|
||||
));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediate { op, dst, simm16 }, 4));
|
||||
}
|
||||
if let Some(op) = ScalarImmediateCompareOp::from_word(first) {
|
||||
let src = ((first >> 16) & 0x7f) as u8;
|
||||
if src > 105 {
|
||||
return Err(unsupported(op.mnemonic(), "expected a normal SGPR operand"));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
|
||||
}
|
||||
if let Some(op) = SoppControlOp::from_word(first) {
|
||||
let immediate = first as u16;
|
||||
if op
|
||||
.required_immediate()
|
||||
.is_some_and(|exact| immediate != exact)
|
||||
{
|
||||
let detail = if op == SoppControlOp::EndProgram {
|
||||
"expected zero immediate"
|
||||
} else {
|
||||
"expected vmcnt(0) alone"
|
||||
};
|
||||
return Err(unsupported(op.mnemonic(), detail));
|
||||
}
|
||||
let instruction = op.decode(|| branch_target(immediate, offset, op.mnemonic()))?;
|
||||
return Ok((instruction, 4));
|
||||
}
|
||||
if let Some(op) = ScalarAluOp::from_word(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
return Ok((
|
||||
Instruction::BranchSccZero { target },
|
||||
S_CBRANCH_SCC0.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_EXECZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_execz")?;
|
||||
return Ok((
|
||||
Instruction::BranchExecZero { target },
|
||||
S_CBRANCH_EXECZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_VCCZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_vccz")?;
|
||||
return Ok((
|
||||
Instruction::BranchVccZero { target },
|
||||
S_CBRANCH_VCCZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluOp::from_word(first) {
|
||||
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
|
||||
let dst = ((first >> 17) & 0xff) as u8;
|
||||
@@ -400,7 +439,10 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
|
||||
(VectorSource::Register(src0), 4)
|
||||
}
|
||||
_ => vector_src0(first, bytes, op.assembly_name())?,
|
||||
OperandRule::Vop2Vgpr | OperandRule::Vop2Vcc => {
|
||||
vector_src0(first, bytes, op.assembly_name())?
|
||||
}
|
||||
_ => unreachable!("non-VOP2 operand rule for VOP2 instruction"),
|
||||
};
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
@@ -426,15 +468,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
V_MUL_F32.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_WAITCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_WAITCNT.byte_len(),
|
||||
0xbf8c_3f70,
|
||||
Instruction::WaitLoad,
|
||||
"expected vmcnt(0) alone",
|
||||
);
|
||||
}
|
||||
if S_WAITCNT_VSCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
@@ -444,15 +477,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
"expected null, 0",
|
||||
);
|
||||
}
|
||||
if S_ENDPGM.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_ENDPGM.byte_len(),
|
||||
0xbf81_0000,
|
||||
Instruction::EndProgram,
|
||||
"expected zero immediate",
|
||||
);
|
||||
}
|
||||
|
||||
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
|
||||
}
|
||||
@@ -509,11 +533,11 @@ fn scalar_source(
|
||||
}
|
||||
|
||||
fn branch_target(
|
||||
first: u32,
|
||||
immediate: u16,
|
||||
offset: usize,
|
||||
mnemonic: &'static str,
|
||||
) -> Result<usize, DecodeErrorKind> {
|
||||
let displacement = first as u16 as i16;
|
||||
let displacement = immediate as i16;
|
||||
let words = usize::try_from(displacement)
|
||||
.map_err(|_| unsupported(mnemonic, "expected a forward branch"))?;
|
||||
offset
|
||||
@@ -640,11 +664,26 @@ fn vector_compare(
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
let mnemonic = op.assembly_name();
|
||||
if op.semantics().width == 64 {
|
||||
// Guide §3.6.3 requires even SGPR bases. Reject invalid selectors
|
||||
// before reading a literal word or considering the execution mask.
|
||||
let source = first & 0x1ff;
|
||||
if src1 == 255
|
||||
|| !matches!(source, 0..=104 | 128..=208 | 256..=510)
|
||||
|| (source <= 104 && !source.is_multiple_of(2))
|
||||
{
|
||||
return Err(unsupported(mnemonic, "invalid 64-bit compare source"));
|
||||
}
|
||||
}
|
||||
if op.semantics().width == 16 && first & 0x1ff == 255 {
|
||||
return Err(unsupported(mnemonic, "literal in 16-bit compare"));
|
||||
}
|
||||
let (src0, len) = vector_src0(first, bytes, mnemonic)?;
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
|
||||
/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an
|
||||
/// inline integer -16..64 or a literal word; everything else is unsupported.
|
||||
fn vector_src0(
|
||||
first: u32,
|
||||
@@ -704,29 +743,37 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
Ok((Instruction::MoveB32 { dst, src }, len))
|
||||
}
|
||||
|
||||
/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1
|
||||
/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources
|
||||
/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is
|
||||
/// the gfx1030 assembler's inline-zero operand encoding.
|
||||
fn vop3_vgpr2(
|
||||
op: VectorAluVop3Op,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<Instruction, DecodeErrorKind> {
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
Ok(Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: first as u8,
|
||||
src0,
|
||||
src1,
|
||||
})
|
||||
}
|
||||
|
||||
/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4).
|
||||
/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL,
|
||||
/// CLAMP, OMOD and NEG are clear.
|
||||
fn vop3_vgpr2_sources(
|
||||
mnemonic: &'static str,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<(u8, u8), DecodeErrorKind> {
|
||||
let src0 = second & 0x1ff;
|
||||
let src1 = (second >> 9) & 0x1ff;
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
mnemonic,
|
||||
"expected two VGPR sources and no modifiers",
|
||||
));
|
||||
}
|
||||
Ok(Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: first as u8,
|
||||
src0: src0 as u8,
|
||||
src1: src1 as u8,
|
||||
})
|
||||
Ok((src0 as u8, src1 as u8))
|
||||
}
|
||||
|
||||
fn scalar_form(
|
||||
|
||||
+492
-52
@@ -4,13 +4,13 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorSource, decode,
|
||||
decode_at,
|
||||
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
VectorInteger,
|
||||
BranchCondition, CompareSource, CompareWidth, Comparison, Op, ScalarAlu, ScalarImmediate,
|
||||
ScalarUnary, Source, VectorAlu, VectorInteger, VectorUnary,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
@@ -71,6 +71,127 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
assert_eq!(instructions, wanted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_wave32_vop3_compares_from_llvm_words() {
|
||||
use VectorCompareVop3Op::*;
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -mattr=+wavefrontsize32 -show-encoding
|
||||
let cases: [(u32, VectorCompareVop3Op, u8); 19] = [
|
||||
// v_cmp_lt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x81,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd481_0004, CmpLtI32, 4),
|
||||
// v_cmp_eq_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x82,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd482_0004, CmpEqI32, 4),
|
||||
// v_cmp_le_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x83,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd483_0004, CmpLeI32, 4),
|
||||
// v_cmp_gt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x84,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd484_0004, CmpGtI32, 4),
|
||||
// v_cmp_ne_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x85,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd485_0004, CmpNeI32, 4),
|
||||
// v_cmp_ge_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x86,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd486_0004, CmpGeI32, 4),
|
||||
// v_cmp_lt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc1,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c1_0004, CmpLtU32, 4),
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0004, CmpEqU32, 4),
|
||||
// v_cmp_le_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc3,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c3_0004, CmpLeU32, 4),
|
||||
// v_cmp_gt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc4,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c4_0004, CmpGtU32, 4),
|
||||
// v_cmp_ne_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc5,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c5_0004, CmpNeU32, 4),
|
||||
// v_cmp_ge_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc6,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c6_0004, CmpGeU32, 4),
|
||||
// v_cmp_f_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x80,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd480_0004, CmpFI32, 4),
|
||||
// v_cmp_t_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x87,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd487_0004, CmpTI32, 4),
|
||||
// v_cmp_f_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc0,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c0_0004, CmpFU32, 4),
|
||||
// v_cmp_t_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc7,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c7_0004, CmpTU32, 4),
|
||||
// v_cmp_eq_u32_e64 s0, v1, v2 ; encoding: [0x00,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0000, CmpEqU32, 0),
|
||||
// v_cmp_eq_u32_e64 s105, v1, v2 ; encoding: [0x69,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0069, CmpEqU32, 105),
|
||||
// v_cmp_eq_u32_e64 vcc_lo, v1, v2 ; encoding: [0x6a,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_006a, CmpEqU32, 106),
|
||||
];
|
||||
for (first, op, sdst) in cases {
|
||||
let code: Vec<_> = [first, 0x0202_0501]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let decoded = decode(Architecture::Gfx1030, &code).unwrap();
|
||||
let dst = if sdst == 106 {
|
||||
"vcc_lo".to_owned()
|
||||
} else {
|
||||
format!("s{sdst}")
|
||||
};
|
||||
assert_eq!(
|
||||
decoded,
|
||||
[DecodedInstruction {
|
||||
offset: 0,
|
||||
byte_len: 8,
|
||||
instruction: Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0: 1,
|
||||
src1: 2
|
||||
},
|
||||
}],
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[0].instruction.to_string(),
|
||||
format!("{} {dst}, v1, v2", op.assembly_name())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_noncanonical_wave32_vop3_compare_operands() {
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2
|
||||
let first = 0xd4c2_0004;
|
||||
let second = 0x0202_0501;
|
||||
let rejects = |first, second| {
|
||||
let code: Vec<_> = [first, second]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let error = decode(Architecture::Gfx1030, &code).unwrap_err();
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "v_cmp_eq_u32_e64",
|
||||
..
|
||||
}
|
||||
),
|
||||
"{first:#010x} {second:#010x}: {error}"
|
||||
);
|
||||
};
|
||||
|
||||
// Includes vcc_hi (107), TTMPs (108-123), null (124), m0 (125) and EXEC (126-127).
|
||||
for sdst in 107..=255 {
|
||||
rejects((first & !0xff) | sdst, second);
|
||||
}
|
||||
for bit in 8..=15 {
|
||||
// ABS, OP_SEL and CLAMP.
|
||||
rejects(first | (1 << bit), second);
|
||||
}
|
||||
for bit in 27..=31 {
|
||||
// OMOD and NEG.
|
||||
rejects(first, second | (1 << bit));
|
||||
}
|
||||
rejects(first, second ^ (1 << 18)); // SRC2 = 129 instead of 128.
|
||||
for shift in [0, 9] {
|
||||
for selector in [4, 106, 128, 240, 255] {
|
||||
// SGPR, VCC_LO, inline integer/float, literal.
|
||||
rejects(first, (second & !(0x1ff << shift)) | (selector << shift));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
|
||||
let lengths = [8, 4, 8, 8, 8, 4, 4];
|
||||
@@ -303,6 +424,44 @@ fn reference_scalar(scalar: ScalarSource) -> Source {
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_comparison(op: VectorCompareOp) -> Comparison {
|
||||
Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_vector_integer(op: VectorAluOp) -> VectorInteger {
|
||||
match op {
|
||||
VectorAluOp::CndmaskB32 => VectorInteger::Select,
|
||||
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
|
||||
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
|
||||
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_op(instruction: Instruction) -> Op {
|
||||
match instruction {
|
||||
Instruction::BufferLoadDword {
|
||||
@@ -330,6 +489,22 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
src: VectorSource::Scalar(src),
|
||||
} => Op::MoveScalar(dst, src),
|
||||
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
|
||||
Instruction::VectorUnary { op, dst, src } => Op::VectorUnary(
|
||||
match op {
|
||||
VectorUnaryOp::NotB32 => VectorUnary::Not,
|
||||
VectorUnaryOp::BfrevB32 => VectorUnary::ReverseBits,
|
||||
VectorUnaryOp::FfbhU32 => VectorUnary::FindFirstOneFromMsb,
|
||||
VectorUnaryOp::FfblB32 => VectorUnary::FindFirstOneFromLsb,
|
||||
VectorUnaryOp::FfbhI32 => VectorUnary::FindSignChange,
|
||||
},
|
||||
dst,
|
||||
match src {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
),
|
||||
Instruction::VectorSwap { dst, src, .. } => Op::Swap(dst, src),
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
@@ -375,16 +550,27 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
reference_scalar(src0),
|
||||
reference_scalar(src1),
|
||||
),
|
||||
// The reference's VOP3 add; it is the only VOP3 variant so far.
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
reference_vector_integer(op.base()),
|
||||
dst,
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = reference_scalar(src);
|
||||
let unary = match op {
|
||||
ScalarUnaryOp::MovB32 => return Op::ScalarMove(dst, src),
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
@@ -396,10 +582,9 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src),
|
||||
),
|
||||
};
|
||||
Op::ScalarUnary(unary, dst, src)
|
||||
}
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
|
||||
// The reference keeps CompareEqual for EQ and uses its VOPC relation
|
||||
@@ -416,6 +601,25 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::ScalarImmediate { op, dst, simm16 } => Op::ScalarImmediate(
|
||||
match op {
|
||||
ScalarImmediateOp::MovkI32 => ScalarImmediate::Move,
|
||||
ScalarImmediateOp::CmovkI32 => ScalarImmediate::ConditionalMove,
|
||||
ScalarImmediateOp::AddkI32 => ScalarImmediate::Add,
|
||||
ScalarImmediateOp::MulkI32 => ScalarImmediate::Multiply,
|
||||
},
|
||||
dst,
|
||||
simm16,
|
||||
),
|
||||
Instruction::ScalarImmediateCompare { op, src, simm16 } => Op::ScalarImmediate(
|
||||
ScalarImmediate::Compare(Comparison {
|
||||
// The reference's VOPC relation offsets, as for SOPC above.
|
||||
offset: op.relation() as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
}),
|
||||
src,
|
||||
simm16,
|
||||
),
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::SccZero,
|
||||
@@ -470,25 +674,29 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
panic!("compute reference matrix received a graphics/image instruction")
|
||||
}
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
|
||||
Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
},
|
||||
match src0 {
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
let comparison = reference_comparison(op);
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
};
|
||||
match op.semantics().width {
|
||||
16 => Op::WideCompare(comparison, CompareWidth::Half, src0, src1),
|
||||
32 => Op::Compare(comparison, src0, src1),
|
||||
64 => Op::WideCompare(comparison, CompareWidth::Double, src0, src1),
|
||||
width => panic!("unexpected VOPC operand width {width}"),
|
||||
}
|
||||
}
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::CompareVop3(
|
||||
sdst,
|
||||
reference_comparison(op.base()),
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAlu {
|
||||
@@ -497,21 +705,7 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
match op {
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
|
||||
},
|
||||
reference_vector_integer(op),
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
@@ -545,15 +739,21 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-vcc.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 104, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 169, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -611,6 +811,12 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
s_or_b32 s103, s3, 0x80000000
|
||||
s_xor_b32 s102, s104, -16
|
||||
s_xor_b32 s7, s7, lit(0x1)
|
||||
s_movk_i32 s105, 0xffff
|
||||
s_movk_i32 s8, 0
|
||||
s_cmovk_i32 s105, 0x8000
|
||||
s_addk_i32 s9, 0x7fff
|
||||
s_addk_i32 s105, 0xffff
|
||||
s_mulk_i32 s8, 0x8001
|
||||
v_mov_b32_e32 v255, s105
|
||||
v_mov_b32_e32 v0, s0
|
||||
v_mov_b32_e32 v128, vcc_lo
|
||||
@@ -636,6 +842,15 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
|
||||
}
|
||||
}
|
||||
// Every SOPK compare on the lowest and highest readable SGPR.
|
||||
for relation in ["eq", "lg", "gt", "ge", "lt", "le"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for register in ["s0", "s7", "s8", "s105"] {
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} {register}, 0x8000").unwrap();
|
||||
}
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} s9, 0").unwrap();
|
||||
}
|
||||
}
|
||||
for value in -16..=64 {
|
||||
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
|
||||
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
|
||||
@@ -766,7 +981,7 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_026b], // VOP1 VCC_HI source
|
||||
&[0x7da2_0501], // v_cmpx_eq_u32_e32
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_eq_i32_e64 with SRC2 = 0
|
||||
&[0x8788_0908], // s_and_b64
|
||||
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
|
||||
&[0x806c_0908], // SOP2 TTMP destination
|
||||
@@ -835,7 +1050,7 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
|
||||
// VOPC and registry VOP2 forms print SRC0 as bits.
|
||||
mnemonic
|
||||
if mnemonic.starts_with("v_cmp_")
|
||||
|| VectorAluOp::ALL
|
||||
@@ -843,10 +1058,11 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
.any(|op| op.assembly_name() == mnemonic) =>
|
||||
{
|
||||
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
|
||||
parts[1] = match literal_bits(&parts[1]) {
|
||||
let src = if parts.len() == 5 { 2 } else { 1 };
|
||||
parts[src] = match literal_bits(&parts[src]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
None => parts[1].parse::<i32>().map_or_else(
|
||||
|_| parts[1].clone(),
|
||||
None => parts[src].parse::<i32>().map_or_else(
|
||||
|_| parts[src].clone(),
|
||||
|value| format!("0x{:x}", value as u32),
|
||||
),
|
||||
};
|
||||
@@ -956,14 +1172,16 @@ fn decodes_inline_negative_and_register_sources() {
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
dst: 10,
|
||||
src: ScalarSource::Immediate(5)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[1].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
dst: 11,
|
||||
src: ScalarSource::Immediate(0xffff_fffd)
|
||||
}
|
||||
@@ -997,7 +1215,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
let valid = 0xbee9_0380u32.to_le_bytes();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &valid).unwrap()[0].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
dst: 105,
|
||||
src: ScalarSource::Immediate(0)
|
||||
}
|
||||
@@ -1051,3 +1270,224 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() {
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding
|
||||
const VOP3_INTEGER_ENCODINGS: [(VectorAluVop3Op, u32); 11] = [
|
||||
// v_mul_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x09,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulI32I24, 0xd50900ff),
|
||||
// v_mul_hi_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0a,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiI32I24, 0xd50a00ff),
|
||||
// v_mul_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0b,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulU32U24, 0xd50b00ff),
|
||||
// v_mul_hi_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0c,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiU32U24, 0xd50c00ff),
|
||||
// v_min_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x11,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinI32, 0xd51100ff),
|
||||
// v_max_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x12,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxI32, 0xd51200ff),
|
||||
// v_min_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x13,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinU32, 0xd51300ff),
|
||||
// v_max_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x14,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxU32, 0xd51400ff),
|
||||
// v_xnor_b32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x1e,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::XnorB32, 0xd51e00ff),
|
||||
// v_sub_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x26,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubNcU32, 0xd52600ff),
|
||||
// v_subrev_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x27,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubrevNcU32, 0xd52700ff),
|
||||
];
|
||||
const VOP3_INTEGER_SOURCE_WORD: u32 = 0x0202_ff00;
|
||||
|
||||
#[test]
|
||||
fn decodes_registry_vop3_integer_encodings() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let bytes = [first.to_le_bytes(), VOP3_INTEGER_SOURCE_WORD.to_le_bytes()].concat();
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_eq!(decoded[0].byte_len, 8);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: 255,
|
||||
src0: 0,
|
||||
src1: 127,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_vop3_integer_fixture() {
|
||||
use VectorAluVop3Op::*;
|
||||
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
|
||||
let decoded = decode(Architecture::Gfx1030, code).unwrap();
|
||||
let expected = [
|
||||
(MulI32I24, 2, 1, 1),
|
||||
(MulHiI32I24, 3, 2, 1),
|
||||
(MulU32U24, 4, 2, 1),
|
||||
(MulHiU32U24, 255, 4, 1),
|
||||
(MinI32, 6, 1, 2),
|
||||
(MaxI32, 7, 1, 4),
|
||||
(MinU32, 8, 3, 1),
|
||||
(MaxU32, 9, 255, 2),
|
||||
(XnorB32, 10, 1, 255),
|
||||
(SubNcU32, 11, 6, 10),
|
||||
(SubrevNcU32, 1, 1, 9),
|
||||
];
|
||||
let actual: Vec<_> = decoded
|
||||
.iter()
|
||||
.filter_map(|decoded| match decoded.instruction {
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Some((decoded.offset, decoded.byte_len, op, dst, src0, src1)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let expected: Vec<_> = expected
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (op, dst, src0, src1))| (12 + 8 * index, 8, op, dst, src0, src1))
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_registry_vop3_integer_modifiers_and_other_sources() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let second = VOP3_INTEGER_SOURCE_WORD;
|
||||
let reject = |first: u32, second: u32| {
|
||||
let bytes = [first.to_le_bytes(), second.to_le_bytes()].concat();
|
||||
let error = decode(Architecture::Gfx1030, &bytes)
|
||||
.expect_err(&format!("{op:?} accepted {first:#010x} {second:#010x}"));
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, .. }
|
||||
if mnemonic == op.assembly_name()
|
||||
));
|
||||
};
|
||||
|
||||
// First word: ABS[10:8], OP_SEL[14:11], CLAMP[15].
|
||||
for bit in 8..=15 {
|
||||
reject(first | (1 << bit), second);
|
||||
}
|
||||
// Second word: OMOD[28:27], NEG[31:29].
|
||||
for bit in 27..=31 {
|
||||
reject(first, second | (1 << bit));
|
||||
}
|
||||
|
||||
reject(first, second & !0x1ff); // SRC0 = s0
|
||||
reject(first, (second & !(0x1ff << 9)) | (128 << 9)); // SRC1 = inline zero
|
||||
reject(first, second | (1 << 18)); // SRC2 = inline one
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
|
||||
use xenora_decoder::ScalarImmediateCompareOp;
|
||||
let decode_word = |word: u32| decode(Architecture::Gfx1030, &word.to_le_bytes());
|
||||
// Words assembled by LLVM for gfx1030 (llvm-mc --show-encoding).
|
||||
// s_movk_i32 s8, 0x8000
|
||||
let decoded = decode_word(0xb008_8000).unwrap();
|
||||
assert_eq!(decoded[0].byte_len, 4);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MovkI32,
|
||||
dst: 8,
|
||||
simm16: 0x8000
|
||||
}
|
||||
);
|
||||
// s_cmovk_i32 s105, 0xffff keeps the full 16 bits: the sign extension is
|
||||
// the translator's job, not the decoder's.
|
||||
assert_eq!(
|
||||
decode_word(0xb169_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::CmovkI32,
|
||||
dst: 105,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_cmpk_gt_u32 s0, 0x1234 and s_cmpk_le_i32 s7, 0xffff read SDST s0-s7.
|
||||
assert_eq!(
|
||||
decode_word(0xb580_1234).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkGtU32,
|
||||
src: 0,
|
||||
simm16: 0x1234
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb407_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkLeI32,
|
||||
src: 7,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_addk_i32 s9, 0x7fff and s_mulk_i32 s105, 0
|
||||
assert_eq!(
|
||||
decode_word(0xb789_7fff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::AddkI32,
|
||||
dst: 9,
|
||||
simm16: 0x7fff
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb869_0000).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MulkI32,
|
||||
dst: 105,
|
||||
simm16: 0
|
||||
}
|
||||
);
|
||||
// vcc_lo, exec_lo, null and ttmp0 as SDST, and s_cmpk_eq_i32 m0: refused.
|
||||
for (word, mnemonic, detail) in [
|
||||
(
|
||||
0xb06a_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07e_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07d_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb06c_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb1fc_0001,
|
||||
"s_cmpk_eq_i32",
|
||||
"expected a normal SGPR operand",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
decode_word(word).unwrap_err().kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, detail },
|
||||
"{word:#010x}"
|
||||
);
|
||||
}
|
||||
// Other SOPK opcodes (opcode 1 s_version, 17 s_getreg_b32) stay unsupported.
|
||||
for word in [0xb080_0000u32, 0xb888_0000] {
|
||||
assert!(decode_word(word).is_err(), "{word:#010x}");
|
||||
}
|
||||
// The fixed store fence is still the one decoded SOPK word outside the registry.
|
||||
assert_eq!(
|
||||
decode_word(0xbbfd_0000).unwrap()[0].instruction,
|
||||
Instruction::WaitStore
|
||||
);
|
||||
}
|
||||
@@ -44,12 +44,25 @@ TOP_KEYS = {
|
||||
# An encoding variant is another encoding of a form already in the registry (for
|
||||
# example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base
|
||||
# form, the encoding family, its opcode there and the operand rule of that
|
||||
# encoding. It inherits the base form's operation, signedness and effects.
|
||||
# encoding. The rule may redirect the base form's mask to an explicit destination.
|
||||
VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"}
|
||||
# The assembler suffix LLVM prints for a variant's encoding family.
|
||||
ASSEMBLY_SUFFIX = {"VOP3": "_e64"}
|
||||
|
||||
# Control effects select an existing typed instruction and its operand contract.
|
||||
# The XML records SCC as a separate implicit input. VCC and EXEC predicates
|
||||
# have fieldless mask inputs instead.
|
||||
CONTROL_OPERATIONS = {
|
||||
"end_program": ("EndProgram", "sopp_end", None),
|
||||
"branch": ("Branch", "sopp_branch", None),
|
||||
"branch_scc_zero": ("BranchSccZero", "sopp_branch", None),
|
||||
"branch_vcc_zero": ("BranchVccZero", "sopp_branch", "OPR_VCC"),
|
||||
"branch_exec_zero": ("BranchExecZero", "sopp_branch", "OPR_SDST_EXEC"),
|
||||
"wait_load": ("WaitLoad", "sopp_wait", None),
|
||||
}
|
||||
|
||||
OPERATIONS = {
|
||||
**{name: variant for name, (variant, _, _) in CONTROL_OPERATIONS.items()},
|
||||
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
|
||||
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
|
||||
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
|
||||
@@ -61,6 +74,7 @@ OPERATIONS = {
|
||||
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
|
||||
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
|
||||
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
|
||||
"mov": "Move", "cmov": "ConditionalMove", "swap": "Swap",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
@@ -75,10 +89,13 @@ RELATIONS = {
|
||||
}
|
||||
# F and T exist only as VOPC compares (guide Table 59 offsets 0 and 7).
|
||||
VECTOR_ONLY_RELATIONS = {"f", "t"}
|
||||
# Guide 12.9 Table 59 and Table 61: a 32-bit integer VOPC compare's opcode is
|
||||
# its group base (128 for _I32, 192 for _U32) plus its relation's offset. This
|
||||
# is the guide's opcode layout, not a reading of the mnemonic.
|
||||
VOPC_INTEGER_BASES = {"signed": 128, "unsigned": 192}
|
||||
# Guide 12.9 Tables 59 and 61: integer VOPC opcodes are the group base
|
||||
# for the operand width and signedness plus the relation offset.
|
||||
VOPC_INTEGER_BASES = {
|
||||
16: {"signed": 136, "unsigned": 168},
|
||||
32: {"signed": 128, "unsigned": 192},
|
||||
64: {"signed": 160, "unsigned": 224},
|
||||
}
|
||||
VOPC_RELATION_OFFSETS = {"f": 0, "lt": 1, "eq": 2, "le": 3, "gt": 4, "lg": 5, "ge": 6, "t": 7}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
@@ -96,7 +113,7 @@ COMPARE_PRIMITIVES = {
|
||||
# the signedness their primitive names, and their S1 is an unsigned count.
|
||||
LOGICAL = {
|
||||
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm", "swap",
|
||||
}
|
||||
ARITHMETIC = {
|
||||
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
|
||||
@@ -106,7 +123,7 @@ SHIFTS = {"lshl", "lshr", "ashr"}
|
||||
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
|
||||
CONTROL_S1 = SHIFTS | {"bfe"}
|
||||
# Operations that always read SCC: the select condition. They need carry_in scc.
|
||||
SCC_READERS = {"cselect"}
|
||||
SCC_READERS = {"cselect", "cmov"}
|
||||
# XML number formats a source may have for each declared signedness.
|
||||
SOURCE_FORMATS = {
|
||||
"signed": {"FMT_NUM_I32"},
|
||||
@@ -123,7 +140,7 @@ SHIFT_AMOUNTS = {1, 2, 3, 4}
|
||||
SOURCE_ORDER_KEY = "source_order"
|
||||
SOURCE_ORDERS = {"reversed"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc", "vcc": "Vcc"}
|
||||
SCC = {
|
||||
"unchanged": "Unchanged",
|
||||
"carry_out": "CarryOut",
|
||||
@@ -133,16 +150,19 @@ SCC = {
|
||||
"relation": "Relation",
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
# lane_mask: the Wave32 VOPC result written to VCC_LO (vcc only; EXEC writes
|
||||
# such as v_cmpx have no contract yet, so exec must stay unchanged).
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
|
||||
# lane_mask: the Wave32 compare or carry result written to VCC_LO.
|
||||
# sdst_lane_mask: the Wave32 compare result written to explicit VOP3A SDST.
|
||||
# EXEC writes such as v_cmpx have no contract, so exec must stay unchanged.
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask", "sdst_lane_mask": "SdstLaneMask"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# Which wave declaration each operand-rule kind must make. The decoder has no
|
||||
# wave-size input, so "wave32" is only true where the caller's ABI fixes the
|
||||
# wave size: the lane-mask compares, whose one entry point is the Wave32
|
||||
# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other
|
||||
# kind must be "any".
|
||||
WAVE_BY_KIND = {"vector_compare": "wave32"}
|
||||
# The synthetic compute fixture ABI fixes the wave size for these operand-rule
|
||||
# kinds and for the VCC-reading VOP2 rule. Other forms declare "any".
|
||||
WAVE_BY_KIND = {"control": "wave32", "vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"}
|
||||
VCC_VECTOR_PRIMITIVES = {
|
||||
("cselect", "bitwise"): "Select",
|
||||
("add", "unsigned"): "AddCarry",
|
||||
("sub", "unsigned"): "SubtractBorrow",
|
||||
}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
@@ -163,7 +183,6 @@ PINNED_DOCUMENTS = {
|
||||
"file": "amdgpu_isa_rdna2.xml",
|
||||
},
|
||||
}
|
||||
WIDTHS = {32}
|
||||
|
||||
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
|
||||
# A form whose declaration is not a row here has no primitive and is rejected.
|
||||
@@ -183,6 +202,7 @@ PRIMITIVES = {
|
||||
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
|
||||
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
|
||||
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
|
||||
("mov", "bitwise"): ("unchanged", "mov_b32", False),
|
||||
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
|
||||
("brev", "bitwise"): ("unchanged", "brev_b32", False),
|
||||
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
|
||||
@@ -208,6 +228,22 @@ PRIMITIVES = {
|
||||
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
|
||||
}
|
||||
|
||||
# SOPK forms (operation, signedness) -> (SCC effect, primitive, reads SCC). D is
|
||||
# SDST and the immediate is SIMM16 sign-extended (guide 12.2); `sext_simm16` is
|
||||
# the sign extension, so a move or conditional move writes it unchanged.
|
||||
IMMEDIATE_PRIMITIVES = {
|
||||
("mov", "signed"): ("unchanged", "sext_simm16", False),
|
||||
("cmov", "signed"): ("unchanged", "sext_simm16", True),
|
||||
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
|
||||
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
|
||||
}
|
||||
# SOPK compares: the opcode is the group base (3 signed, 9 unsigned) plus the
|
||||
# relation's index in this order (guide 13.1.2).
|
||||
SOPK_COMPARE_BASES = {"signed": 3, "unsigned": 9}
|
||||
SOPK_RELATION_ORDER = ["eq", "lg", "gt", "ge", "lt", "le"]
|
||||
# Operand-rule kinds whose forms have a 16-bit immediate field.
|
||||
IMMEDIATE_KINDS = {"immediate", "immediate_compare"}
|
||||
|
||||
# Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their
|
||||
# MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged.
|
||||
VECTOR_PRIMITIVES = {
|
||||
@@ -240,8 +276,73 @@ UNSUPPORTED_COMBOS = {
|
||||
# which SOP2 groups under src_vcc and src_special).
|
||||
# VOP3 rules also name source classes and encoding fields they refuse.
|
||||
VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"}
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null", "dst_vcc_hi"} | VOP3_COMBOS
|
||||
VOP3_VGPR2_UNSUPPORTED = {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
}
|
||||
|
||||
VECTOR_UNARY_PRIMITIVES = {
|
||||
("not", "bitwise"): "Not",
|
||||
("brev", "bitwise"): "ReverseBits",
|
||||
("flbit", "unsigned"): "FindHighUnsigned",
|
||||
("ff1", "bitwise"): "FindLow",
|
||||
("flbit", "signed"): "FindHighSigned",
|
||||
}
|
||||
|
||||
OPERAND_RULES = {
|
||||
"sopp_end": {
|
||||
"rust": "SoppEnd",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [], "max_literals": 0, "immediate": 0},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"sopp_branch": {
|
||||
"rust": "SoppBranch",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [{"field": "SIMM16", "class": "label"}], "max_literals": 0},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"sopp_wait": {
|
||||
"rust": "SoppWait",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [{"field": "SIMM16", "class": "waitcnt"}],
|
||||
"max_literals": 0, "immediate": 0x3f70},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"vop1_vgpr": {
|
||||
"rust": "Vop1Vgpr",
|
||||
"enum": "VectorUnaryOp",
|
||||
"shape": {
|
||||
"family": "VOP1",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [{"field": "SRC0", "class": "vector_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector_unary",
|
||||
},
|
||||
"vop1_swap": {
|
||||
"rust": "Vop1Swap",
|
||||
"enum": "VectorSwapOp",
|
||||
"shape": {
|
||||
"family": "VOP1",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [{"field": "SRC0", "class": "vgpr"}],
|
||||
"max_literals": 0,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal",
|
||||
},
|
||||
"kind": "vector_swap",
|
||||
},
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
"enum": "ScalarAluOp",
|
||||
@@ -286,6 +387,46 @@ OPERAND_RULES = {
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
"sop1_move": {
|
||||
"rust": "Sop1Move",
|
||||
"enum": "ScalarUnaryOp",
|
||||
"shape": {
|
||||
"family": "SOP1",
|
||||
"dst": {"field": "SDST", "class": "sgpr_or_vcc_exec"},
|
||||
"src": [{"field": "SSRC0", "class": "scalar_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
"unsupported": UNSUPPORTED_COMBOS - {"two_literals", "dst_vcc", "dst_exec"},
|
||||
"kind": "unary",
|
||||
},
|
||||
"sopk_sgpr": {
|
||||
"rust": "SopkSgpr",
|
||||
"enum": "ScalarImmediateOp",
|
||||
"shape": {
|
||||
"family": "SOPK",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [{"field": "SIMM16", "class": "simm16"}],
|
||||
"max_literals": 0,
|
||||
},
|
||||
# SOPK never takes a literal dword; the decoder rejects SDST 106-127.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")},
|
||||
"kind": "immediate",
|
||||
},
|
||||
"sopk_compare": {
|
||||
"rust": "SopkCompare",
|
||||
"enum": "ScalarImmediateCompareOp",
|
||||
"shape": {
|
||||
"family": "SOPK",
|
||||
"src": [
|
||||
{"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
{"field": "SIMM16", "class": "simm16"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
},
|
||||
# The compared register is SDST (S0); the decoder rejects SDST 106-127.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")},
|
||||
"kind": "immediate_compare",
|
||||
},
|
||||
"vopc_vcc": {
|
||||
"rust": "VopcVcc",
|
||||
"enum": "VectorCompareOp",
|
||||
@@ -305,6 +446,44 @@ OPERAND_RULES = {
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
},
|
||||
"vopc_vcc_half": {
|
||||
"rust": "VopcVccHalf",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOPC",
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
},
|
||||
# The destination is implicitly vcc_lo; the decoder rejects these SRC0
|
||||
# selectors (the same vector_source as VOP2).
|
||||
"unsupported": {
|
||||
"src_literal", "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
"width": 16,
|
||||
},
|
||||
"vopc_vcc_pair": {
|
||||
"rust": "VopcVccPair",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOPC",
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_pair_or_inline_integer"},
|
||||
{"field": "VSRC1", "class": "vgpr_pair"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_vcc", "src_literal", "src_exec", "src_m0", "src_ttmp", "src_null",
|
||||
"src_float_inline", "src_special",
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
"width": 64,
|
||||
},
|
||||
"vop3_vgpr2": {
|
||||
"rust": "Vop3Vgpr2",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -322,16 +501,34 @@ OPERAND_RULES = {
|
||||
},
|
||||
# Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and
|
||||
# SRC2 the assembler's unused inline zero; the decoder rejects the rest.
|
||||
"unsupported": {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
},
|
||||
"unsupported": VOP3_VGPR2_UNSUPPORTED,
|
||||
"kind": "vector_vop3",
|
||||
# Only encoding variants of forms whose rule has this kind may use it.
|
||||
"variant_of": "vector",
|
||||
# The generated enum of this rule's variants; base() maps to "enum".
|
||||
"variant_enum": "VectorAluVop3Op",
|
||||
},
|
||||
"vop3_cmp_vgpr2": {
|
||||
"rust": "Vop3CmpVgpr2",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOP3",
|
||||
"dst": {"field": "VDST", "class": "sgpr", "min": 0, "max": 106},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vgpr"},
|
||||
{"field": "SRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
"variant_only": True,
|
||||
},
|
||||
"unsupported": VOP3_VGPR2_UNSUPPORTED | {
|
||||
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
},
|
||||
"kind": "vector_compare_vop3",
|
||||
"variant_of": "vector_compare",
|
||||
"variant_enum": "VectorCompareVop3Op",
|
||||
"vcc_transition": ("lane_mask", "sdst_lane_mask"),
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -352,6 +549,24 @@ OPERAND_RULES = {
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
"vop2_vcc": {
|
||||
"rust": "Vop2Vcc",
|
||||
"enum": "VectorAluOp",
|
||||
"shape": {
|
||||
"family": "VOP2",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
"vop2_vgpr2": {
|
||||
"rust": "Vop2Vgpr2",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -541,24 +756,35 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
implicit = set()
|
||||
vcc_writes = []
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
vcc_operands = []
|
||||
control_mask = CONTROL_OPERATIONS.get(form["operation"], (None, None, None))[2]
|
||||
mask_inputs = 0
|
||||
for field, data_format, kind, size, is_input, is_output, is_implicit, encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif control_mask and (field, kind, data_format, size, is_input, is_output, is_implicit, encoded) == (
|
||||
"", control_mask, "FMT_NUM_M64", 64, True, False, True, True
|
||||
):
|
||||
mask_inputs += 1
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
operands[field] = (data_format, kind, size, is_input, is_output)
|
||||
elif kind == "OPR_VCC":
|
||||
vcc_operands.append((data_format, size, is_input, is_output))
|
||||
else:
|
||||
implicit.add(kind)
|
||||
if kind == "OPR_VCC":
|
||||
vcc_writes.append((is_input, is_output))
|
||||
# The vocabulary states SCC effects and a lane-mask VCC write; any other
|
||||
# implicit XML operand (such as an EXEC write) is undeclared.
|
||||
if form["carry_in"] == "vcc":
|
||||
if vcc_operands.count(("FMT_NUM_M64", 64, True, False)) != 1:
|
||||
errors.append(f"{label}: carry_in vcc requires one implicit XML VCC input")
|
||||
if ("FMT_NUM_M64", 64, True, False) in vcc_operands:
|
||||
vcc_operands.remove(("FMT_NUM_M64", 64, True, False))
|
||||
if form["vcc"] == "lane_mask":
|
||||
# Exactly one fieldless VCC operand, written and not read.
|
||||
if vcc_writes != [(False, True)]:
|
||||
if vcc_operands != [("FMT_NUM_M64", 64, False, True)]:
|
||||
errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output")
|
||||
implicit.discard("OPR_VCC")
|
||||
elif vcc_operands:
|
||||
implicit.add("OPR_VCC")
|
||||
if control_mask and mask_inputs != 1:
|
||||
errors.append(f"{label}: expected one implicit {control_mask} input in the XML")
|
||||
if implicit:
|
||||
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
@@ -578,12 +804,37 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
data_format, kind, size, is_input, is_output = operands[field]
|
||||
if field == "SIMM16" and _rule_kind(form) == "control":
|
||||
expected_kind, expected_format = (
|
||||
("OPR_LABEL", "FMT_NUM_I16") if form["operands"] == "sopp_branch"
|
||||
else ("OPR_WAITCNT", "FMT_NUM_B16")
|
||||
)
|
||||
if [field, expected_format, expected_kind, 16, True, False, False, True] not in variant["operands"]:
|
||||
errors.append(f"{label}: SIMM16 is not an encoded {expected_kind} input")
|
||||
continue
|
||||
if field == "SIMM16":
|
||||
# The 16-bit immediate: signed forms read it as FMT_NUM_I16 (sign
|
||||
# extended), unsigned compares as FMT_NUM_U16 (zero extended).
|
||||
wanted = "FMT_NUM_U16" if form["signedness"] == "unsigned" else "FMT_NUM_I16"
|
||||
if size != 16 or data_format != wanted:
|
||||
errors.append(f"{label}: SIMM16 is {size} bits {data_format} in the XML, expected 16 {wanted}")
|
||||
if (is_input, is_output) != (True, False):
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
continue
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if not is_source and form["vcc"] == "sdst_lane_mask":
|
||||
# The XML describes the Wave64 pair. The Wave32 ABI writes one SGPR.
|
||||
expected = 64
|
||||
if (kind, data_format) != ("OPR_SREG", "FMT_NUM_M64"):
|
||||
errors.append(f"{label}: {field} is not a scalar mask destination in the XML")
|
||||
if size != expected:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
|
||||
if (is_input, is_output) != (is_source, not is_source):
|
||||
# The XML marks both swap operands as outputs. Guide 12.8 also
|
||||
# reads both old values before assigning either result.
|
||||
direction = (False, True) if _rule_kind(form) == "vector_swap" else (is_source, not is_source)
|
||||
if (is_input, is_output) != direction:
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
if field == count_field:
|
||||
if data_format != "FMT_NUM_U32":
|
||||
@@ -593,7 +844,11 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
elif type(bits) is int:
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
|
||||
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
|
||||
elif is_source and data_format not in (
|
||||
{f"FMT_NUM_{'I' if form['signedness'] == 'signed' else 'U'}{form['width']}"}
|
||||
if form["operands"] in ("vopc_vcc_half", "vopc_vcc_pair")
|
||||
else SOURCE_FORMATS.get(form["signedness"], ())
|
||||
):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
@@ -663,18 +918,23 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: variant {form['variant']!r} is reserved")
|
||||
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid opcode")
|
||||
wave = WAVE_BY_KIND.get(_rule_kind(form), "any")
|
||||
reads_vcc = form["operands"] == "vop2_vcc"
|
||||
wave = "wave32" if reads_vcc else WAVE_BY_KIND.get(_rule_kind(form), "any")
|
||||
if (form["carry_in"] == "vcc") != reads_vcc:
|
||||
errors.append(f"{label}: implicit VCC input requires the vop2_vcc rule")
|
||||
if form["wave"] in WAVE and form["wave"] != wave:
|
||||
errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})")
|
||||
lane_mask = _rule_kind(form) == "vector_compare"
|
||||
if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask:
|
||||
lane_mask = _rule_kind(form) == "vector_compare" or (reads_vcc and form["operation"] != "cselect")
|
||||
vcc = "lane_mask" if lane_mask else "unchanged"
|
||||
if form["vcc"] in MASK and form["vcc"] != vcc:
|
||||
errors.append(
|
||||
f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} "
|
||||
f"(requires {'lane_mask' if lane_mask else 'unchanged'})"
|
||||
f"(requires {vcc})"
|
||||
)
|
||||
if form["exec"] != "unchanged":
|
||||
errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)")
|
||||
if type(form["width"]) is not int or form["width"] not in WIDTHS:
|
||||
expected_width = (_implemented_rule(form) or {}).get("width", 32)
|
||||
if type(form["width"]) is not int or form["width"] != expected_width:
|
||||
errors.append(f"{label}: width {form['width']} is not supported")
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
@@ -714,7 +974,7 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
|
||||
elif _rule_kind(form) != "vector":
|
||||
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
|
||||
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
if not reads_vcc and form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
@@ -730,8 +990,17 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare":
|
||||
errors.append(f"{label}: relation {relation} exists only for VOPC compares")
|
||||
elif _rule_kind(form) == "immediate_compare":
|
||||
base = SOPK_COMPARE_BASES.get(form["signedness"])
|
||||
expected = None if base is None else base + SOPK_RELATION_ORDER.index(relation) \
|
||||
if relation in SOPK_RELATION_ORDER else None
|
||||
if form["opcode"] != expected:
|
||||
errors.append(
|
||||
f"{label}: relation {relation}/{form['signedness']} has SOPK opcode "
|
||||
f"{expected} (guide 13.1.2), not {form['opcode']}"
|
||||
)
|
||||
elif _rule_kind(form) == "vector_compare":
|
||||
base = VOPC_INTEGER_BASES.get(form["signedness"])
|
||||
base = VOPC_INTEGER_BASES.get(expected_width, {}).get(form["signedness"])
|
||||
expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation]
|
||||
if form["opcode"] != expected:
|
||||
errors.append(
|
||||
@@ -745,15 +1014,30 @@ def validate(registry, snapshot):
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = (scc, None, False)
|
||||
elif _rule_kind(form) == "vector":
|
||||
elif form["operation"] in CONTROL_OPERATIONS:
|
||||
variant, operand_rule, _ = CONTROL_OPERATIONS[form["operation"]]
|
||||
signedness = "signed" if operand_rule == "sopp_branch" else "bitwise"
|
||||
if (form["variant"], form["operands"], form["signedness"]) != (variant, operand_rule, signedness):
|
||||
errors.append(f"{label}: control operation requires {variant}, {operand_rule}, {signedness}")
|
||||
if RELATION_KEY in form or form["width"] != 32:
|
||||
errors.append(f"{label}: control operation requires width 32 and no relation")
|
||||
primitive = ("unchanged", None, form["operation"] == "branch_scc_zero")
|
||||
elif _rule_kind(form) in ("vector", "vector_unary", "vector_swap"):
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
key = (form["operation"], form["signedness"])
|
||||
table = {
|
||||
"vector": VCC_VECTOR_PRIMITIVES if reads_vcc else VECTOR_PRIMITIVES,
|
||||
"vector_unary": VECTOR_UNARY_PRIMITIVES,
|
||||
"vector_swap": {("swap", "bitwise"): "Swap"},
|
||||
}[_rule_kind(form)]
|
||||
lowering = table.get(key)
|
||||
primitive = None if lowering is None else ("unchanged", lowering, False)
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
table = IMMEDIATE_PRIMITIVES if _rule_kind(form) == "immediate" else PRIMITIVES
|
||||
primitive = table.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
@@ -773,10 +1057,16 @@ def validate(registry, snapshot):
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
("vector_compare" if _rule_kind(form) == "vector_compare" else "compare")
|
||||
(_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare")
|
||||
if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY
|
||||
else "vector_swap" if form["operation"] == "swap"
|
||||
else "vector_unary" if _rule_kind(form) == "vector_unary" and form["operation"] in UNARY
|
||||
else "unary" if form["operation"] in UNARY or (
|
||||
form["operation"] == "mov" and form["family"] == "SOP1"
|
||||
)
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "control" if form["operation"] in CONTROL_OPERATIONS
|
||||
else "immediate" if _rule_kind(form) == "immediate"
|
||||
else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
@@ -810,9 +1100,10 @@ def variant_row(registry, variant, base=None):
|
||||
"""The base form re-encoded: its declaration with the variant's identity."""
|
||||
if base is None:
|
||||
base = next(form for form in registry["form"] if form.get("name") == variant["of"])
|
||||
_, vcc = OPERAND_RULES[variant["operands"]].get("vcc_transition", ("unchanged", "unchanged"))
|
||||
return dict(
|
||||
base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"],
|
||||
spec=variant["spec"], verify=variant["verify"],
|
||||
vcc=vcc, spec=variant["spec"], verify=variant["verify"],
|
||||
)
|
||||
|
||||
|
||||
@@ -882,24 +1173,32 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
|
||||
if FORM_KEYS - set(base):
|
||||
errors.append(f"{label}: not checked, its form {variant['of']} is incomplete")
|
||||
continue
|
||||
base_vcc, _ = implemented.get("vcc_transition", ("unchanged", "unchanged"))
|
||||
if base["vcc"] != base_vcc:
|
||||
errors.append(
|
||||
f"{label}: operand rule {variant['operands']} requires a base "
|
||||
f"destination contract of {base_vcc}, got {base['vcc']}"
|
||||
)
|
||||
# The same base row as the completeness check above (with duplicate
|
||||
# declarations, the dict keeps the last one).
|
||||
_check_xml(variant_row(registry, variant, base), rule, snapshot, errors)
|
||||
# Every explicit operand, destination included, has the base encoding's
|
||||
# data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3).
|
||||
# Explicit destinations and sources keep the base encoding's data format
|
||||
# in the same role. The implicit-to-explicit mask transition is checked
|
||||
# above and in _check_xml for each encoding.
|
||||
base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"])))
|
||||
own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"])))
|
||||
base_rule = rules.get(base.get("operands"))
|
||||
if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule):
|
||||
# Operands correspond by role, in rule order: the destination, then
|
||||
# each source (VSRC1 of VOP2 is SRC1 of VOP3).
|
||||
def roles(rule, record):
|
||||
def roles(rule, record, explicit_dst):
|
||||
by_field = {row[0]: row[1] for row in record["operands"] if row[0]}
|
||||
fields = ([rule["dst"]["field"]] if "dst" in rule else [])
|
||||
fields = [rule["dst"]["field"]] if explicit_dst else []
|
||||
fields += [src["field"] for src in rule.get("src", [])]
|
||||
return [(field, by_field.get(field)) for field in fields]
|
||||
|
||||
pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml)))
|
||||
explicit_dst = "dst" in base_rule and "dst" in rule
|
||||
pairs = zip(roles(base_rule, base_xml, explicit_dst), roles(rule, own_xml, explicit_dst))
|
||||
for (base_field, base_format), (field, data_format) in pairs:
|
||||
if base_format != data_format:
|
||||
errors.append(
|
||||
@@ -962,7 +1261,7 @@ def render(registry, snapshot):
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, VectorBinary, Wave,",
|
||||
" Signedness, SpecRef, VectorBinary, VectorLowering, VectorUnary, VectorVcc, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
@@ -1152,7 +1451,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
carry = {"scc": " plus SCC", "vcc": " with VCC input"}.get(form["carry_in"], "")
|
||||
what = f"compare {form[RELATION_KEY]}" if RELATION_KEY in form else form["operation"]
|
||||
effect = f"VCC = {form['vcc']}" if form["vcc"] != "unchanged" else f"SCC = {form['scc']}"
|
||||
out += [
|
||||
@@ -1209,6 +1508,159 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "control":
|
||||
out += [
|
||||
"",
|
||||
" /// Exact SIMM16 required by the fixture, or None for a displacement.",
|
||||
" pub const fn required_immediate(self) -> Option<u16> {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
exact = OPERAND_RULES[form["operands"]]["shape"].get("immediate")
|
||||
value = "None" if exact is None else f"Some({exact:#x})"
|
||||
out.append(f" Self::{form['variant']} => {value},")
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Constructs the existing decoded instruction, resolving a target only for a branch.",
|
||||
" pub fn decode<E>(",
|
||||
" self,",
|
||||
" target: impl FnOnce() -> Result<usize, E>,",
|
||||
" ) -> Result<crate::Instruction, E> {",
|
||||
" Ok(match self {",
|
||||
]
|
||||
for form in forms:
|
||||
variant = form["variant"]
|
||||
fields = " { target: target()? }" if form["operands"] == "sopp_branch" else ""
|
||||
out.append(f" Self::{variant} => crate::Instruction::{variant}{fields},")
|
||||
out += [" })", " }", "}", "", "impl crate::Instruction {",
|
||||
" /// The registry operation corresponding to a decoded SOPP control.",
|
||||
f" pub const fn sopp_control(self) -> Option<{enum}> {{",
|
||||
" match self {"]
|
||||
for form in forms:
|
||||
variant = form["variant"]
|
||||
fields = " { .. }" if form["operands"] == "sopp_branch" else ""
|
||||
out.append(f" Self::{variant}{fields} => Some({enum}::{variant}),")
|
||||
out += [" _ => None,", " }", " }", "}"]
|
||||
return out
|
||||
if kind in ("vector_unary", "vector_swap"):
|
||||
out += [
|
||||
"",
|
||||
" /// Assembler name of the 32-bit VOP1 encoding.",
|
||||
" pub const fn assembly_name(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
suffix = "_e32" if kind == "vector_unary" else ""
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}{suffix}\"," for form in forms]
|
||||
out += [" }", " }"]
|
||||
if kind == "vector_swap":
|
||||
return out + ["}"]
|
||||
if kind == "vector_unary":
|
||||
out += [
|
||||
"",
|
||||
" /// Per-lane integer operation selected by the registry.",
|
||||
" pub const fn lowering(self) -> VectorUnary {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorUnary::{VECTOR_UNARY_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
return out + [" }", " }", "}"]
|
||||
if kind == "immediate":
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation reads SCC (the conditional move's condition).",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation always reads the old SDST (`D = D op imm`).",
|
||||
" pub const fn reads_dst(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['operation'] in ('add', 'mul') else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The new SDST (`None` leaves it unchanged) and, for forms that write it, the",
|
||||
" /// new SCC (`None` leaves SCC unchanged). `dst` is the old SDST (ignored by",
|
||||
" /// forms that do not read it) and `scc_in` the SCC read by the conditional move.",
|
||||
" pub const fn evaluate(self, dst: u32, simm16: u16, scc_in: bool) -> (Option<u32>, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, _ = IMMEDIATE_PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
immediate = "primitive::sext_simm16(simm16)"
|
||||
variant = form["variant"]
|
||||
if form["operation"] == "mov":
|
||||
out.append(f" Self::{variant} => (Some({immediate}), None),")
|
||||
elif form["operation"] == "cmov":
|
||||
out.append(
|
||||
f" Self::{variant} => (if scc_in {{ Some({immediate}) }} else {{ None }}, None),"
|
||||
)
|
||||
elif form["scc"] == "unchanged":
|
||||
out.append(f" Self::{variant} => (Some(primitive::{function}(dst, {immediate})), None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{variant} => {{",
|
||||
f" let (value, scc) = primitive::{function}(dst, {immediate});",
|
||||
" (Some(value), Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "immediate_compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with SDST (S0) on the left.",
|
||||
" pub const fn relation(self) -> CompareRelation {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The SCC: whether the relation holds for SDST and SIMM16, which signed forms",
|
||||
" /// sign-extend and unsigned forms zero-extend.",
|
||||
" pub const fn test(self, dst: u32, simm16: u16) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
immediate = "primitive::sext_simm16(simm16)" if form["signedness"] == "signed" else "simm16 as u32"
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(dst, {immediate}),")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "unary":
|
||||
out += [
|
||||
"",
|
||||
@@ -1259,14 +1711,16 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }",
|
||||
"",
|
||||
" /// The per-lane operation its MSL lowering uses.",
|
||||
" pub const fn lowering(self) -> VectorBinary {",
|
||||
" pub const fn lowering(self) -> VectorLowering {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
for form in forms:
|
||||
key = (form["operation"], form["signedness"])
|
||||
if form["operands"] == "vop2_vcc":
|
||||
lowering = f"Vcc(VectorVcc::{VCC_VECTOR_PRIMITIVES[key]})"
|
||||
else:
|
||||
lowering = f"Binary(VectorBinary::{VECTOR_PRIMITIVES[key]})"
|
||||
out.append(f" Self::{form['variant']} => VectorLowering::{lowering},")
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
@@ -1316,6 +1770,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [" }", " }"]
|
||||
if kind in ("compare", "vector_compare"):
|
||||
result = "SCC" if kind == "compare" else "per-lane result"
|
||||
has_pairs = any(form["width"] == 64 for form in forms)
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with S0 on the left.",
|
||||
@@ -1332,11 +1787,32 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
"",
|
||||
f" /// The {result}: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
if has_pairs:
|
||||
out += [
|
||||
" self.test_bits(src0 as u64, src1 as u64)",
|
||||
" }",
|
||||
"",
|
||||
" /// Test raw operand bits at the width declared by this VOPC form.",
|
||||
" pub const fn test_bits(self, src0: u64, src1: u64) -> bool {",
|
||||
]
|
||||
out += [" match self {"]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
|
||||
relation = form[RELATION_KEY]
|
||||
if form["width"] in (16, 64) and relation not in VECTOR_ONLY_RELATIONS:
|
||||
symbol = {"lt": "<", "eq": "==", "le": "<=", "gt": ">", "lg": "!=", "ge": ">="}[relation]
|
||||
width = form["width"]
|
||||
if width == 64 and form["signedness"] == "unsigned":
|
||||
left, right = "src0", "src1"
|
||||
else:
|
||||
cast = f"{'i' if form['signedness'] == 'signed' else 'u'}{width}"
|
||||
left, right = f"(src0 as {cast})", f"(src1 as {cast})"
|
||||
expression = f"{left} {symbol} {right}"
|
||||
else:
|
||||
function = COMPARE_PRIMITIVES[(relation, form["signedness"])]
|
||||
args = "src0 as u32, src1 as u32" if has_pairs else "src0, src1"
|
||||
expression = f"primitive::{function}({args})"
|
||||
out.append(f" Self::{form['variant']} => {expression},")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
out += [
|
||||
|
||||
@@ -19,10 +19,13 @@ source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f
|
||||
include = [
|
||||
"rdna2/sop2.toml",
|
||||
"rdna2/sopc.toml",
|
||||
"rdna2/sopk.toml",
|
||||
"rdna2/sop1.toml",
|
||||
"rdna2/vop1.toml",
|
||||
"rdna2/vop2.toml",
|
||||
"rdna2/vopc.toml",
|
||||
"rdna2/vop3.toml",
|
||||
"rdna2/sopp.toml",
|
||||
]
|
||||
|
||||
# Named public documents that spec references point at.
|
||||
@@ -42,11 +45,12 @@ file = "amdgpu_isa_rdna2.xml"
|
||||
# variant Rust enum variant of the typed op
|
||||
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
|
||||
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
|
||||
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
|
||||
# carry_in none | scc | vcc (implicit scalar or per-lane condition or carry)
|
||||
# width operand and result width in bits
|
||||
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
|
||||
# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares)
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output)
|
||||
# VOP3A compare variant rows derive sdst_lane_mask from their operand rule.
|
||||
# wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms)
|
||||
# operands a key of [operand_rules]
|
||||
# spec references; at least one guide section with a page
|
||||
# verify evidence required before the form counts as verified
|
||||
@@ -15,6 +15,38 @@ unsupported = [
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
# Guide sections 5.3 and 12.3. VCC and EXEC halves can be explicit
|
||||
# destinations; the move has no implicit mask or SCC effects.
|
||||
[operand_rules.sop1_move]
|
||||
family = "SOP1"
|
||||
dst = { field = "SDST", class = "sgpr_or_vcc_exec" }
|
||||
src = [{ field = "SSRC0", class = "scalar_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_MOV_B32"
|
||||
family = "SOP1"
|
||||
opcode = 3
|
||||
variant = "MovB32"
|
||||
operation = "mov"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_move"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOT_B32"
|
||||
family = "SOP1"
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
# SOPK forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOPK 16-bit immediate integer forms (#215) ----
|
||||
# SDST is the destination, and the left operand of the compares; SIMM16 is
|
||||
# sign-extended except by the unsigned compares (guide 12.2). The word never
|
||||
# takes a literal dword. SDST s0-s105 only; s0-s7 hold resource descriptors,
|
||||
# so the decoder accepts them as compare operands and the translator never
|
||||
# writes them.
|
||||
|
||||
[operand_rules.sopk_sgpr]
|
||||
family = "SOPK"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SIMM16", class = "simm16" }]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[operand_rules.sopk_compare]
|
||||
family = "SOPK"
|
||||
src = [
|
||||
{ field = "SDST", class = "sgpr", min = 0, max = 105 },
|
||||
{ field = "SIMM16", class = "simm16" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 0
|
||||
variant = "MovkI32"
|
||||
operation = "mov"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 2
|
||||
variant = "CmovkI32"
|
||||
operation = "cmov"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_I32"
|
||||
family = "SOPK"
|
||||
opcode = 3
|
||||
variant = "CmpkEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_I32"
|
||||
family = "SOPK"
|
||||
opcode = 4
|
||||
variant = "CmpkLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 5
|
||||
variant = "CmpkGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 6
|
||||
variant = "CmpkGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 7
|
||||
variant = "CmpkLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 8
|
||||
variant = "CmpkLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_U32"
|
||||
family = "SOPK"
|
||||
opcode = 9
|
||||
variant = "CmpkEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_U32"
|
||||
family = "SOPK"
|
||||
opcode = 10
|
||||
variant = "CmpkLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 11
|
||||
variant = "CmpkGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 12
|
||||
variant = "CmpkGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 13
|
||||
variant = "CmpkLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 14
|
||||
variant = "CmpkLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 15
|
||||
variant = "AddkI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MULK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 16
|
||||
variant = "MulkI32"
|
||||
operation = "mul"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -0,0 +1,123 @@
|
||||
# Existing gfx1030 compute controls, AMD RDNA 2 ISA guide §12.5.
|
||||
|
||||
[operand_rules.sopp_end]
|
||||
family = "SOPP"
|
||||
src = []
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0
|
||||
|
||||
[operand_rules.sopp_branch]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "label" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
|
||||
[operand_rules.sopp_wait]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "waitcnt" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0x3f70
|
||||
|
||||
[[form]]
|
||||
name = "S_ENDPGM"
|
||||
family = "SOPP"
|
||||
opcode = 1
|
||||
variant = "EndProgram"
|
||||
operation = "end_program"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_end"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BRANCH"
|
||||
family = "SOPP"
|
||||
opcode = 2
|
||||
variant = "Branch"
|
||||
operation = "branch"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_SCC0"
|
||||
family = "SOPP"
|
||||
opcode = 4
|
||||
variant = "BranchSccZero"
|
||||
operation = "branch_scc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_VCCZ"
|
||||
family = "SOPP"
|
||||
opcode = 6
|
||||
variant = "BranchVccZero"
|
||||
operation = "branch_vcc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_EXECZ"
|
||||
family = "SOPP"
|
||||
opcode = 8
|
||||
variant = "BranchExecZero"
|
||||
operation = "branch_exec_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_WAITCNT"
|
||||
family = "SOPP"
|
||||
opcode = 12
|
||||
variant = "WaitLoad"
|
||||
operation = "wait_load"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_wait"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -0,0 +1,123 @@
|
||||
# Wave32 VOP1 integer forms, AMD RDNA 2 ISA guide 12.8.
|
||||
|
||||
[operand_rules.vop1_vgpr]
|
||||
family = "VOP1"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [{ field = "SRC0", class = "vector_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
# Both operands are read and written by swap; SRC0 must select a VGPR.
|
||||
[operand_rules.vop1_swap]
|
||||
family = "VOP1"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [{ field = "SRC0", class = "vgpr" }]
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_NOT_B32"
|
||||
family = "VOP1"
|
||||
opcode = 55
|
||||
variant = "NotB32"
|
||||
operation = "not"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_BFREV_B32"
|
||||
family = "VOP1"
|
||||
opcode = 56
|
||||
variant = "BfrevB32"
|
||||
operation = "brev"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBH_U32"
|
||||
family = "VOP1"
|
||||
opcode = 57
|
||||
variant = "FfbhU32"
|
||||
operation = "flbit"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBL_B32"
|
||||
family = "VOP1"
|
||||
opcode = 58
|
||||
variant = "FfblB32"
|
||||
operation = "ff1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBH_I32"
|
||||
family = "VOP1"
|
||||
opcode = 59
|
||||
variant = "FfbhI32"
|
||||
operation = "flbit"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 144 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SWAP_B32"
|
||||
family = "VOP1"
|
||||
opcode = 101
|
||||
variant = "SwapB32"
|
||||
operation = "swap"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_swap"
|
||||
spec = [{ document = "guide", section = "12.8", page = 149 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -348,3 +348,85 @@ wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[operand_rules.vop2_vcc]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CNDMASK_B32"
|
||||
family = "VOP2"
|
||||
opcode = 1
|
||||
variant = "CndmaskB32"
|
||||
operation = "cselect"
|
||||
signedness = "bitwise"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 131 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ADD_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 40
|
||||
variant = "AddCoCiU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUB_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 41
|
||||
variant = "SubCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUBREV_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 42
|
||||
variant = "SubrevCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
source_order = "reversed"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,6 +1,202 @@
|
||||
# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- Wave32 VOPC compares in VOP3A (#215) ----
|
||||
|
||||
# VDST encodes the scalar lane-mask destination, including vcc_lo (selector 106).
|
||||
# The two sources are VGPRs. Modifiers are clear and SRC2 is inline zero.
|
||||
[operand_rules.vop3_cmp_vgpr2]
|
||||
family = "VOP3"
|
||||
dst = { field = "VDST", class = "sgpr", min = 0, max = 106 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "SRC1", class = "vgpr" },
|
||||
]
|
||||
max_literals = 0
|
||||
variant_only = true
|
||||
unsupported = [
|
||||
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
]
|
||||
|
||||
# Opcodes come from the pinned XML's default ENC_VOP3 records.
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 129
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_I32"
|
||||
family = "VOP3"
|
||||
opcode = 130
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 131
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 132
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 133
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 134
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 193
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_U32"
|
||||
family = "VOP3"
|
||||
opcode = 194
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 195
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 196
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 197
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 198
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_I32"
|
||||
family = "VOP3"
|
||||
opcode = 128
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_I32"
|
||||
family = "VOP3"
|
||||
opcode = 135
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_U32"
|
||||
family = "VOP3"
|
||||
opcode = 192
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_U32"
|
||||
family = "VOP3"
|
||||
opcode = 199
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOP3 encoding variants of registry forms (#215) ----
|
||||
# An [[encoding_variant]] re-encodes a form declared in another family file: it
|
||||
# names the form (`of`), this family, the XML opcode here and the operand rule
|
||||
@@ -37,3 +233,130 @@ spec = [
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ABS and NEG apply to floating-point inputs (guide 6.2.1) and OMOD
|
||||
# applies to floating-point results (6.2.2). These integer forms use neither.
|
||||
# OP_SEL selects 16-bit halves (13.3.4). CLAMP saturates integer results
|
||||
# (6.5), which these registry forms do not declare. SGPR, inline and literal
|
||||
# sources remain outside this operand rule.
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 265
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 131 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 266
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 267
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 268
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_I32"
|
||||
family = "VOP3"
|
||||
opcode = 273
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_I32"
|
||||
family = "VOP3"
|
||||
opcode = 274
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_U32"
|
||||
family = "VOP3"
|
||||
opcode = 275
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_U32"
|
||||
family = "VOP3"
|
||||
opcode = 276
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_XNOR_B32"
|
||||
family = "VOP3"
|
||||
opcode = 286
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUB_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 294
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUBREV_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 295
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -358,3 +358,617 @@ spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# Wave32 64-bit integer compares (guide 3.6.3, 6.2 Table 20 and 12.9).
|
||||
[operand_rules.vopc_vcc_pair]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_pair_or_inline_integer" },
|
||||
{ field = "VSRC1", class = "vgpr_pair" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_vcc", "src_literal", "src_exec", "src_m0", "src_ttmp", "src_null",
|
||||
"src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I64"
|
||||
family = "VOPC"
|
||||
opcode = 161
|
||||
variant = "CmpLtI64"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I64"
|
||||
family = "VOPC"
|
||||
opcode = 162
|
||||
variant = "CmpEqI64"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 163
|
||||
variant = "CmpLeI64"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I64"
|
||||
family = "VOPC"
|
||||
opcode = 164
|
||||
variant = "CmpGtI64"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 165
|
||||
variant = "CmpNeI64"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 166
|
||||
variant = "CmpGeI64"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U64"
|
||||
family = "VOPC"
|
||||
opcode = 225
|
||||
variant = "CmpLtU64"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U64"
|
||||
family = "VOPC"
|
||||
opcode = 226
|
||||
variant = "CmpEqU64"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 227
|
||||
variant = "CmpLeU64"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U64"
|
||||
family = "VOPC"
|
||||
opcode = 228
|
||||
variant = "CmpGtU64"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 229
|
||||
variant = "CmpNeU64"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 230
|
||||
variant = "CmpGeU64"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_I64"
|
||||
family = "VOPC"
|
||||
opcode = 160
|
||||
variant = "CmpFI64"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_I64"
|
||||
family = "VOPC"
|
||||
opcode = 167
|
||||
variant = "CmpTI64"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_U64"
|
||||
family = "VOPC"
|
||||
opcode = 224
|
||||
variant = "CmpFU64"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_U64"
|
||||
family = "VOPC"
|
||||
opcode = 231
|
||||
variant = "CmpTU64"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
# Wave32 16-bit integer compares (guide 12.9, Tables 59 and 61).
|
||||
[operand_rules.vopc_vcc_half]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# Guide 6.2, 6.2.5 and 6.8: read the low half of each source.
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_literal", "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 137
|
||||
variant = "CmpLtI16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I16"
|
||||
family = "VOPC"
|
||||
opcode = 138
|
||||
variant = "CmpEqI16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 139
|
||||
variant = "CmpLeI16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 140
|
||||
variant = "CmpGtI16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 141
|
||||
variant = "CmpNeI16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 142
|
||||
variant = "CmpGeI16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 169
|
||||
variant = "CmpLtU16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U16"
|
||||
family = "VOPC"
|
||||
opcode = 170
|
||||
variant = "CmpEqU16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 171
|
||||
variant = "CmpLeU16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 172
|
||||
variant = "CmpGtU16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 173
|
||||
variant = "CmpNeU16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 174
|
||||
variant = "CmpGeU16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+96
-12
@@ -19,9 +19,23 @@ pub use rdna2::{
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
|
||||
impl VectorAluOp {
|
||||
/// Whether this encoding takes a per-lane VCC_LO bit.
|
||||
pub fn reads_vcc(self) -> bool {
|
||||
self.semantics().carry_in == semantics::CarryIn::Vcc
|
||||
}
|
||||
|
||||
/// Whether this encoding replaces the Wave32 VCC_LO mask.
|
||||
pub fn writes_vcc(self) -> bool {
|
||||
self.semantics().vcc == semantics::MaskEffect::LaneMask
|
||||
}
|
||||
}
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
|
||||
@@ -154,6 +168,14 @@ pub enum Instruction {
|
||||
WaitStore,
|
||||
/// VOP1 unmodified 32-bit vector move.
|
||||
MoveB32 { dst: u8, src: VectorSource },
|
||||
/// VOP1 unary integer operation with a single VGPR result.
|
||||
VectorUnary {
|
||||
op: VectorUnaryOp,
|
||||
dst: u8,
|
||||
src: VectorSource,
|
||||
},
|
||||
/// VOP1 register swap. Both operands are inputs and outputs.
|
||||
VectorSwap { op: VectorSwapOp, dst: u8, src: u8 },
|
||||
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
|
||||
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
|
||||
VectorAluVop3 {
|
||||
@@ -162,10 +184,8 @@ pub enum Instruction {
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
|
||||
/// for some operations, SCC.
|
||||
/// SOP1 32-bit unary integer operation. The move also allows an explicit
|
||||
/// VCC or EXEC half destination. Some unary operations write SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
@@ -185,13 +205,37 @@ pub enum Instruction {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
|
||||
/// SOPK 32-bit integer operation on SDST (s0-s105, never s0-s7) and the
|
||||
/// 16-bit immediate `simm16`; `s_addk_i32` also writes SCC and
|
||||
/// `s_cmovk_i32` reads it.
|
||||
ScalarImmediate {
|
||||
op: ScalarImmediateOp,
|
||||
dst: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// SOPK 32-bit integer compare of `src` (s0-s105) with the 16-bit
|
||||
/// immediate, writing only SCC.
|
||||
ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp,
|
||||
src: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// VOPC integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// For 64-bit forms register operands name pair bases and the immediate
|
||||
/// contains the low word of a sign-extended inline integer.
|
||||
VectorCompare {
|
||||
op: VectorCompareOp,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP3A 32-bit integer compare writing a Wave32 mask to s0-s105 or `vcc_lo`.
|
||||
/// Both sources are VGPR indices.
|
||||
VectorCompareVop3 {
|
||||
op: VectorCompareVop3Op,
|
||||
sdst: u8,
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP2 32-bit per-lane integer operation from the semantic registry.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
|
||||
/// `src1` is a VGPR. Inactive lanes keep `dst`.
|
||||
@@ -265,12 +309,16 @@ impl Instruction {
|
||||
Self::WaitLoad => "s_waitcnt",
|
||||
Self::WaitStore => "s_waitcnt_vscnt",
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::VectorUnary { op, .. } => op.assembly_name(),
|
||||
Self::VectorSwap { op, .. } => op.assembly_name(),
|
||||
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediate { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.assembly_name(),
|
||||
Self::VectorCompareVop3 { op, .. } => op.assembly_name(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
@@ -315,7 +363,10 @@ impl fmt::Display for Instruction {
|
||||
}
|
||||
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
|
||||
Self::WaitStore => formatter.write_str(" null, 0"),
|
||||
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
|
||||
Self::MoveB32 { dst, src } | Self::VectorUnary { dst, src, .. } => {
|
||||
write!(formatter, " v{dst}, {src}")
|
||||
}
|
||||
Self::VectorSwap { dst, src, .. } => write!(formatter, " v{dst}, v{src}"),
|
||||
Self::VectorAluVop3 {
|
||||
dst, src0, src1, ..
|
||||
}
|
||||
@@ -323,20 +374,53 @@ impl fmt::Display for Instruction {
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
|
||||
Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarImmediate { dst, simm16, .. } => {
|
||||
write!(formatter, " s{dst}, {simm16:#x}")
|
||||
}
|
||||
Self::ScalarImmediateCompare { src, simm16, .. } => {
|
||||
write!(formatter, " s{src}, {simm16:#x}")
|
||||
}
|
||||
Self::VectorCompare { op, src0, src1 } if op.semantics().width == 64 => {
|
||||
formatter.write_str(" vcc_lo, ")?;
|
||||
match src0 {
|
||||
VectorSource::Register(base) => {
|
||||
write!(formatter, "v[{base}:{}]", u16::from(base) + 1)?;
|
||||
}
|
||||
VectorSource::Scalar(base) => {
|
||||
write!(formatter, "s[{base}:{}]", u16::from(base) + 1)?;
|
||||
}
|
||||
VectorSource::Immediate(bits) => write!(formatter, "{}", bits as i32)?,
|
||||
}
|
||||
write!(formatter, ", v[{src1}:{}]", u16::from(src1) + 1)
|
||||
}
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorCompareVop3 {
|
||||
sdst, src0, src1, ..
|
||||
} => write!(formatter, " {}, v{src0}, v{src1}", ScalarDestination(sdst)),
|
||||
Self::VectorAlu {
|
||||
dst, src0, src1, ..
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
write!(formatter, " v{dst}, {src0}, v{src1}")
|
||||
write!(formatter, " v{dst}, ")?;
|
||||
if op.writes_vcc() {
|
||||
write!(formatter, "vcc_lo, ")?;
|
||||
}
|
||||
write!(formatter, "{src0}, v{src1}")?;
|
||||
if op.reads_vcc() {
|
||||
write!(formatter, ", vcc_lo")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
|
||||
@@ -218,6 +218,11 @@ pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
(((a << shift) as i32) >> shift) as u32
|
||||
}
|
||||
|
||||
/// SIMM16 sign-extended to 32 bits (SOPK, guide 12.2).
|
||||
pub const fn sext_simm16(simm16: u16) -> u32 {
|
||||
simm16 as i16 as i32 as u32
|
||||
}
|
||||
|
||||
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
@@ -326,3 +331,8 @@ pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
|
||||
let sum = ((a as u64) << shift) + b as u64;
|
||||
(sum as u32, sum >> 32 != 0)
|
||||
}
|
||||
|
||||
/// A bitwise copy of the source (RDNA 2 guide section 12.3).
|
||||
pub(crate) const fn mov_b32(src: u32) -> u32 {
|
||||
src
|
||||
}
|
||||
@@ -47,7 +47,7 @@ pub enum Operation {
|
||||
LogicalShiftRight,
|
||||
/// Shift S0 right by the masked count in S1, filling with its sign bit.
|
||||
ArithmeticShiftRight,
|
||||
/// Compare S0 with S1 under the form's relation; writes only SCC.
|
||||
/// Compare S0 with S1 under the form's relation, producing SCC or a lane mask.
|
||||
Compare,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
@@ -90,6 +90,39 @@ pub enum Operation {
|
||||
Multiply24,
|
||||
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
MultiplyHigh24,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16.
|
||||
Move,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
|
||||
ConditionalMove,
|
||||
/// Terminate the program.
|
||||
EndProgram,
|
||||
/// Unconditional PC-relative branch.
|
||||
Branch,
|
||||
/// Branch when SCC is clear.
|
||||
BranchSccZero,
|
||||
/// Branch when VCC is zero.
|
||||
BranchVccZero,
|
||||
/// Branch when EXEC is zero.
|
||||
BranchExecZero,
|
||||
/// Complete an outstanding vector load.
|
||||
WaitLoad,
|
||||
/// Swap the two old per-lane VGPR values (guide 12.8).
|
||||
Swap,
|
||||
}
|
||||
|
||||
/// Per-lane integer operation with one input and one result.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorUnary {
|
||||
/// Bitwise complement.
|
||||
Not,
|
||||
/// Reverse bit order.
|
||||
ReverseBits,
|
||||
/// Count leading zeros, or return all ones for zero.
|
||||
FindHighUnsigned,
|
||||
/// Count trailing zeros, or return all ones for zero.
|
||||
FindLow,
|
||||
/// Count leading sign bits, or return all ones if every bit matches.
|
||||
FindHighSigned,
|
||||
}
|
||||
|
||||
/// The per-lane integer operation a vector form lowers to. One reusable MSL
|
||||
@@ -144,13 +177,35 @@ pub enum Signedness {
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC.
|
||||
/// Per-lane VOP2 operation selected by the semantic registry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorLowering {
|
||||
/// Two explicit operands, with no implicit lane input.
|
||||
Binary(VectorBinary),
|
||||
/// Two explicit operands and the lane's VCC bit.
|
||||
Vcc(VectorVcc),
|
||||
}
|
||||
|
||||
/// VOP2 primitives with an implicit per-lane VCC input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorVcc {
|
||||
/// Choose S1 when the VCC bit is set, otherwise S0.
|
||||
Select,
|
||||
/// Unsigned addition with carry-in and carry-out.
|
||||
AddCarry,
|
||||
/// Unsigned subtraction with borrow-in and borrow-out.
|
||||
SubtractBorrow,
|
||||
}
|
||||
|
||||
/// Implicit condition or carry input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// SCC is not read.
|
||||
/// No implicit condition or carry input.
|
||||
None,
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
/// Per-lane Wave32 VCC_LO bit.
|
||||
Vcc,
|
||||
}
|
||||
|
||||
/// What a form writes to SCC.
|
||||
@@ -172,7 +227,7 @@ pub enum SccEffect {
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC.
|
||||
/// Where a form writes its lane mask, if any.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
@@ -181,6 +236,8 @@ pub enum MaskEffect {
|
||||
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
|
||||
/// it (docs/shaders/vector-compare.md section 3).
|
||||
LaneMask,
|
||||
/// Wave32 VOP3A compare mask written to SDST, which may be `vcc_lo`.
|
||||
SdstLaneMask,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
@@ -204,21 +261,51 @@ pub enum OperandRule {
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
/// SOP1 move: the same sources as Sop1Sgpr, with VCC and EXEC halves
|
||||
/// also allowed as explicit destinations.
|
||||
Sop1Move,
|
||||
/// SOPK integer: SDST is s0-s105 and, except for compares, written (never s0-s7,
|
||||
/// which hold resource descriptors); SIMM16 is the 16-bit immediate. The word
|
||||
/// never takes a literal. Everything else is rejected as unsupported.
|
||||
SopkSgpr,
|
||||
/// SOPK integer compare: SDST (s0-s105) is the left operand, SIMM16 the right
|
||||
/// (sign-extended for `_i32`, zero-extended for `_u32`); only SCC is written.
|
||||
SopkCompare,
|
||||
/// SOPP termination with zero in the reserved immediate field.
|
||||
SoppEnd,
|
||||
/// SOPP branch with a signed dword displacement from the next instruction.
|
||||
SoppBranch,
|
||||
/// SOPP wait with exactly vmcnt(0) and the other counters disabled.
|
||||
SoppWait,
|
||||
/// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR,
|
||||
/// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a
|
||||
/// VGPR. Everything else is rejected as unsupported.
|
||||
VopcVcc,
|
||||
/// Wave32 VOPC with a VGPR pair, even normal SGPR pair or inline integer
|
||||
/// as SRC0 and a VGPR pair as VSRC1. The destination is `vcc_lo`.
|
||||
VopcVccPair,
|
||||
/// VOPC with low-half operands and no literal selector.
|
||||
VopcVccHalf,
|
||||
/// VOP3 encoding of a VOP2 vector form: VDST is v0-v255, SRC0 and SRC1 are
|
||||
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop3Vgpr2,
|
||||
/// VOP3A compare: VDST encodes s0-s105 or `vcc_lo`; SRC0 and SRC1 are
|
||||
/// VGPRs, SRC2 is unused and all modifiers are clear.
|
||||
Vop3CmpVgpr2,
|
||||
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
|
||||
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop2Vgpr,
|
||||
/// VOP2 general SRC0 and VGPR VSRC1 with an implicit VCC_LO input.
|
||||
Vop2Vcc,
|
||||
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
|
||||
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
|
||||
Vop2Vgpr2,
|
||||
/// VOP1 unary: VGPR VDST and the same SRC0 domain as VOP2.
|
||||
Vop1Vgpr,
|
||||
/// VOP1 swap: VDST and SRC0 each read and write a VGPR.
|
||||
Vop1Swap,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
@@ -283,7 +370,7 @@ pub struct FormSemantics {
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
/// Implicit VCC write or explicit scalar destination for a compare mask.
|
||||
pub vcc: MaskEffect,
|
||||
/// EXEC write.
|
||||
pub exec: MaskEffect,
|
||||
|
||||
+3773
-130
File diff suppressed because it is too large.
Load diff
+127
-11
@@ -2,11 +2,12 @@
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect,
|
||||
Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorCompareOp,
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -78,6 +79,64 @@ fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_dispatch_selects_exactly_the_registry_sopk_forms() {
|
||||
for op in ScalarImmediateOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
for op in ScalarImmediateCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
// The two enums together are the registry's SOPK forms; the fixed
|
||||
// s_waitcnt_vscnt word (opcode 23) stays hand-written and is in neither.
|
||||
dispatch_selects_exactly(EncodingFamily::Sopk, |word| {
|
||||
ScalarImmediateOp::from_word(word)
|
||||
.map(|op| op.semantics().name)
|
||||
.or_else(|| ScalarImmediateCompareOp::from_word(word).map(|op| op.semantics().name))
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_evaluation_extends_simm16_as_the_form_declares() {
|
||||
// SIMM16 = 0x8000 is -32768 signed and 32768 unsigned.
|
||||
let d = 0xffff_8000;
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MovkI32.evaluate(0, 0x8000, false),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, true),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, false),
|
||||
(None, None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(0x7fff_ffff, 1, false),
|
||||
(Some(0x8000_0000), Some(true))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(5, 0xffff, false),
|
||||
(Some(4), Some(false))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MulkI32.evaluate(3, 0xffff, true),
|
||||
(Some(0xffff_fffd), None)
|
||||
);
|
||||
assert!(ScalarImmediateCompareOp::CmpkEqI32.test(d, 0x8000));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkEqU32.test(d, 0x8000));
|
||||
assert!(ScalarImmediateCompareOp::CmpkGtU32.test(d, 0xffff));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkGtI32.test(d, 0xffff));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
@@ -86,7 +145,6 @@ fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
|
||||
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
|
||||
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
@@ -111,7 +169,16 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
|
||||
#[test]
|
||||
fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
const OPERANDS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
|
||||
const OPERANDS16: [u64; 6] = [
|
||||
0xaaaa_0000,
|
||||
0x5555_0001,
|
||||
0xdead_7fff,
|
||||
0x8000,
|
||||
0xfffe,
|
||||
0xffff,
|
||||
];
|
||||
const OPERANDS32: [u64; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
|
||||
const OPERANDS64: [u64; 6] = [0, 1, u64::MAX >> 1, 1 << 63, u64::MAX - 1, u64::MAX];
|
||||
for op in VectorCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vopc);
|
||||
@@ -130,9 +197,22 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
);
|
||||
// The per-lane test is the declared relation over the declared
|
||||
// signedness, with SRC0 on the left.
|
||||
for src0 in OPERANDS {
|
||||
for src1 in OPERANDS {
|
||||
let ordering = if op.signed() {
|
||||
let operands = match row.width {
|
||||
16 => OPERANDS16,
|
||||
64 => OPERANDS64,
|
||||
_ => OPERANDS32,
|
||||
};
|
||||
for src0 in operands {
|
||||
for src1 in operands {
|
||||
let ordering = if row.width == 16 {
|
||||
if op.signed() {
|
||||
(src0 as i16).cmp(&(src1 as i16))
|
||||
} else {
|
||||
(src0 as u16).cmp(&(src1 as u16))
|
||||
}
|
||||
} else if op.signed() && row.width == 64 {
|
||||
(src0 as i64).cmp(&(src1 as i64))
|
||||
} else if op.signed() {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
@@ -148,7 +228,7 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
CompareRelation::True => true,
|
||||
};
|
||||
assert_eq!(
|
||||
op.test(src0, src1),
|
||||
op.test_bits(src0, src1),
|
||||
expected,
|
||||
"{} {src0:#x} {src1:#x}",
|
||||
row.name
|
||||
@@ -156,7 +236,7 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// v_cmpx and the 16-, 64-bit and float compares must not be dispatched.
|
||||
// v_cmpx and the float compares must not be dispatched.
|
||||
dispatch_selects_exactly(EncodingFamily::Vopc, |word| {
|
||||
VectorCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
@@ -182,8 +262,38 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
assert_eq!(row.swap_sources, base.swap_sources);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
|
||||
}
|
||||
for base_op in VectorCompareOp::ALL {
|
||||
let base = base_op.semantics();
|
||||
let mut variants = VectorCompareVop3Op::ALL
|
||||
.into_iter()
|
||||
.filter(|op| op.base() == base_op);
|
||||
if base.width != 32 {
|
||||
assert_eq!(variants.next(), None, "{}", base.name);
|
||||
continue;
|
||||
}
|
||||
let op = variants
|
||||
.next()
|
||||
.expect("32-bit VOPC form must have a VOP3A encoding");
|
||||
assert_eq!(variants.next(), None);
|
||||
let row = op.semantics();
|
||||
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
|
||||
assert_eq!(row.operation, base.operation);
|
||||
assert_eq!(row.signedness, base.signedness);
|
||||
assert_eq!(row.relation, base.relation);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
assert_eq!(row.exec, MaskEffect::Unchanged);
|
||||
assert_eq!(row.wave, Wave::Wave32);
|
||||
assert_eq!(row.width, 32);
|
||||
assert_eq!(row.vcc, MaskEffect::SdstLaneMask);
|
||||
assert_eq!(row.operands, OperandRule::Vop3CmpVgpr2);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", base_op.mnemonic()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
|
||||
VectorAluVop3Op::from_word(word).map(|op| op.semantics().name)
|
||||
let alu = VectorAluVop3Op::from_word(word);
|
||||
let compare = VectorCompareVop3Op::from_word(word);
|
||||
assert!(alu.is_none() || compare.is_none(), "{word:#x}");
|
||||
alu.map(|op| op.semantics().name)
|
||||
.or_else(|| compare.map(|op| op.semantics().name))
|
||||
});
|
||||
// No first word of the other 64-bit families (VOP3B shares VOP3's
|
||||
// encoding bits) selects a variant.
|
||||
@@ -197,5 +307,11 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
assert_eq!(
|
||||
VectorCompareVop3Op::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ gpu-tests = []
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
sha2 = "0.10"
|
||||
xenora-texture = { path = "../texture" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-metal = { path = "../metal" }
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Synthetic interpreter and DBT timings.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
//! and run the executable named by the benchmark's compiler-artifact message.
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
@@ -88,14 +95,25 @@ fn check(result: ExecutionResult) {
|
||||
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
|
||||
}
|
||||
|
||||
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
|
||||
// Interpolate between adjacent values at rank (n - 1) * fraction.
|
||||
let rank = (sorted.len() - 1) as f64 * fraction;
|
||||
let lower = sorted[rank.floor() as usize];
|
||||
let upper = sorted[rank.ceil() as usize];
|
||||
lower + (upper - lower).mul_f64(rank.fract())
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
samples.sort_unstable();
|
||||
let median = samples[samples.len() / 2];
|
||||
let median = percentile(samples, 0.50);
|
||||
let p95 = percentile(samples, 0.95);
|
||||
let p99 = percentile(samples, 0.99);
|
||||
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
}
|
||||
@@ -104,6 +122,8 @@ fn main() {
|
||||
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
|
||||
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
|
||||
assert!(sample_count > 0);
|
||||
let warmup_count = std::env::var("XENORA_DBT_BENCH_WARMUP")
|
||||
.map_or(10, |value| value.parse::<usize>().expect("warmup count"));
|
||||
|
||||
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
|
||||
for _ in 0..ADDS {
|
||||
@@ -124,38 +144,52 @@ fn main() {
|
||||
let mut warm = Vec::with_capacity(sample_count);
|
||||
let mut cold_metrics = None;
|
||||
|
||||
for _ in 0..sample_count {
|
||||
for record in
|
||||
std::iter::repeat_n(false, warmup_count).chain(std::iter::repeat_n(true, sample_count))
|
||||
{
|
||||
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
|
||||
let start = Instant::now();
|
||||
let result = black_box(interp.run());
|
||||
interpreter.push(start.elapsed());
|
||||
let interpreter_time = start.elapsed();
|
||||
check(result);
|
||||
|
||||
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
cold.push(start.elapsed());
|
||||
let cold_time = start.elapsed();
|
||||
check(result);
|
||||
assert!(dbt.metrics.blocks_compiled > 0);
|
||||
assert_eq!(dbt.metrics.cache_hits, 0);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
cold_metrics = Some(dbt.metrics);
|
||||
let metrics = dbt.metrics;
|
||||
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
warm.push(start.elapsed());
|
||||
let warm_time = start.elapsed();
|
||||
check(result);
|
||||
assert_eq!(
|
||||
Some(dbt.metrics.blocks_compiled),
|
||||
cold_metrics.map(|m| m.blocks_compiled)
|
||||
);
|
||||
assert_eq!(dbt.metrics.blocks_compiled, metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
|
||||
if record {
|
||||
interpreter.push(interpreter_time);
|
||||
cold.push(cold_time);
|
||||
warm.push(warm_time);
|
||||
cold_metrics = Some(metrics);
|
||||
}
|
||||
}
|
||||
|
||||
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
|
||||
println!("{warmup_count} warmup rounds excluded (XENORA_DBT_BENCH_WARMUP, default 10)");
|
||||
println!(
|
||||
"Cold DBT includes translation with a fresh engine; warm DBT reuses that engine's cache."
|
||||
);
|
||||
println!(
|
||||
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
|
||||
);
|
||||
println!("Even sample counts use the midpoint of the two middle values for the median.");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
@@ -165,3 +199,38 @@ fn main() {
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn single_sample_has_no_spread() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [Duration::from_micros(50)];
|
||||
for fraction in [0.25, 0.50, 0.75, 0.95, 0.99] {
|
||||
assert_eq!(percentile(&samples, fraction), samples[0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentiles_interpolate_across_even_samples() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [10, 20, 30, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(25));
|
||||
assert_eq!(percentile(&samples, 0.95), Duration::from_nanos(89_500));
|
||||
assert_eq!(percentile(&samples, 0.99), Duration::from_nanos(97_900));
|
||||
assert_eq!(
|
||||
percentile(&samples, 0.75) - percentile(&samples, 0.25),
|
||||
Duration::from_nanos(30_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn median_uses_the_middle_of_odd_samples() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [10, 20, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,9 @@
|
||||
differs. Never writes.
|
||||
|
||||
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
|
||||
forms sharing an opcode, operand constraints that contradict each other, and
|
||||
flags declared both written and undefined. Standard library only (Python 3.11+).
|
||||
forms sharing an opcode, operand constraints that contradict each other, LOCK
|
||||
on a form that cannot write memory, and flags declared both written and
|
||||
undefined. Standard library only (Python 3.11+).
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -26,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
|
||||
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
|
||||
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
|
||||
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned"}
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
|
||||
GROUP_KEYS = {"map", "opcodes", "digits"}
|
||||
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
|
||||
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
|
||||
@@ -39,6 +40,7 @@ SRCS = {"": 0, "b": 1, "w": 2, "d": 4, "q": 8, "x": 16}
|
||||
# encoding -> (Rust variant, has ModRM, required immediates)
|
||||
ENCS = {
|
||||
"none": ("None", False, {""}),
|
||||
"string": ("String", False, {""}),
|
||||
"rm_reg": ("RmReg", True, {""}),
|
||||
"reg_rm": ("RegRm", True, {""}),
|
||||
"reg_rm_imm": ("RegRmImm", True, {"ib", "iz"}),
|
||||
@@ -63,6 +65,8 @@ ENCS = {
|
||||
"reg_xmm": ("RegXmm", True, {""}),
|
||||
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
|
||||
}
|
||||
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
|
||||
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl"}
|
||||
# Encodings whose ModRM operand is an XMM register or memory of the source width.
|
||||
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
|
||||
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
|
||||
@@ -171,6 +175,8 @@ def load(text):
|
||||
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
|
||||
or form["enc"] == "xmm_gpr_imm"):
|
||||
fail(f"{where}: XMM size does not match the encoding")
|
||||
if form.get("lock") and (form["enc"] not in RM_DESTINATIONS or form.get("register_only")):
|
||||
fail(f"{where}: LOCK needs a memory destination")
|
||||
if form.get("unaligned") and form["src"] != "x":
|
||||
fail(f"{where}: alignment applies only to 16-byte operands")
|
||||
if form["prefix"] and form["map"] != "0f":
|
||||
@@ -266,7 +272,8 @@ def generate(operations, forms):
|
||||
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
|
||||
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
|
||||
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
|
||||
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
|
||||
out += ["];", ""]
|
||||
|
||||
groups = []
|
||||
|
||||
+148
-14
@@ -306,6 +306,26 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// RBIT Xd, Xn: reverse the bit order of the source.
|
||||
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// CLZ Xd, Xn: count the leading zero bits of the source.
|
||||
pub fn clz_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
|
||||
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x9ac2_2000
|
||||
| ((u32::from(xm) & 0x1f) << 16)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(xd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
|
||||
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
|
||||
self.emit(
|
||||
@@ -562,22 +582,35 @@ impl Arm64Assembler {
|
||||
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Load a full 64-bit constant into register Xd.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let w0 = (val & 0xffff) as u16;
|
||||
let w1 = ((val >> 16) & 0xffff) as u16;
|
||||
let w2 = ((val >> 32) & 0xffff) as u16;
|
||||
let w3 = ((val >> 48) & 0xffff) as u16;
|
||||
/// MOVN (64-bit with shift): MOVN Xd, #imm16, LSL #shift writes
|
||||
/// NOT (imm16 << shift), so every other halfword becomes 0xFFFF.
|
||||
pub fn movn_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
self.movz_64(xd, w0, 0);
|
||||
if w1 != 0 || (w2 == 0 && w3 == 0) {
|
||||
self.movk_64(xd, w1, 1);
|
||||
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
|
||||
/// MOVN plus MOVK instructions: one for each halfword that differs from
|
||||
/// the background the first instruction leaves, and always at least one.
|
||||
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
|
||||
/// when more halfwords are 0xFFFF than zero.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
|
||||
let zeros = halves.iter().filter(|&&h| h == 0).count();
|
||||
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
|
||||
let background = if ones > zeros { 0xffff } else { 0 };
|
||||
// The first halfword that differs from the background, or halfword 0
|
||||
// when none does (val is 0 or all ones).
|
||||
let first = halves.iter().position(|&h| h != background).unwrap_or(0);
|
||||
if background == 0 {
|
||||
self.movz_64(xd, halves[first], first as u8);
|
||||
} else {
|
||||
self.movn_64(xd, !halves[first], first as u8);
|
||||
}
|
||||
if w2 != 0 || w3 != 0 {
|
||||
self.movk_64(xd, w2, 2);
|
||||
}
|
||||
if w3 != 0 {
|
||||
self.movk_64(xd, w3, 3);
|
||||
for (index, &half) in halves.iter().enumerate().skip(first + 1) {
|
||||
if half != background {
|
||||
self.movk_64(xd, half, index as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -766,4 +799,105 @@ mod tests {
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
|
||||
}
|
||||
|
||||
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
|
||||
const IMMEDIATE_EDGES: [u64; 16] = [
|
||||
0,
|
||||
1,
|
||||
0xffff,
|
||||
0x1_0000,
|
||||
0x8000_0000,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x1234_0000_0000_0000,
|
||||
0x0000_0001_0000_0005,
|
||||
0x1234_5678_9abc_def0,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
0x8000_0000_0000_0000,
|
||||
0xffff_0000_ffff_ffff,
|
||||
0xffff_ffff_edcc_5678,
|
||||
0xffff_ffff_ffff_1234,
|
||||
u64::MAX,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn immediate_sequences_match_llvm_encodings() {
|
||||
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
|
||||
let cases: &[(u64, &[u32])] = &[
|
||||
(0, &[0xd2800000]), // movz x0, #0
|
||||
(u64::MAX, &[0x92800000]), // movn x0, #0
|
||||
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
|
||||
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
|
||||
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
|
||||
(0x0000_0001_0000_0005, &[0xd28000a0, 0xf2c00020]), // movz #5; movk #1, lsl #32
|
||||
// movn x0, #0xa987; movk x0, #0xedcc, lsl #16
|
||||
(0xffff_ffff_edcc_5678, &[0x929530e0, 0xf2bdb980]),
|
||||
];
|
||||
for &(value, expected) in cases {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X0, value);
|
||||
assert_eq!(asm.instructions(), expected, "{value:#x}");
|
||||
}
|
||||
// movz x9, #0xdef0; movk x9, #0x9abc, lsl #16; #0x5678, lsl #32;
|
||||
// #0x1234, lsl #48
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X9, 0x1234_5678_9abc_def0);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[0xd29bde09, 0xf2b35789, 0xf2cacf09, 0xf2e24689]
|
||||
);
|
||||
}
|
||||
|
||||
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
|
||||
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
|
||||
fn shortest_wide_move(value: u64) -> usize {
|
||||
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
|
||||
let not_zero = halves.clone().filter(|&h| h != 0).count();
|
||||
let not_ones = halves.filter(|&h| h != 0xffff).count();
|
||||
not_zero.min(not_ones).max(1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediates_run_on_the_host_and_use_the_fewest_wide_moves() {
|
||||
let mut values = IMMEDIATE_EDGES.to_vec();
|
||||
let mut state = 0x9e37_79b9_7f4a_7c15u64;
|
||||
for _ in 0..512 {
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
let raw = state.wrapping_mul(0x2545_f491_4f6c_dd1d);
|
||||
// Force some halfwords to zero or all ones so both MOVZ and MOVN
|
||||
// sequences of every length occur.
|
||||
let mut value = raw;
|
||||
for half in 0..4 {
|
||||
match (raw >> (60 - 2 * half)) & 3 {
|
||||
0 => value &= !(0xffff << (16 * half)),
|
||||
1 => value |= 0xffff << (16 * half),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
values.push(value);
|
||||
}
|
||||
let mut jit = crate::jit::JitMemory::new(64 * 1024).unwrap();
|
||||
for value in values {
|
||||
for register in [X0, X9] {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(register, value);
|
||||
assert_eq!(
|
||||
asm.instructions().len(),
|
||||
shortest_wide_move(value),
|
||||
"{value:#x}"
|
||||
);
|
||||
if register != X0 {
|
||||
asm.mov_reg_64(X0, register);
|
||||
}
|
||||
asm.ret();
|
||||
let entry = jit.emit_block(asm.instructions()).unwrap();
|
||||
// SAFETY: the block is a complete AAPCS64 leaf function that
|
||||
// writes only X0 (and X9, a caller-saved register) and returns.
|
||||
let function: extern "C" fn() -> u64 = unsafe { std::mem::transmute(entry) };
|
||||
assert_eq!(function(), value, "{value:#x} in x{register}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,8 @@ pub struct CpuState {
|
||||
/// XMM0-XMM15, lane 0 in the low bits.
|
||||
pub xmm: [u128; 16],
|
||||
pub mxcsr: Mxcsr,
|
||||
/// Direction flag: string instructions step RSI and RDI down when set.
|
||||
pub df: bool,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
@@ -111,6 +113,7 @@ impl CpuState {
|
||||
fs_base: 0,
|
||||
xmm: [0; 16],
|
||||
mxcsr: Mxcsr::default(),
|
||||
df: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +126,35 @@ impl CpuState {
|
||||
}
|
||||
}
|
||||
|
||||
/// CPUID leaf 1, EDX: CMOVcc.
|
||||
pub const CPUID_CMOV: u32 = 1 << 15;
|
||||
/// CPUID leaf 1, ECX: POPCNT.
|
||||
pub const CPUID_POPCNT: u32 = 1 << 23;
|
||||
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
|
||||
pub const CPUID_LZCNT: u32 = 1 << 5;
|
||||
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
|
||||
pub const CPUID_LONG_MODE: u32 = 1 << 29;
|
||||
|
||||
/// What the guest's CPUID returns in EAX, EBX, ECX and EDX.
|
||||
///
|
||||
/// The table is fixed and never reads the host. It names a synthetic
|
||||
/// processor, not an Intel or AMD product, and sets a feature bit only when
|
||||
/// every instruction of that feature is implemented. A leaf that is not
|
||||
/// listed returns zeros.
|
||||
pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
|
||||
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
|
||||
match leaf {
|
||||
// Highest basic leaf, then "Xenora guest" in EBX, EDX, ECX.
|
||||
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
|
||||
// No family, model or stepping: this is no shipped processor.
|
||||
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
|
||||
// Highest extended leaf.
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
|
||||
_ => [0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// Termination reason for guest execution.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ExitReason {
|
||||
|
||||
@@ -330,10 +330,18 @@ pub fn is_translatable(insn: &Insn) -> bool {
|
||||
/// [`DbtMetrics::interpreter_fallbacks`].
|
||||
pub fn is_native(insn: &Insn) -> bool {
|
||||
let wide = matches!(insn.size, 4 | 8);
|
||||
// The bit scans work on any register or memory source, and the bit test
|
||||
// needs the index in a register.
|
||||
let scanned = matches!(insn.size, 2 | 4 | 8);
|
||||
match insn.op {
|
||||
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
|
||||
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
|
||||
Op::Cmov => wide,
|
||||
Op::Bsf | Op::Bsr => scanned,
|
||||
// Only the `0F A3` form has the bit index in a register. The `0F BA`
|
||||
// group form takes an immediate index and may write memory, so it
|
||||
// stays on the shared semantics.
|
||||
Op::Bt => scanned && insn.encoding == Encoding::RmReg,
|
||||
Op::Pop => insn.encoding == Encoding::OpReg,
|
||||
Op::Mov
|
||||
| Op::Movzx
|
||||
@@ -500,6 +508,18 @@ impl Emitter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero-extend the low `size` bytes of `xd` to the full 64-bit register.
|
||||
///
|
||||
/// An operation narrower than the register reads only the low bytes of its
|
||||
/// source, so the bits above them must not take part in a bit scan.
|
||||
fn zero_extend(&mut self, xd: u8, size: u8) {
|
||||
match size {
|
||||
8 => {}
|
||||
4 => self.asm.mov_reg_32(xd, xd),
|
||||
_ => self.asm.uxth_32(xd, xd),
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective address into X1, clobbering X9.
|
||||
fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) {
|
||||
let asm = &mut *self.asm;
|
||||
@@ -1032,6 +1052,71 @@ impl Emitter<'_> {
|
||||
self.load_condition(insn.condition);
|
||||
self.store_rm(insn, X12, completed);
|
||||
}
|
||||
Op::Bsf | Op::Bsr => {
|
||||
// BSF and BSR write the index of the lowest or the highest set
|
||||
// bit of the source into the destination and set the zero flag
|
||||
// when the source is zero (Intel SDM Volume 2B, "BSF" and
|
||||
// "BSR"). A zero source leaves the destination undefined, so
|
||||
// the destination keeps its value, which is the same rule the
|
||||
// interpreter and the reference apply.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
match insn.op {
|
||||
// The lowest set bit is the highest set bit of the
|
||||
// reversed value, so its index is the leading zero count
|
||||
// of the reversed value.
|
||||
Op::Bsf => {
|
||||
self.asm.rbit_64(X10, X9);
|
||||
self.asm.clz_64(X10, X10);
|
||||
}
|
||||
// The highest set bit sits at 63 minus the leading zero
|
||||
// count.
|
||||
_ => {
|
||||
self.asm.clz_64(X10, X9);
|
||||
self.asm.movz_64(X13, 63, 0);
|
||||
self.asm.sub_reg_64(X10, X13, X10);
|
||||
}
|
||||
}
|
||||
self.load_reg(X11, insn.reg);
|
||||
self.asm.tst_reg_64(X9, X9);
|
||||
// CSEL takes the first operand when the condition holds, so
|
||||
// the index is the value that replaces the destination.
|
||||
self.asm.csel_64(X11, X10, X11, Condition::Ne);
|
||||
match insn.size {
|
||||
// A 16-bit destination keeps the bits above it, so the
|
||||
// register is merged rather than replaced.
|
||||
2 => self.store_reg(insn.reg, insn.size, X11),
|
||||
// A 32-bit or 64-bit destination is written in full. The
|
||||
// index has no bits above the operand width, so this
|
||||
// matches the interpreter's 32-bit write, and a zero
|
||||
// source keeps the whole register unchanged.
|
||||
_ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)),
|
||||
}
|
||||
if flags {
|
||||
// The zero flag is set when the source is zero. The other
|
||||
// flags are undefined and keep their value.
|
||||
self.asm.cset_32(X12, Condition::Eq);
|
||||
self.asm.strb_uoff(X12, X19, ZF);
|
||||
}
|
||||
}
|
||||
Op::Bt => {
|
||||
// BT sets the carry flag from the tested bit and leaves the
|
||||
// other flags undefined (Intel SDM Volume 2B, "BT"). The bit
|
||||
// index comes from the register operand and is masked to the
|
||||
// operand width.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
self.load_reg(X10, insn.reg);
|
||||
self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1));
|
||||
self.asm.and_reg_64(X10, X10, X13);
|
||||
self.asm.load_imm_64(X11, 1);
|
||||
self.asm.lslv_64(X11, X11, X10);
|
||||
self.asm.tst_reg_64(X9, X11);
|
||||
if flags {
|
||||
self.asm.cset_32(X12, Condition::Ne);
|
||||
self.asm.strb_uoff(X12, X19, CF);
|
||||
}
|
||||
}
|
||||
Op::Cmov => {
|
||||
self.load_rm(X10, insn, completed);
|
||||
self.load_reg(X9, insn.reg);
|
||||
@@ -2182,4 +2267,207 @@ mod tests {
|
||||
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
|
||||
);
|
||||
}
|
||||
|
||||
/// Intel SDM Volume 1, section 3.4.3.1: for `SUB` and `CMP`, `CF` is the
|
||||
/// borrow out of the most significant bit. `JB` is `CF = 1`, `JAE` is
|
||||
/// `CF = 0`, `JBE` is `CF = 1 or ZF = 1` and `JA` is `CF = 0 and ZF = 0`.
|
||||
///
|
||||
/// ARM64 reports the inverse: `SUBS` sets `C` when the subtraction does
|
||||
/// *not* borrow, and its `HI`/`LS` conditions are defined on that same
|
||||
/// inverted carry. These four x86 conditions therefore cannot be taken
|
||||
/// from an ARM64 condition code without translating the borrow first,
|
||||
/// which makes them the ones to pin at the boundaries.
|
||||
/// One unsigned condition: the low nibble pair as encoded in the `0x70`
|
||||
/// block, and the rule that decides it from CF and ZF.
|
||||
type UnsignedCondition = (u8, fn(bool, bool) -> bool);
|
||||
|
||||
const UNSIGNED_CONDITIONS: [UnsignedCondition; 4] = [
|
||||
(0x72, |cf, _zf| cf), // JB, JC, JNAE
|
||||
(0x73, |cf, _zf| !cf), // JAE, JNB, JNC
|
||||
(0x76, |cf, zf| cf || zf), // JBE, JNA
|
||||
(0x77, |cf, zf| !cf && !zf), // JA, JNBE
|
||||
];
|
||||
|
||||
/// Build `<op> eax, ebx` (or `rax, rbx`) followed by the short or near form
|
||||
/// of `condition`. The not-taken path writes 1 to `ECX` and halts, the
|
||||
/// taken path writes 2. A near branch targets offset 140, which a `disp8`
|
||||
/// cannot reach, so the two encodings are exercised separately.
|
||||
fn unsigned_branch_program(op: [u8; 2], condition: u8, wide: bool, near: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
if wide {
|
||||
code.push(0x48); // REX.W
|
||||
}
|
||||
code.extend_from_slice(&op); // cmp/sub eax, ebx
|
||||
let jcc = code.len();
|
||||
if near {
|
||||
// The near form is `0F 8x`, where x is the low nibble of the
|
||||
// short form's opcode.
|
||||
code.extend_from_slice(&[0x0F, 0x80 | (condition & 0x0F), 0, 0, 0, 0]);
|
||||
} else {
|
||||
code.extend_from_slice(&[condition, 0]);
|
||||
}
|
||||
code.extend_from_slice(&[0xB9, 1, 0, 0, 0]); // mov ecx, 1
|
||||
code.push(0xF4); // hlt
|
||||
let target = if near { 140 } else { code.len() };
|
||||
while code.len() < target {
|
||||
code.push(0x90); // nop
|
||||
}
|
||||
code.extend_from_slice(&[0xB9, 2, 0, 0, 0]); // mov ecx, 2
|
||||
code.push(0xF4); // hlt
|
||||
let next = jcc + if near { 6 } else { 2 };
|
||||
let displacement = target as i64 - next as i64;
|
||||
if near {
|
||||
code[jcc + 2..jcc + 6].copy_from_slice(&(displacement as i32).to_le_bytes());
|
||||
} else {
|
||||
code[jcc + 1] = displacement as i8 as u8;
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
/// Run one branch program and return `(ecx, cf, zf)`.
|
||||
fn run_unsigned_branch(code: &[u8], left: u64, right: u64) -> (u64, bool, bool) {
|
||||
let (mut engine, mut cpu, mut memory) = fixture(code);
|
||||
cpu.set(Register::Rax, left);
|
||||
cpu.set(Register::Rbx, right);
|
||||
let result = engine.run(&mut cpu, &mut memory, 32);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
// Either the two-instruction taken path or the two-instruction
|
||||
// not-taken path runs after the compare and the branch.
|
||||
assert_eq!(result.instructions_executed, 4);
|
||||
// The compare, the branch and the halting move all run as translated
|
||||
// ARM64, not through the shared interpreter.
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
(cpu.get(Register::Rcx), cpu.flags.cf, cpu.flags.zf)
|
||||
}
|
||||
|
||||
/// The four unsigned conditions, at both ends of the 32-bit and 64-bit
|
||||
/// ranges, in the short and the near encoding. Expected flags and
|
||||
/// outcomes come from the SDM rules above, not from the lowering.
|
||||
#[test]
|
||||
fn unsigned_branch_conditions_follow_the_borrow_at_every_boundary() {
|
||||
const CMP: [u8; 2] = [0x39, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
// 32-bit: zero, one, equal operands, both ends of the range, and
|
||||
// the pair where the sign bit flips but the unsigned order holds.
|
||||
(false, 0, 0),
|
||||
(false, 0, 1),
|
||||
(false, 1, 0),
|
||||
(false, 0xFFFF_FFFF, 0xFFFF_FFFF),
|
||||
(false, 0xFFFF_FFFF, 0),
|
||||
(false, 0, 0xFFFF_FFFF),
|
||||
(false, 0x7FFF_FFFF, 0x8000_0000),
|
||||
(false, 0x8000_0000, 0x7FFF_FFFF),
|
||||
// The same boundaries at 64 bits, plus a subtraction that clears
|
||||
// the sign bit without borrowing.
|
||||
(true, 0, 0),
|
||||
(true, 0, 1),
|
||||
(true, 1, 0),
|
||||
(true, u64::MAX, u64::MAX),
|
||||
(true, u64::MAX, 0),
|
||||
(true, 0, u64::MAX),
|
||||
(true, 0x7FFF_FFFF_FFFF_FFFF, 0x8000_0000_0000_0000),
|
||||
(true, 0x8000_0000_0000_0000, 0x7FFF_FFFF_FFFF_FFFF),
|
||||
(true, 0x8000_0000_0000_0000, 1),
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
|
||||
let (left, right) = (left & mask, right & mask);
|
||||
// SDM: CF is the borrow out of the most significant bit, ZF is a
|
||||
// zero result. Both follow from the operands alone.
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
for &near in &[false, true] {
|
||||
let code = unsigned_branch_program(CMP, condition, wide, near);
|
||||
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
|
||||
let case = format!(
|
||||
"{condition:#04x} {:#x} {:#x} {}",
|
||||
left,
|
||||
right,
|
||||
if near { "near" } else { "short" }
|
||||
);
|
||||
assert_eq!(got_cf, cf, "{case}: CF");
|
||||
assert_eq!(got_zf, zf, "{case}: ZF");
|
||||
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `SUB` is the other producer of the carry these conditions read, and the
|
||||
/// one where the ARM64 carry is inverted: `0 - 1` borrows, while
|
||||
/// `0x8000_0000_0000_0000 - 1` does not borrow even though it clears the
|
||||
/// sign bit.
|
||||
#[test]
|
||||
fn subtract_borrow_into_and_out_of_the_high_bit_feeds_the_unsigned_branches() {
|
||||
const SUB: [u8; 2] = [0x29, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
(false, 0, 1),
|
||||
(false, 0x8000_0000, 1),
|
||||
(true, 0, 1),
|
||||
(true, 0x8000_0000_0000_0000, 1),
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
|
||||
let (left, right) = (left & mask, right & mask);
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
for &near in &[false, true] {
|
||||
let code = unsigned_branch_program(SUB, condition, wide, near);
|
||||
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
|
||||
let case = format!(
|
||||
"{condition:#04x} {:#x} {:#x} {}",
|
||||
left,
|
||||
right,
|
||||
if near { "near" } else { "short" }
|
||||
);
|
||||
assert_eq!(got_cf, cf, "{case}: CF");
|
||||
assert_eq!(got_zf, zf, "{case}: ZF");
|
||||
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The carry these conditions read is produced in one translated block and
|
||||
/// consumed in the next. A lowering that left it in the host's condition
|
||||
/// flags would pass the single-block cases above and fail here.
|
||||
#[test]
|
||||
fn unsigned_branch_reads_flags_stored_by_a_previous_block() {
|
||||
const CMP: [u8; 2] = [0x39, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
(false, 0, 0), // CF = 0, ZF = 1
|
||||
(false, 0, 1), // CF = 1, ZF = 0
|
||||
(false, 0xFFFF_FFFF, 0), // CF = 0, ZF = 0
|
||||
(true, 0x8000_0000_0000_0000, 1), // CF = 0 although the sign bit clears
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
let code = unsigned_branch_program(CMP, condition, wide, false);
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
cpu.set(Register::Rax, left);
|
||||
cpu.set(Register::Rbx, right);
|
||||
|
||||
// One instruction per run: the compare is translated as a
|
||||
// one-instruction block, so the branch is compiled separately
|
||||
// and can only read the flags the first block stored.
|
||||
let first = engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(first.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(cpu.rip, ENTRY + if wide { 3 } else { 2 });
|
||||
assert_eq!((cpu.flags.cf, cpu.flags.zf), (cf, zf));
|
||||
|
||||
let second = engine.run(&mut cpu, &mut memory, 8);
|
||||
assert_eq!(second.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(second.instructions_executed, 3);
|
||||
assert_eq!(cpu.get(Register::Rcx), if taken { 2 } else { 1 });
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1030
-2
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,10 @@
|
||||
//! Bounded parser for the PE32+ import directory (Microsoft PE format,
|
||||
//! "The .idata Section"). Binding and static inspection both use it, so they
|
||||
//! agree on which imports an image has and how they are named.
|
||||
//!
|
||||
//! Static inspection also reads the delay-load directory ("Delay-Load Import
|
||||
//! Tables (Image Only)"). Binding does not: the PE format leaves those imports
|
||||
//! to a delay-load helper that runs inside the image on first use.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
@@ -14,6 +18,9 @@ pub const MAX_IMPORTS: usize = 65_536;
|
||||
pub const MAX_NAME_LEN: usize = 4096;
|
||||
|
||||
const DESCRIPTOR_LEN: u32 = 20;
|
||||
const DELAY_DESCRIPTOR_LEN: u32 = 32;
|
||||
/// Delay-load attribute bit 0: the descriptor's address fields are RVAs.
|
||||
const DELAY_RVA_BASED: u32 = 1;
|
||||
const ORDINAL_FLAG: u64 = 1 << 63;
|
||||
|
||||
/// How an import names its target. A symbol that happens to be spelled like an
|
||||
@@ -42,6 +49,24 @@ pub struct ImportEntry {
|
||||
pub iat_rva: u32,
|
||||
}
|
||||
|
||||
/// A delay-load descriptor field that must hold an RVA.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DelayField {
|
||||
DllName,
|
||||
AddressTable,
|
||||
NameTable,
|
||||
}
|
||||
|
||||
impl fmt::Display for DelayField {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::DllName => "DLL name",
|
||||
Self::AddressTable => "import address table",
|
||||
Self::NameTable => "import name table",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ImportTableError {
|
||||
/// A structure at this RVA is not fully backed by section data.
|
||||
@@ -56,6 +81,25 @@ pub enum ImportTableError {
|
||||
ReservedBits {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA sets reserved attribute bits.
|
||||
DelayReservedBits {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA has `RvaBased` clear, the earlier
|
||||
/// form whose address fields are virtual addresses. It is not read.
|
||||
DelayVirtualAddresses {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA leaves a required field zero.
|
||||
DelayFieldMissing {
|
||||
rva: u32,
|
||||
field: DelayField,
|
||||
},
|
||||
/// The declared delay-load directory ends at this RVA before its empty
|
||||
/// descriptor.
|
||||
DelayDirectoryEnd {
|
||||
rva: u32,
|
||||
},
|
||||
TooManyDescriptors,
|
||||
TooManyImports,
|
||||
}
|
||||
@@ -63,7 +107,10 @@ pub enum ImportTableError {
|
||||
impl fmt::Display for ImportTableError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"),
|
||||
Self::OutOfBounds { rva } => write!(
|
||||
f,
|
||||
"import data at RVA 0x{rva:08x} is truncated or outside the section data"
|
||||
),
|
||||
Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"),
|
||||
Self::ReservedBits { rva } => {
|
||||
write!(
|
||||
@@ -71,6 +118,21 @@ impl fmt::Display for ImportTableError {
|
||||
"reserved bits set in the import lookup at RVA 0x{rva:08x}"
|
||||
)
|
||||
}
|
||||
Self::DelayReservedBits { rva } => write!(
|
||||
f,
|
||||
"reserved attribute bits set in the delay-load descriptor at RVA 0x{rva:08x}"
|
||||
),
|
||||
Self::DelayVirtualAddresses { rva } => write!(
|
||||
f,
|
||||
"delay-load descriptor at RVA 0x{rva:08x} holds virtual addresses, not RVAs, and is not read"
|
||||
),
|
||||
Self::DelayFieldMissing { rva, field } => {
|
||||
write!(f, "delay-load descriptor at RVA 0x{rva:08x} has no {field}")
|
||||
}
|
||||
Self::DelayDirectoryEnd { rva } => write!(
|
||||
f,
|
||||
"delay-load directory ends at RVA 0x{rva:08x} before its empty descriptor"
|
||||
),
|
||||
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
|
||||
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
|
||||
}
|
||||
@@ -159,7 +221,7 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
return Ok(());
|
||||
}
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, lookup_rva, address_rva, entries)?;
|
||||
collect_symbols(reader, &module, lookup_rva, address_rva, false, entries)?;
|
||||
descriptor = descriptor
|
||||
.checked_add(DESCRIPTOR_LEN)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
|
||||
@@ -167,11 +229,88 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
/// Parse the delay-load directory of `directory_size` bytes at `directory_rva`.
|
||||
///
|
||||
/// Only descriptors that lie wholly inside the declared directory are read,
|
||||
/// and the directory must hold the empty descriptor that ends the table.
|
||||
/// Each entry's `iat_rva` is its slot in the delay import address table.
|
||||
/// Returns every import before the first problem, and the problem.
|
||||
pub fn parse_delay_imports(
|
||||
bytes: &[u8],
|
||||
directory_rva: u32,
|
||||
directory_size: u32,
|
||||
rva_to_offset: impl Fn(u32) -> Option<usize>,
|
||||
) -> (Vec<ImportEntry>, Option<ImportTableError>) {
|
||||
let reader = Reader {
|
||||
bytes,
|
||||
rva_to_offset,
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
let error = collect_delayed(&reader, directory_rva, directory_size, &mut entries).err();
|
||||
(entries, error)
|
||||
}
|
||||
|
||||
fn collect_delayed<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
directory_rva: u32,
|
||||
directory_size: u32,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
let end = directory_rva
|
||||
.checked_add(directory_size)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: directory_rva })?;
|
||||
let mut descriptor = directory_rva;
|
||||
for _ in 0..MAX_DESCRIPTORS {
|
||||
if end - descriptor < DELAY_DESCRIPTOR_LEN {
|
||||
return Err(ImportTableError::DelayDirectoryEnd { rva: end });
|
||||
}
|
||||
let fields = reader.array::<{ DELAY_DESCRIPTOR_LEN as usize }>(descriptor)?;
|
||||
// The table ends with an empty descriptor.
|
||||
if fields == [0; DELAY_DESCRIPTOR_LEN as usize] {
|
||||
return Ok(());
|
||||
}
|
||||
let attributes = reader.u32(descriptor)?;
|
||||
if attributes & !DELAY_RVA_BASED != 0 {
|
||||
return Err(ImportTableError::DelayReservedBits { rva: descriptor });
|
||||
}
|
||||
if attributes & DELAY_RVA_BASED == 0 {
|
||||
return Err(ImportTableError::DelayVirtualAddresses { rva: descriptor });
|
||||
}
|
||||
let name_rva = reader.u32(descriptor + 4)?;
|
||||
let address_rva = reader.u32(descriptor + 12)?;
|
||||
let names_rva = reader.u32(descriptor + 16)?;
|
||||
// All three are required. The address table holds thunk addresses, so
|
||||
// it cannot stand in for a missing name table.
|
||||
for (field, rva) in [
|
||||
(DelayField::DllName, name_rva),
|
||||
(DelayField::AddressTable, address_rva),
|
||||
(DelayField::NameTable, names_rva),
|
||||
] {
|
||||
if rva == 0 {
|
||||
return Err(ImportTableError::DelayFieldMissing {
|
||||
rva: descriptor,
|
||||
field,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Each must also start in section data, whether or not an import uses it.
|
||||
reader.array::<1>(name_rva)?;
|
||||
reader.array::<8>(address_rva)?;
|
||||
reader.array::<8>(names_rva)?;
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, names_rva, address_rva, true, entries)?;
|
||||
// The declared end bounds this sum.
|
||||
descriptor += DELAY_DESCRIPTOR_LEN;
|
||||
}
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
module: &str,
|
||||
lookup_rva: u32,
|
||||
address_rva: u32,
|
||||
slots_on_disk: bool,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
// Without a lookup table the address table holds the same entries on disk.
|
||||
@@ -194,6 +333,10 @@ fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
return Err(ImportTableError::TooManyImports);
|
||||
}
|
||||
let iat_rva = at(address_rva)?;
|
||||
if slots_on_disk {
|
||||
// A delay-load slot starts out holding its thunk's address.
|
||||
reader.array::<8>(iat_rva)?;
|
||||
}
|
||||
let name = if value & ORDINAL_FLAG != 0 {
|
||||
let ordinal = value & !ORDINAL_FLAG;
|
||||
ImportName::Ordinal(
|
||||
|
||||
+113
-28
@@ -11,7 +11,9 @@
|
||||
//! startup blockers.
|
||||
|
||||
use crate::dbt::{is_native, is_translatable};
|
||||
use crate::import_table::{ImportName, ImportTableError, parse_imports};
|
||||
use crate::import_table::{
|
||||
ImportEntry, ImportName, ImportTableError, parse_delay_imports, parse_imports,
|
||||
};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection};
|
||||
@@ -678,6 +680,11 @@ pub struct ProbeReport {
|
||||
pub imports: Vec<ImportedSymbol>,
|
||||
/// Why the import table could not be read to its end.
|
||||
pub import_error: Option<ImportTableError>,
|
||||
/// Delay-loaded imports before the first malformed entry, if any. Binding
|
||||
/// does not resolve them, so `imports` and its totals leave them out.
|
||||
pub delayed_imports: Vec<ImportedSymbol>,
|
||||
/// Why the delay-load import tables could not be read to their end.
|
||||
pub delay_import_error: Option<ImportTableError>,
|
||||
pub instruction_records: Vec<InstructionRecord>,
|
||||
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
|
||||
}
|
||||
@@ -822,6 +829,30 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// The delay import descriptor is data directory 13. It exists only when
|
||||
// NumberOfRvaAndSizes covers it.
|
||||
let (delay_dir_rva, delay_dir_size) = if size_of_optional_header >= 224
|
||||
&& u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) > 13
|
||||
{
|
||||
(
|
||||
u32::from_le_bytes(
|
||||
bytes[opt_offset + 216..opt_offset + 220]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
),
|
||||
u32::from_le_bytes(
|
||||
bytes[opt_offset + 220..opt_offset + 224]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(0, 0)
|
||||
};
|
||||
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
let section_header_size = 40;
|
||||
@@ -960,35 +991,40 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
let backed_offset = |rva: u32| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
};
|
||||
let (entries, import_error) = if import_dir_rva == 0 {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
parse_imports(bytes, import_dir_rva, |rva| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
})
|
||||
parse_imports(bytes, import_dir_rva, backed_offset)
|
||||
};
|
||||
let imports: Vec<ImportedSymbol> = entries
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
let binding = registry.resolve(&entry.module, &entry.name);
|
||||
ImportedSymbol {
|
||||
category: ProbeReport::categorize_dll(&entry.module),
|
||||
dll: entry.module,
|
||||
symbol: entry.name.to_string(),
|
||||
import_name: entry.name,
|
||||
iat_rva: entry.iat_rva,
|
||||
is_supported: binding.is_some(),
|
||||
service_status: binding.map(|service| service.status),
|
||||
canonical_module: binding.map(|service| service.module.clone()),
|
||||
canonical_symbol: binding.map(|service| service.symbol.clone()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let (delayed_entries, delay_import_error) = if delay_dir_rva == 0 {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
parse_delay_imports(bytes, delay_dir_rva, delay_dir_size, backed_offset)
|
||||
};
|
||||
let describe = |entry: ImportEntry| {
|
||||
let binding = registry.resolve(&entry.module, &entry.name);
|
||||
ImportedSymbol {
|
||||
category: ProbeReport::categorize_dll(&entry.module),
|
||||
dll: entry.module,
|
||||
symbol: entry.name.to_string(),
|
||||
import_name: entry.name,
|
||||
iat_rva: entry.iat_rva,
|
||||
is_supported: binding.is_some(),
|
||||
service_status: binding.map(|service| service.status),
|
||||
canonical_module: binding.map(|service| service.module.clone()),
|
||||
canonical_symbol: binding.map(|service| service.symbol.clone()),
|
||||
}
|
||||
};
|
||||
let imports: Vec<ImportedSymbol> = entries.into_iter().map(&describe).collect();
|
||||
let delayed_imports: Vec<ImportedSymbol> = delayed_entries.into_iter().map(&describe).collect();
|
||||
|
||||
// 4. Control-Flow-Aware Static Disassembly
|
||||
//
|
||||
@@ -1124,6 +1160,8 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
tls,
|
||||
imports,
|
||||
import_error,
|
||||
delayed_imports,
|
||||
delay_import_error,
|
||||
instruction_records,
|
||||
first_unsupported_dbt_insn,
|
||||
})
|
||||
@@ -1142,7 +1180,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
|
||||
// 1. imports.csv
|
||||
let mut imports_csv = String::from(
|
||||
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
|
||||
"module,symbol_or_ordinal,iat_rva,import_table,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
|
||||
);
|
||||
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva,import_kind\n");
|
||||
let mut modules = BTreeSet::new();
|
||||
@@ -1186,7 +1224,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let canonical = canonical.replace('"', "\"\"");
|
||||
let _ = writeln!(
|
||||
imports_csv,
|
||||
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
|
||||
"{key},ordinary,{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
|
||||
imp.category, imp.is_supported
|
||||
);
|
||||
if !imp.is_supported {
|
||||
@@ -1194,6 +1232,34 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
missing += 1;
|
||||
}
|
||||
}
|
||||
// Delay-loaded imports follow the ordinary rows. Binding does not resolve
|
||||
// them, so they stay out of every ordinary total, the startup clusters and
|
||||
// `missing_imports.csv`.
|
||||
let mut delayed_modules = BTreeSet::new();
|
||||
for imp in &report.delayed_imports {
|
||||
delayed_modules.insert(imp.dll.to_ascii_lowercase());
|
||||
let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_));
|
||||
let import_kind = if is_ordinal { "ordinal" } else { "name" };
|
||||
let module = imp.dll.replace('"', "\"\"");
|
||||
let symbol = imp.symbol.replace('"', "\"\"");
|
||||
let canonical = imp.canonical_module.as_deref().unwrap_or("");
|
||||
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
|
||||
let canonical = canonical.replace('"', "\"\"");
|
||||
let (priority, cluster) = imp.startup_priority();
|
||||
let _ = writeln!(
|
||||
imports_csv,
|
||||
"\"{module}\",\"{symbol}\",0x{:08x},delayed,{},{},{},{is_alias},\"{canonical}\",{priority},{cluster},false,{import_kind}",
|
||||
imp.iat_rva,
|
||||
imp.category,
|
||||
imp.is_supported,
|
||||
imp.coverage_label()
|
||||
);
|
||||
}
|
||||
let delayed_slots = report.delayed_imports.len();
|
||||
let delayed_dlls = delayed_modules.len();
|
||||
let delay_error = report
|
||||
.delay_import_error
|
||||
.map_or_else(|| "none".to_string(), |error| error.to_string());
|
||||
fs::write(out.join("imports.csv"), imports_csv)?;
|
||||
fs::write(out.join("missing_imports.csv"), missing_csv)?;
|
||||
|
||||
@@ -1250,6 +1316,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"stub_slots": {stubs},
|
||||
"recognized_unsupported_slots": {unsupported},
|
||||
"missing_handler_slots": {unknown},
|
||||
"delayed_imports": {delayed_slots},
|
||||
"delayed_imported_dlls_count": {delayed_dlls},
|
||||
"delay_import_error": "{delay_error}",
|
||||
"total_relocations": {},
|
||||
"dir64_relocations": {},
|
||||
"tls_callbacks_count": {},
|
||||
@@ -1381,6 +1450,16 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n"
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"- **Delay-Loaded Import Slots**: `{delayed_slots}` across `{delayed_dlls}` DLLs. They are marked `delayed` in `imports.csv` and are not part of the counts above or of `missing_imports.csv`: binding does not resolve them, and the PE format leaves them to the image's delay-load helper.\n"
|
||||
);
|
||||
if let Some(error) = &report.delay_import_error {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"- **Delay-load import table is malformed**: {error}. Only the delay-loaded imports before it are listed.\n"
|
||||
);
|
||||
}
|
||||
if trusted_runner_slots > 0 {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
@@ -1425,6 +1504,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
distinct_imports.len(),
|
||||
unique_symbols.len()
|
||||
);
|
||||
if delayed_slots > 0 {
|
||||
let _ = writeln!(
|
||||
matrix,
|
||||
"\nThe delay-load import tables contain {delayed_slots} more slots across {delayed_dlls} DLLs. They are not counted in this document."
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
matrix,
|
||||
"\nRegistered slots include {implemented} implemented, {partial} partial, and {stubs} stubs. They reference {} canonical registered services through {aliases} alias slots. The {missing} unresolved slots include {unsupported} explicitly tracked unsupported APIs and {unknown} other missing handlers.",
|
||||
|
||||
+234
-1
@@ -163,7 +163,6 @@ pub fn apply_relocations(
|
||||
let reloc_type = (entry_val >> 12) as u8;
|
||||
let offset_in_page = (entry_val & 0x0FFF) as u32;
|
||||
|
||||
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
|
||||
report.total_entries += 1;
|
||||
|
||||
match reloc_type {
|
||||
@@ -221,6 +220,17 @@ pub fn apply_relocations(
|
||||
read_bytes += block_size as usize;
|
||||
}
|
||||
|
||||
// Only these two types can reach a successful return. Build the public
|
||||
// histogram once instead of searching its tree for every relocation.
|
||||
for (kind, count) in [
|
||||
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
|
||||
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
|
||||
] {
|
||||
if count != 0 {
|
||||
report.type_counts.insert(kind, count);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -274,3 +284,226 @@ fn find_reloc_directory(
|
||||
Ok(Some((reloc_rva, reloc_size)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::PeSection;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
const PREFERRED: u64 = 0x140000000;
|
||||
const LOADED: u64 = PREFERRED + 0x200000;
|
||||
const DATA_RVA: u32 = 0x1000;
|
||||
const DIRECTORY_RVA: u32 = 0x10000000;
|
||||
const DIRECTORY_OFFSET: usize = 0x200;
|
||||
|
||||
// Original synthetic directory, laid out from Microsoft's PE Format,
|
||||
// .reloc section: eight-byte block headers and two-byte type/offset words.
|
||||
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
|
||||
// Header fields and metadata are supplied directly: PE parsing is not timed.
|
||||
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
|
||||
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
|
||||
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
|
||||
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
|
||||
for (page, entries) in blocks {
|
||||
bytes.extend_from_slice(&page.to_le_bytes());
|
||||
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
|
||||
for entry in entries {
|
||||
bytes.extend_from_slice(&entry.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
|
||||
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
|
||||
let pe = ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: PREFERRED,
|
||||
section_alignment: 4096,
|
||||
file_alignment: 512,
|
||||
size_of_image: DIRECTORY_RVA + size.max(4096),
|
||||
size_of_headers: 512,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".reloc".into(),
|
||||
virtual_address: DIRECTORY_RVA,
|
||||
virtual_size: size,
|
||||
raw_data_ptr: DIRECTORY_OFFSET as u32,
|
||||
raw_data_size: size,
|
||||
characteristics: 0x40000040,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
};
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
LOADED + u64::from(DATA_RVA),
|
||||
data.len(),
|
||||
MemoryPermissions::READ_ONLY,
|
||||
data,
|
||||
)
|
||||
.unwrap();
|
||||
(pe, bytes, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_padding_and_rebases_read_only_targets() {
|
||||
for (preferred, initial, expected) in [
|
||||
(PREFERRED, 0x140001234, 0x140201234),
|
||||
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
|
||||
(LOADED - 8, u64::MAX - 3, 4),
|
||||
(LOADED + 8, 3, u64::MAX - 4),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) =
|
||||
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
|
||||
pe.image_base = preferred;
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
|
||||
assert_eq!(report.total_entries, 2);
|
||||
assert_eq!(report.applied_dir64, 1);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_omits_types_that_did_not_occur() {
|
||||
for (entries, counts) in [
|
||||
(vec![], BTreeMap::new()),
|
||||
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
|
||||
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
|
||||
] {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(report.type_counts, counts);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_duplicate_and_overlapping_entry_order() {
|
||||
let (pe, bytes, mut memory) = fixture(
|
||||
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
|
||||
&[0; 16],
|
||||
);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
// Two additions of 0x200000 at offset zero, then one at offset four.
|
||||
let mut actual = [0; 16];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_fields_observe_prior_carries_in_directory_order() {
|
||||
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
|
||||
for (entries, expected) in [
|
||||
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
|
||||
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
|
||||
pe.image_base = LOADED - 1;
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
let mut actual = [0; 12];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_prior_writes_and_rejects_unsupported_types() {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory),
|
||||
Err(RelocationError::UnsupportedRelocationType(15))
|
||||
);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_delta_keeps_the_empty_report_without_parsing() {
|
||||
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
|
||||
pe.image_base = LOADED;
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
|
||||
RelocationReport::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
|
||||
fn relocation_profile() {
|
||||
for pages in [1u32, 128] {
|
||||
for padding_every in [0usize, 2, 1] {
|
||||
let blocks: Vec<_> = (0..pages)
|
||||
.map(|page| {
|
||||
let entries = (0..512)
|
||||
.map(|slot| {
|
||||
let padding = padding_every != 0 && slot % padding_every == 0;
|
||||
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
|
||||
})
|
||||
.collect();
|
||||
(DATA_RVA + page * 4096, entries)
|
||||
})
|
||||
.collect();
|
||||
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
|
||||
let mut samples = Vec::new();
|
||||
for run in 0..36 {
|
||||
let mut memory = initial.clone();
|
||||
let start = Instant::now();
|
||||
let report = black_box(
|
||||
apply_relocations(
|
||||
black_box(&pe),
|
||||
black_box(&bytes),
|
||||
LOADED,
|
||||
black_box(&mut memory),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let elapsed = start.elapsed().as_secs_f64() * 1e6;
|
||||
assert_eq!(report.total_entries, pages as usize * 512);
|
||||
let padding = match padding_every {
|
||||
0 => 0,
|
||||
2 => report.total_entries / 2,
|
||||
_ => report.total_entries,
|
||||
};
|
||||
assert_eq!(report.skipped_absolute, padding);
|
||||
assert_eq!(report.applied_dir64, report.total_entries - padding);
|
||||
// Check every output against the fixture's independently specified pattern.
|
||||
for slot in 0..pages as usize * 512 {
|
||||
let expected = if padding_every != 0 && slot % padding_every == 0 {
|
||||
0
|
||||
} else {
|
||||
0x200000
|
||||
};
|
||||
assert_eq!(
|
||||
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
if run >= 5 {
|
||||
samples.push(elapsed);
|
||||
}
|
||||
}
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
|
||||
let variance =
|
||||
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
|
||||
println!(
|
||||
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
|
||||
samples.len(),
|
||||
samples[samples.len() / 2],
|
||||
samples[0],
|
||||
samples[samples.len() - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -251,6 +251,21 @@ impl ServicesState {
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Forget the last-error value of a guest thread that has ended, so a
|
||||
/// later thread given the same TEB address starts at zero. Returns
|
||||
/// whether a nonzero value was dropped.
|
||||
///
|
||||
/// Each service call names its own TEB and the values sit behind one
|
||||
/// lock, so calls for different threads may run concurrently. Retire a
|
||||
/// TEB only once no service call for that thread is still running.
|
||||
pub fn retire_thread_last_error(&self, teb: u64) -> bool {
|
||||
self.last_errors
|
||||
.lock()
|
||||
.expect("guest last-error state")
|
||||
.remove(&teb)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn set_last_error(&self, teb: u64, error: u32) {
|
||||
let mut errors = self.last_errors.lock().expect("guest last-error state");
|
||||
if error == 0 {
|
||||
|
||||
@@ -35,6 +35,7 @@ pub struct Control {
|
||||
pub rounding: Rounding,
|
||||
pub denormals_are_zero: bool,
|
||||
pub flush_to_zero: bool,
|
||||
pub overflow_masked: bool,
|
||||
pub underflow_masked: bool,
|
||||
}
|
||||
|
||||
@@ -49,6 +50,7 @@ impl Control {
|
||||
},
|
||||
denormals_are_zero: mxcsr & 1 << 6 != 0,
|
||||
flush_to_zero: mxcsr & 1 << 15 != 0,
|
||||
overflow_masked: mxcsr & 1 << 10 != 0,
|
||||
underflow_masked: mxcsr & 1 << 11 != 0,
|
||||
}
|
||||
}
|
||||
@@ -263,6 +265,14 @@ fn round(
|
||||
flags |= PRECISION;
|
||||
}
|
||||
if leading > format.bias() {
|
||||
if !control.overflow_masked {
|
||||
// No result is delivered. Precision is reported only if rounding
|
||||
// with an unbounded exponent was inexact.
|
||||
return Outcome {
|
||||
bits: 0,
|
||||
flags: OVERFLOW | if inexact { PRECISION } else { 0 },
|
||||
};
|
||||
}
|
||||
let to_infinity = match control.rounding {
|
||||
Rounding::Nearest => true,
|
||||
Rounding::Down => sign,
|
||||
|
||||
@@ -50,6 +50,8 @@ pub struct Form {
|
||||
pub no_rex_b: bool,
|
||||
/// A 16-byte memory operand may have any alignment.
|
||||
pub unaligned: bool,
|
||||
/// The LOCK prefix is accepted when the ModRM operand is memory.
|
||||
pub lockable: bool,
|
||||
}
|
||||
|
||||
/// Opcode table entry.
|
||||
@@ -64,6 +66,8 @@ pub enum Entry {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Encoding {
|
||||
None,
|
||||
/// A string instruction: source `[RSI]`, destination `[RDI]`, REP allowed.
|
||||
String,
|
||||
RmReg,
|
||||
RegRm,
|
||||
RegRmImm,
|
||||
@@ -167,6 +171,11 @@ pub struct Insn {
|
||||
pub imm: u64,
|
||||
/// Condition code for Jcc, CMOVcc and SETcc.
|
||||
pub condition: u8,
|
||||
/// Carries a LOCK prefix. Set only for a lockable form with a memory
|
||||
/// destination.
|
||||
pub lock: bool,
|
||||
/// A string instruction carrying a REP prefix.
|
||||
pub rep: bool,
|
||||
}
|
||||
|
||||
impl Insn {
|
||||
@@ -228,11 +237,21 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `byte` is a legacy prefix: an operand-size, address-size, segment,
|
||||
/// LOCK or repeat prefix (Intel SDM Vol. 2A, 2.1.1).
|
||||
fn is_legacy_prefix(byte: u8) -> bool {
|
||||
matches!(
|
||||
byte,
|
||||
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3
|
||||
)
|
||||
}
|
||||
|
||||
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
|
||||
/// is called only for bytes that belong to the instruction, in order.
|
||||
///
|
||||
/// Forms the registry does not declare, LOCK, address-size overrides and an
|
||||
/// ignored segment override after FS or GS are rejected rather than approximated.
|
||||
/// Forms the registry does not declare, LOCK anywhere but on a lockable form
|
||||
/// with a memory destination, address-size overrides and an ignored segment
|
||||
/// override after FS or GS are rejected rather than approximated.
|
||||
pub fn decode<E>(
|
||||
rip: u64,
|
||||
fetch: impl FnMut(u64) -> Result<u8, E>,
|
||||
@@ -246,10 +265,24 @@ pub fn decode<E>(
|
||||
let mut operand_size = false;
|
||||
let mut rep = false;
|
||||
let mut repne = false;
|
||||
let mut lock = false;
|
||||
let mut segment = None;
|
||||
let mut rex = 0;
|
||||
let mut byte = cursor.u8()?;
|
||||
loop {
|
||||
let selected = match byte {
|
||||
// REX applies only immediately before the opcode. One that is
|
||||
// followed by a legacy prefix is ignored (Intel SDM Vol. 2A, 2.2.1).
|
||||
0x40..=0x4F => {
|
||||
let next = cursor.u8()?;
|
||||
if !is_legacy_prefix(next) {
|
||||
rex = byte;
|
||||
byte = next;
|
||||
break;
|
||||
}
|
||||
byte = next;
|
||||
continue;
|
||||
}
|
||||
0x64 => Segment::Fs,
|
||||
0x65 => Segment::Gs,
|
||||
0x66 => {
|
||||
@@ -267,6 +300,11 @@ pub fn decode<E>(
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
0xF0 => {
|
||||
lock = true;
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
// CS, DS, ES and SS overrides have no effect in 64-bit mode. After
|
||||
// FS or GS their meaning is not relied on, so it is rejected.
|
||||
0x26 | 0x2E | 0x36 | 0x3E if segment.is_none() => {
|
||||
@@ -283,10 +321,6 @@ pub fn decode<E>(
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
|
||||
let rex = if byte & 0xF0 == 0x40 { byte } else { 0 };
|
||||
if rex != 0 {
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
let (rex_w, rex_r, rex_x, rex_b) =
|
||||
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
|
||||
|
||||
@@ -298,8 +332,12 @@ pub fn decode<E>(
|
||||
let opcode = if two_byte { cursor.u8()? } else { byte };
|
||||
let slot = usize::from(opcode);
|
||||
let table = if !two_byte {
|
||||
// Only PAUSE (F3 90) has a meaning here for F3 on a one-byte opcode.
|
||||
if repne || (rep && opcode != 0x90) {
|
||||
// On a one-byte opcode F3 is PAUSE (F3 90) or REP on a string form.
|
||||
let string = matches!(
|
||||
ONE_BYTE[slot],
|
||||
Entry::Form(index) if FORMS[usize::from(index)].encoding == Encoding::String
|
||||
);
|
||||
if repne || (rep && opcode != 0x90 && !string) {
|
||||
return Err(DecodeError::Unsupported(if rep { 0xF3 } else { 0xF2 }));
|
||||
}
|
||||
&ONE_BYTE
|
||||
@@ -325,9 +363,24 @@ pub fn decode<E>(
|
||||
GROUPS[usize::from(index)][usize::from((modrm >> 3) & 7)]
|
||||
}
|
||||
};
|
||||
let form = FORMS
|
||||
let mut form = FORMS
|
||||
.get(usize::from(form_index))
|
||||
.ok_or(DecodeError::Unsupported(opcode))?;
|
||||
let mut form_index = form_index;
|
||||
if form.no_rex_b && rex_b != 0 {
|
||||
// 90 is NOP only without REX.B. With it the byte exchanges r8 with the
|
||||
// accumulator, as the first register of the 91..97 row would (Intel
|
||||
// SDM Vol. 2B, "NOP" and "XCHG").
|
||||
match ONE_BYTE[slot + 1] {
|
||||
Entry::Form(index)
|
||||
if !two_byte && !rep && FORMS[usize::from(index)].encoding == Encoding::OpReg =>
|
||||
{
|
||||
form_index = index;
|
||||
form = &FORMS[usize::from(index)];
|
||||
}
|
||||
_ => return Err(DecodeError::Unsupported(opcode)),
|
||||
}
|
||||
}
|
||||
if form.has_modrm && matches!(entry, Entry::Form(_)) {
|
||||
modrm = cursor.u8()?;
|
||||
}
|
||||
@@ -348,10 +401,6 @@ pub fn decode<E>(
|
||||
if operand_size && !takes_operand_size && !overridden {
|
||||
return Err(DecodeError::Unsupported(0x66));
|
||||
}
|
||||
if form.no_rex_b && rex_b != 0 {
|
||||
return Err(DecodeError::Unsupported(opcode));
|
||||
}
|
||||
|
||||
let rm_size = if form.source != 0 { form.source } else { size };
|
||||
let register = |field: u8, extension: u8, width: u8| {
|
||||
if width == 1 && rex == 0 && field >= 4 {
|
||||
@@ -412,6 +461,20 @@ pub fn decode<E>(
|
||||
}
|
||||
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
|
||||
reg = register(opcode & 7, rex_b, size);
|
||||
} else if form.encoding == Encoding::String {
|
||||
// The source is DS:[RSI], which FS or GS may override. The destination
|
||||
// ES:[RDI] takes no override.
|
||||
rm = Some(RmOperand::Mem(MemOperand {
|
||||
base: Some(6),
|
||||
index: None,
|
||||
disp: 0,
|
||||
segment,
|
||||
}));
|
||||
}
|
||||
// LOCK is an invalid opcode unless the instruction is lockable and its
|
||||
// destination is memory (Intel SDM Vol. 2, "LOCK").
|
||||
if lock && !(form.lockable && matches!(rm, Some(RmOperand::Mem(_)))) {
|
||||
return Err(DecodeError::Unsupported(0xF0));
|
||||
}
|
||||
|
||||
let mut imm = match form.immediate {
|
||||
@@ -449,6 +512,8 @@ pub fn decode<E>(
|
||||
reg,
|
||||
imm,
|
||||
condition: opcode & 0xF,
|
||||
lock,
|
||||
rep: rep && form.encoding == Encoding::String,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! the state unchanged. Flags that the architecture leaves undefined keep their
|
||||
//! previous value, which is permitted but not something guests may rely on.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register};
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
|
||||
use crate::x86_simd;
|
||||
@@ -19,8 +19,11 @@ use crate::x86_table::Op;
|
||||
const RAX: usize = Register::Rax as usize;
|
||||
const RCX: usize = Register::Rcx as usize;
|
||||
const RDX: usize = Register::Rdx as usize;
|
||||
const RBX: usize = Register::Rbx as usize;
|
||||
const RSP: usize = Register::Rsp as usize;
|
||||
const RBP: usize = Register::Rbp as usize;
|
||||
const RSI: usize = Register::Rsi as usize;
|
||||
const RDI: usize = Register::Rdi as usize;
|
||||
|
||||
/// Value mask of an operand of `size` bytes.
|
||||
fn mask(size: u8) -> u64 {
|
||||
@@ -238,6 +241,25 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
flags.cf = signed >> (count - 1) & 1 != 0;
|
||||
(signed >> count) as u64
|
||||
}
|
||||
Op::Rcl | Op::Rcr => {
|
||||
// The carry flag is one more bit above the operand, so the rotation
|
||||
// is over `bits + 1` positions and the count is reduced modulo that.
|
||||
let width = bits + 1;
|
||||
let ring = wide | u128::from(old.cf) << bits;
|
||||
let by = count % width;
|
||||
let left = if op == Op::Rcl {
|
||||
by
|
||||
} else {
|
||||
(width - by) % width
|
||||
};
|
||||
let rotated = if left == 0 {
|
||||
ring
|
||||
} else {
|
||||
ring << left | ring >> (width - left)
|
||||
};
|
||||
flags.cf = rotated >> bits & 1 != 0;
|
||||
rotated as u64
|
||||
}
|
||||
_ => {
|
||||
let by = count % bits;
|
||||
let left = if op == Op::Rol {
|
||||
@@ -265,7 +287,7 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
// OF is defined only for a count of one.
|
||||
if count == 1 {
|
||||
flags.of = match op {
|
||||
Op::Shl | Op::Rol => (result & top != 0) != flags.cf,
|
||||
Op::Shl | Op::Rol | Op::Rcl => (result & top != 0) != flags.cf,
|
||||
Op::Shr => value & top != 0,
|
||||
Op::Sar => false,
|
||||
_ => (result & top != 0) != (result & (top >> 1) != 0),
|
||||
@@ -351,6 +373,8 @@ pub fn execute(
|
||||
Encoding::OpRegImm => write_reg(cpu, insn.reg, size, insn.imm),
|
||||
_ => write_rm(cpu, memory, insn, insn.imm & mask(size))?,
|
||||
},
|
||||
// A non-temporal store is an ordinary store: there is no cache to bypass.
|
||||
Op::Movnti => write_rm(cpu, memory, insn, read_reg(cpu, insn.reg, size))?,
|
||||
Op::Movzx => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
@@ -364,11 +388,48 @@ pub fn execute(
|
||||
write_reg(cpu, insn.reg, size, offset(cpu, &operand));
|
||||
}
|
||||
}
|
||||
Op::Xchg if insn.encoding == Encoding::OpReg => {
|
||||
// The accumulator with the register in the opcode, never itself:
|
||||
// 90 without REX.B is NOP.
|
||||
let rax = accumulator(RAX);
|
||||
let (a, b) = (read_reg(cpu, rax, size), read_reg(cpu, insn.reg, size));
|
||||
write_reg(cpu, rax, size, b);
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
Op::Xchg => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
write_rm(cpu, memory, insn, b)?;
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
Op::Xadd => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
let (value, flags) = add(a, b, false, size);
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
// The source is loaded before the destination is stored, so a
|
||||
// register added to itself keeps the sum.
|
||||
if insn.rm != Some(RmOperand::Reg(insn.reg)) {
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Cmpxchg => {
|
||||
let (destination, source) = operands(cpu, memory, insn)?;
|
||||
let expected = cpu.gpr[RAX] & mask(size);
|
||||
let (_, flags) = sub(expected, destination, false, size);
|
||||
// The destination is written whether or not the values match, so a
|
||||
// mismatch on memory that cannot be written still faults.
|
||||
let matched = expected == destination;
|
||||
write_rm(
|
||||
cpu,
|
||||
memory,
|
||||
insn,
|
||||
if matched { source } else { destination },
|
||||
)?;
|
||||
if !matched {
|
||||
write_reg(cpu, accumulator(RAX), size, destination);
|
||||
}
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Bswap => {
|
||||
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
@@ -387,7 +448,7 @@ pub fn execute(
|
||||
if negative { mask(size) } else { 0 },
|
||||
);
|
||||
}
|
||||
Op::Rol | Op::Ror | Op::Shl | Op::Shr | Op::Sar => {
|
||||
Op::Rol | Op::Ror | Op::Rcl | Op::Rcr | Op::Shl | Op::Shr | Op::Sar => {
|
||||
let (a, count) = operands(cpu, memory, insn)?;
|
||||
match shift(insn.op, a, count, size, cpu.flags) {
|
||||
Some((value, flags)) => {
|
||||
@@ -544,6 +605,49 @@ pub fn execute(
|
||||
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
|
||||
}
|
||||
Op::Nop => {}
|
||||
// Every load and store of an instruction completes before the next
|
||||
// instruction starts, on one host thread, so guest accesses are already
|
||||
// totally ordered and a fence has nothing further to enforce.
|
||||
Op::Lfence | Op::Mfence | Op::Sfence => {}
|
||||
Op::Cpuid => {
|
||||
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
|
||||
// register write, so the upper halves are cleared.
|
||||
let values = cpuid(cpu.gpr[RAX] as u32, cpu.gpr[RCX] as u32);
|
||||
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(values) {
|
||||
cpu.gpr[register] = u64::from(value);
|
||||
}
|
||||
}
|
||||
Op::Movs | Op::Stos => {
|
||||
// One element per execution. A REP form with elements left keeps
|
||||
// RIP on itself, so every element is a step of its own: it counts
|
||||
// against the step budget, and a fault keeps the elements already
|
||||
// done, with RSI, RDI and RCX at the element that faulted.
|
||||
if !(insn.rep && cpu.gpr[RCX] == 0) {
|
||||
let value = if insn.op == Op::Movs {
|
||||
read_rm(cpu, memory, insn)?
|
||||
} else {
|
||||
cpu.gpr[RAX] & mask(size)
|
||||
};
|
||||
write_mem(memory, cpu.gpr[RDI], size, value)?;
|
||||
let step = if cpu.df {
|
||||
u64::from(size).wrapping_neg()
|
||||
} else {
|
||||
u64::from(size)
|
||||
};
|
||||
if insn.op == Op::Movs {
|
||||
cpu.gpr[RSI] = cpu.gpr[RSI].wrapping_add(step);
|
||||
}
|
||||
cpu.gpr[RDI] = cpu.gpr[RDI].wrapping_add(step);
|
||||
if insn.rep {
|
||||
cpu.gpr[RCX] -= 1;
|
||||
if cpu.gpr[RCX] != 0 {
|
||||
next = insn.rip;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Cld => cpu.df = false,
|
||||
Op::Std => cpu.df = true,
|
||||
Op::Clc => cpu.flags.cf = false,
|
||||
Op::Stc => cpu.flags.cf = true,
|
||||
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
|
||||
|
||||
+635
-484
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,282 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The guest CPUID contract (issue #130).
|
||||
//!
|
||||
//! CPUID reports a fixed synthetic processor. A feature bit is set only when
|
||||
//! every instruction of that feature is implemented, so each bit that is set
|
||||
//! is checked against instructions that run, and each bit software commonly
|
||||
//! tests that is clear has a witness instruction of that feature which both
|
||||
//! engines refuse. The witness must be removed before its bit can be set.
|
||||
//!
|
||||
//! Bit positions and the feature each instruction belongs to are from the
|
||||
//! Intel SDM Vol. 2, CPUID and the instruction entries. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
|
||||
use xenora_loader::cpu::{
|
||||
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
|
||||
RFlags, cpuid,
|
||||
};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RDX: usize = 2;
|
||||
const RBX: usize = 3;
|
||||
const RSI: usize = 6;
|
||||
|
||||
/// Index of a CPUID result, which come in the order EAX, EBX, ECX, EDX.
|
||||
const EBX: usize = 1;
|
||||
const ECX: usize = 2;
|
||||
const EDX: usize = 3;
|
||||
|
||||
fn image(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
/// Final state and exit reason from the interpreter, then from the DBT.
|
||||
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, CpuState, ExitReason); 2] {
|
||||
let mut memory = image(code);
|
||||
let interpreted = Interpreter::new(cpu.clone(), &mut memory, budget).run();
|
||||
let mut memory = image(code);
|
||||
let mut state = cpu.clone();
|
||||
let translated = DbtEngine::new(64 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut state, &mut memory, budget);
|
||||
[
|
||||
(
|
||||
"interpreter",
|
||||
interpreted.final_state,
|
||||
interpreted.exit_reason,
|
||||
),
|
||||
("DBT", translated.final_state, translated.exit_reason),
|
||||
]
|
||||
}
|
||||
|
||||
const SET: RFlags = RFlags {
|
||||
cf: true,
|
||||
zf: true,
|
||||
sf: true,
|
||||
of: true,
|
||||
pf: true,
|
||||
af: true,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_leaf_returns_its_documented_values() {
|
||||
// (leaf, subleaf, [EAX, EBX, ECX, EDX])
|
||||
let leaves: &[(u32, u32, [u32; 4])] = &[
|
||||
// Highest basic leaf 1, and "Xeno", "uest", "ra g" as little-endian text.
|
||||
(0, 0, [1, 0x6F6E_6558, 0x7473_6575, 0x6720_6172]),
|
||||
// POPCNT is ECX bit 23 and CMOV is EDX bit 15. No signature.
|
||||
(1, 0, [0, 0, 0x0080_0000, 0x0000_8000]),
|
||||
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
|
||||
// Highest extended leaf.
|
||||
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
|
||||
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
|
||||
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
// Everything else, above or between the highest leaves, is zeros.
|
||||
(2, 0, [0; 4]),
|
||||
(4, 0, [0; 4]),
|
||||
(6, 0, [0; 4]),
|
||||
(7, 0, [0; 4]),
|
||||
(7, 1, [0; 4]),
|
||||
(0xB, 0, [0; 4]),
|
||||
(0xD, 1, [0; 4]),
|
||||
(0x16, 0, [0; 4]),
|
||||
(0x4000_0000, 0, [0; 4]),
|
||||
(0x7FFF_FFFF, 0, [0; 4]),
|
||||
(0x8000_0002, 0, [0; 4]),
|
||||
(0x8000_0008, 0, [0; 4]),
|
||||
(0xFFFF_FFFF, 0, [0; 4]),
|
||||
];
|
||||
for &(leaf, subleaf, wanted) in leaves {
|
||||
// Only EAX and ECX select the leaf: the upper halves are noise.
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
for (index, register) in cpu.gpr.iter_mut().enumerate() {
|
||||
*register = 0xA5A5_0000_1111_0000 + index as u64;
|
||||
}
|
||||
cpu.gpr[RAX] = 0xDEAD_BEEF_0000_0000 | u64::from(leaf);
|
||||
cpu.gpr[RCX] = 0xFEED_FACE_0000_0000 | u64::from(subleaf);
|
||||
cpu.flags = SET;
|
||||
// Each result is a 32-bit register write, so it clears the upper half.
|
||||
// CPUID changes no flag and no other register.
|
||||
let mut expected = cpu.clone();
|
||||
expected.rip = ENTRY + 2;
|
||||
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(wanted) {
|
||||
expected.gpr[register] = u64::from(value);
|
||||
}
|
||||
for (engine, state, exit) in both(&cpu, &[0x0F, 0xA2], 1) {
|
||||
let what = format!("leaf {leaf:#x} subleaf {subleaf:#x} on the {engine}");
|
||||
assert_eq!(exit, ExitReason::StepLimitExceeded, "{what}");
|
||||
assert_eq!(state, expected, "{what}");
|
||||
}
|
||||
// The function a runtime service would read agrees with the instruction.
|
||||
assert_eq!(cpuid(leaf, subleaf), wanted, "leaf {leaf:#x}");
|
||||
}
|
||||
|
||||
let [_, ebx, ecx, edx] = cpuid(0, 0);
|
||||
let vendor: Vec<u8> = [ebx, edx, ecx]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
assert_eq!(vendor, b"Xenora guest");
|
||||
assert_eq!(
|
||||
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
|
||||
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_features_have_all_their_instructions_in_the_fixtures() {
|
||||
// `tests/x86_integer.rs` runs every line of this file through both engines
|
||||
// against an independent reference. Here each reported feature must have
|
||||
// its whole instruction set among those lines.
|
||||
let fixture = include_str!("x86/integer.txt");
|
||||
let decodable = |text: &str| {
|
||||
let line = fixture
|
||||
.lines()
|
||||
.find(|line| line.split_once(" | ").is_some_and(|(_, asm)| asm == text))
|
||||
.unwrap_or_else(|| panic!("no fixture for {text}"));
|
||||
let code: Vec<u8> = line
|
||||
.split_once(" | ")
|
||||
.unwrap()
|
||||
.0
|
||||
.split(' ')
|
||||
.map(|byte| u8::from_str_radix(byte, 16).unwrap())
|
||||
.collect();
|
||||
decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
|
||||
};
|
||||
let memory = |bits: u32| {
|
||||
let width = match bits {
|
||||
16 => "word",
|
||||
32 => "dword",
|
||||
_ => "qword",
|
||||
};
|
||||
format!("{width} ptr [rsi + 4*rdi + 16]")
|
||||
};
|
||||
// 16-, 32- and 64-bit destinations (RBX and R10) from a register and from memory.
|
||||
let sizes = [
|
||||
(16, "bx", "r9w", "r10w"),
|
||||
(32, "ebx", "r9d", "r10d"),
|
||||
(64, "rbx", "r9", "r10"),
|
||||
];
|
||||
|
||||
assert_ne!(cpuid(1, 0)[EDX] & CPUID_CMOV, 0);
|
||||
for condition in "o no b ae e ne be a s ns p np l ge le g".split(' ') {
|
||||
for (bits, low, source, high) in sizes {
|
||||
decodable(&format!("cmov{condition} {low}, {source}"));
|
||||
decodable(&format!("cmov{condition} {high}, {}", memory(bits)));
|
||||
}
|
||||
}
|
||||
for (feature, bit, name) in [
|
||||
(cpuid(1, 0)[ECX], CPUID_POPCNT, "popcnt"),
|
||||
(cpuid(0x8000_0001, 0)[ECX], CPUID_LZCNT, "lzcnt"),
|
||||
] {
|
||||
assert_ne!(feature & bit, 0, "{name}");
|
||||
for (bits, low, source, high) in sizes {
|
||||
decodable(&format!("{name} {low}, {source}"));
|
||||
decodable(&format!("{name} {high}, {}", memory(bits)));
|
||||
}
|
||||
}
|
||||
// Long mode: 64-bit operands and the registers only it has.
|
||||
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
|
||||
decodable("add r9, r12");
|
||||
decodable("movabs r15, 0x8877665544332211");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreported_features_each_have_an_instruction_that_is_refused() {
|
||||
// (feature, leaf, result register, bit, an instruction of that feature)
|
||||
let witnesses: &[(&str, u32, usize, u32, &[u8])] = &[
|
||||
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
|
||||
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
|
||||
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
|
||||
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
|
||||
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
|
||||
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
|
||||
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
|
||||
("SSE2", 1, EDX, 26, &[0x66, 0x0F, 0xF7, 0xC1]), // maskmovdqu xmm0, xmm1
|
||||
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
|
||||
(
|
||||
"PCLMULQDQ",
|
||||
1,
|
||||
ECX,
|
||||
1,
|
||||
&[0x66, 0x0F, 0x3A, 0x44, 0xC1, 0x00],
|
||||
), // pclmulqdq xmm0, xmm1, 0
|
||||
("SSSE3", 1, ECX, 9, &[0x66, 0x0F, 0x38, 0x00, 0xC1]), // pshufb xmm0, xmm1
|
||||
("FMA", 1, ECX, 12, &[0xC4, 0xE2, 0x71, 0x98, 0xC2]), // vfmadd132ps xmm0, xmm1, xmm2
|
||||
("CMPXCHG16B", 1, ECX, 13, &[0x48, 0x0F, 0xC7, 0x0E]), // cmpxchg16b [rsi]
|
||||
("SSE4.1", 1, ECX, 19, &[0x66, 0x0F, 0x38, 0x40, 0xC1]), // pmulld xmm0, xmm1
|
||||
("SSE4.2", 1, ECX, 20, &[0xF2, 0x0F, 0x38, 0xF1, 0xC1]), // crc32 eax, ecx
|
||||
("MOVBE", 1, ECX, 22, &[0x0F, 0x38, 0xF0, 0x06]), // movbe eax, [rsi]
|
||||
("AESNI", 1, ECX, 25, &[0x66, 0x0F, 0x38, 0xDC, 0xC1]), // aesenc xmm0, xmm1
|
||||
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
|
||||
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
|
||||
("F16C", 1, ECX, 29, &[0xC4, 0xE2, 0x79, 0x13, 0xC1]), // vcvtph2ps xmm0, xmm1
|
||||
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
|
||||
("BMI1", 7, EBX, 3, &[0xC4, 0xE2, 0x70, 0xF2, 0xC2]), // andn eax, ecx, edx
|
||||
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
|
||||
("BMI2", 7, EBX, 8, &[0xC4, 0xE2, 0x73, 0xF6, 0xC2]), // mulx eax, ecx, edx
|
||||
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
|
||||
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
|
||||
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
|
||||
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
|
||||
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
|
||||
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
|
||||
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
|
||||
];
|
||||
for &(feature, leaf, register, bit, code) in witnesses {
|
||||
assert_eq!(
|
||||
cpuid(leaf, 0)[register] >> bit & 1,
|
||||
0,
|
||||
"{feature} is reported"
|
||||
);
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = ENTRY;
|
||||
for (engine, state, exit) in both(&cpu, &padded, 1) {
|
||||
assert!(
|
||||
matches!(exit, ExitReason::IllegalInstruction(_)),
|
||||
"{feature}: {code:02X?} ran on the {engine} ({exit:?}); report the feature only \
|
||||
once all of it is implemented"
|
||||
);
|
||||
assert_eq!(state, cpu, "{feature} on the {engine}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guest_can_use_an_instruction_after_testing_its_feature_bit() {
|
||||
// mov eax, 1
|
||||
// cpuid
|
||||
// bt ecx, 23 ; POPCNT
|
||||
// jnc done
|
||||
// popcnt rax, rsi
|
||||
// done: hlt
|
||||
let code = [
|
||||
0xB8, 0x01, 0x00, 0x00, 0x00, 0x0F, 0xA2, 0x0F, 0xBA, 0xE1, 0x17, 0x73, 0x05, 0xF3, 0x48,
|
||||
0x0F, 0xB8, 0xC6, 0xF4,
|
||||
];
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = 0xF0F0_0000_0000_0001;
|
||||
for (engine, state, exit) in both(&cpu, &code, 16) {
|
||||
assert_eq!(exit, ExitReason::Halt, "{engine}");
|
||||
// Nine bits are set in RSI. Leaf 1 leaves EAX zero, so a skipped
|
||||
// POPCNT would show as 0.
|
||||
assert_eq!(state.gpr[RAX], 9, "{engine}");
|
||||
assert_eq!(state.rip, ENTRY + code.len() as u64, "{engine}");
|
||||
}
|
||||
}
|
||||
@@ -1307,6 +1307,18 @@ addr32_sum_wraps_at_32_bits: rbx=ffff0000 rcx=10000+D rax=0 m0=44332211 => rax=1
|
||||
486601d8
|
||||
SDM 2A 2.2.1
|
||||
rex_not_adjacent_to_opcode_is_ignored: rax=112233445566ffff rbx=1 => rax=1122334455660000 f=CPAZso
|
||||
@ .byte 0x41,0x66,0x01,0xd8
|
||||
416601d8
|
||||
SDM 2A 2.2.1
|
||||
ignored_rex_b_does_not_select_r8: rax=112233445566ffff rbx=1 r8=5 => rax=1122334455660000 f=CPAZso
|
||||
@ .byte 0x48,0x64,0x8b,0x03
|
||||
48648b03
|
||||
SDM 2A 2.2.1; 1 3.4.1.1
|
||||
ignored_rex_w_before_segment_prefix_loads_32_bits: rax=ffffffffffffffff rbx=8 fs8=1122334455667788 => rax=44332211 f=*
|
||||
@ .byte 0x41,0x66,0x41,0x01,0xd8
|
||||
41664101d8
|
||||
SDM 2A 2.2.1
|
||||
rex_after_ignored_rex_applies: rax=7 rbx=1 r8=112233445566ffff => r8=1122334455660000 f=CPAZso
|
||||
@ .byte 0x66,0x48,0x01,0xd8
|
||||
664801d8
|
||||
SDM 2A 2.2.1.2
|
||||
@@ -1353,6 +1365,33 @@ mov_moffs8_store: rax=77 m0=00000000 => m0=00000077 f=*
|
||||
thirteen_byte_fs_add_imm32: rax=10 rbx=8 fs120=0000000000000000 => fs120=4433221100000000 f=cPazso
|
||||
";
|
||||
|
||||
/// Single-thread baseline for the fences (#199). Each engine completes every
|
||||
/// load and store of an instruction before the next instruction starts, so the
|
||||
/// cases only require that a fence changes nothing and that accesses on either
|
||||
/// side of it happen in program order. Nothing here involves a second thread.
|
||||
const FENCES: &str = r"
|
||||
@ mov [rdi], rax; mfence; mov rbx, [rdi]
|
||||
488907 0faef0 488b1f
|
||||
SDM 2B MFENCE
|
||||
mfence_store_is_visible_to_a_later_load: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 f=*
|
||||
@ mov [rdi], rax; sfence; mov rbx, [rdi+8]
|
||||
488907 0faef8 488b5f08
|
||||
SDM 2B SFENCE
|
||||
sfence_after_a_store_keeps_other_memory: rdi=D rax=1 m0=0000000000000000 m8=aabbccddeeff0011 => rbx=1100ffeeddccbbaa m0=0100000000000000 f=*
|
||||
@ mov rbx, [rdi]; lfence; mov [rdi], rax
|
||||
488b1f 0faee8 488907
|
||||
SDM 2B LFENCE
|
||||
lfence_load_precedes_a_later_store: rdi=D rax=5 m0=0200000000000000 => rbx=2 m0=0500000000000000 f=*
|
||||
@ mfence; lfence; sfence
|
||||
0faef0 0faee8 0faef8
|
||||
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE
|
||||
fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 => f=*
|
||||
@ .byte 0x0f,0xae,0xf5; .byte 0x0f,0xae,0xeb; .byte 0x0f,0xae,0xff
|
||||
0faef5 0faeeb 0faeff
|
||||
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE (the r/m field is ignored)
|
||||
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
|
||||
";
|
||||
|
||||
const MEMORY_FAULTS: &str = r"
|
||||
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
|
||||
41b801000000 00d8 !488b0e 41b902000000
|
||||
@@ -2596,12 +2635,15 @@ add_memory_crosses_contiguous_pages: rdi=D+1000 mffd=ffffffffffffffff => mffd=00
|
||||
push_pop_cross_contiguous_pages: rsp=D+1004 rax=1122334455667788 => rbx=1122334455667788 mffc=8877665544332211 f=*
|
||||
";
|
||||
|
||||
const DEFECT_EXACT_UNMASKED_OVERFLOW: &str = r"
|
||||
const EXACT_UNMASKED_OVERFLOW: &str = r"
|
||||
@ mulss xmm1, xmm2
|
||||
!f30f59ca
|
||||
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
|
||||
unmasked_overflow_exact_sets_only_oe: x1=s:7f7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
|
||||
unmasked_negative_overflow_exact_sets_only_oe: x1=s:ff7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
|
||||
unmasked_overflow_exact_sets_only_oe_down: x1=s:7f7fffff x2=s:40000000 mx=3b80 => mx=3b88 f=* ! XM
|
||||
unmasked_overflow_exact_sets_only_oe_up: x1=s:7f7fffff x2=s:40000000 mx=5b80 => mx=5b88 f=* ! XM
|
||||
unmasked_overflow_exact_sets_only_oe_zero: x1=s:7f7fffff x2=s:40000000 mx=7b80 => mx=7b88 f=* ! XM
|
||||
@ addsd xmm1, xmm2
|
||||
!f20f58ca
|
||||
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
|
||||
@@ -2631,6 +2673,7 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("strings", STRINGS),
|
||||
("fs_gs", FS_GS),
|
||||
("decoding", DECODING),
|
||||
("fences", FENCES),
|
||||
("memory_faults", MEMORY_FAULTS),
|
||||
(
|
||||
"defect_straddling_fault_address",
|
||||
@@ -2649,10 +2692,7 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED),
|
||||
("fp_beyond_sse2", FP_BEYOND_SSE2),
|
||||
("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION),
|
||||
(
|
||||
"defect_exact_unmasked_overflow",
|
||||
DEFECT_EXACT_UNMASKED_OVERFLOW,
|
||||
),
|
||||
("exact_unmasked_overflow", EXACT_UNMASKED_OVERFLOW),
|
||||
("page_crossing", PAGE_CROSSING),
|
||||
];
|
||||
|
||||
@@ -2666,31 +2706,21 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("bt_memory_register_offset_can_fault", 0),
|
||||
("btr16_memory_negative_16bit_offset", 0),
|
||||
("bts_memory_negative_offset", 0),
|
||||
("cmpsb_is_rsi_minus_rdi", 0),
|
||||
("cmpsb_is_rsi_minus_rdi", 1),
|
||||
("cmpxchg16b_equal", 0),
|
||||
("cmpxchg16b_equal_without_lock", 0),
|
||||
("cmpxchg16b_not_equal", 0),
|
||||
("cmpxchg16b_unaligned_is_gp", 0),
|
||||
("cmpxchg16b_unaligned_without_lock_is_gp", 0),
|
||||
("cmpxchg32_equal", 0),
|
||||
("cmpxchg64_memory_equal_without_lock", 0),
|
||||
("cmpxchg64_memory_not_equal", 0),
|
||||
("cmpxchg64_memory_not_equal_without_lock", 0),
|
||||
("cmpxchg8_not_equal_loads_al", 0),
|
||||
("cmpxchg8b_equal", 0),
|
||||
("cmpxchg8b_equal_without_lock", 0),
|
||||
("cmpxchg8b_not_equal", 0),
|
||||
("cmpxchg_mismatch_still_writes", 0),
|
||||
("crc32c_byte_and_qword_forms_agree", 0),
|
||||
("crc32c_check_string", 0),
|
||||
("dpps_mask", 0),
|
||||
("enter_leave_round_trip", 0),
|
||||
("fifteen_byte_instruction_executes", 0),
|
||||
("fs_addr32_truncates_before_adding_base", 0),
|
||||
("fs_rep_movsb_overrides_source_only", 0),
|
||||
("fs_rep_movsb_overrides_source_only_df_clear", 0),
|
||||
("gs_lock_xadd", 0),
|
||||
("gs_xadd_without_lock", 0),
|
||||
("haddps_hsubpd_addsubps", 0),
|
||||
("insertps_zero_mask", 0),
|
||||
("jecxz_tests_low_32_bits", 1),
|
||||
@@ -2699,17 +2729,15 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("lahf_zero", 0),
|
||||
("lea64_addr32_truncates_effective_address", 0),
|
||||
("lock_btc_memory", 0),
|
||||
("lodsd_zero_extends", 0),
|
||||
("lodsd_zero_extends", 1),
|
||||
("lodsd_zero_extends_df_clear", 0),
|
||||
("lodsw_preserves_upper48", 0),
|
||||
("lodsw_preserves_upper48", 1),
|
||||
("loop_decrements_rcx_without_flags", 1),
|
||||
("loopne_stops_on_zero_flag", 1),
|
||||
("maskmovdqu_selects_bytes", 0),
|
||||
("mov_moffs64_load", 0),
|
||||
("mov_moffs8_store", 0),
|
||||
("movddup_movsldup_movshdup", 0),
|
||||
("movdqa_movaps_aligned_store_and_load", 3),
|
||||
("movsb_forward", 0),
|
||||
("mpsadbw", 0),
|
||||
("pabs_min_is_unchanged", 0),
|
||||
("packusdw", 0),
|
||||
@@ -2731,44 +2759,19 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("ptest_flags", 0),
|
||||
("push16_moves_rsp_by_two", 0),
|
||||
("pushfq_popfq_status_round_trip", 0),
|
||||
("rcl16_by16", 0),
|
||||
("rcl16_by17_is_identity", 0),
|
||||
("rcl32_by31", 0),
|
||||
("rcl32_cl32_affects_nothing_but_extension", 0),
|
||||
("rcl64_by63", 0),
|
||||
("rcl8_by1_clear_carry_in", 0),
|
||||
("rcl8_by1_set_carry_in_preserves_szap", 0),
|
||||
("rcl8_by8", 0),
|
||||
("rcl8_by9_is_identity", 0),
|
||||
("rcpps_special_values", 0),
|
||||
("rcpss_relative_error_bound", 0),
|
||||
("rcpss_rsqrtss_signal_nothing", 0),
|
||||
("rcr64_by1", 0),
|
||||
("rcr8_by10_is_by_one_mod_9", 0),
|
||||
("rcr8_by1_clear_carry_in", 0),
|
||||
("rcr8_by1_set_carry_in", 0),
|
||||
("rep_lodsb_source_fault", 0),
|
||||
("rep_movs_zero_count_touches_nothing", 0),
|
||||
("rep_movsb_addr32_uses_32bit_registers", 0),
|
||||
("rep_movsb_fault_df_clear", 0),
|
||||
("rep_movsb_fault_stops_at_failing_iteration", 0),
|
||||
("rep_movsb_overlap_propagates_df_clear", 0),
|
||||
("rep_movsq_overlap_propagates", 0),
|
||||
("rep_movsq_zero_count_df_clear", 0),
|
||||
("rep_movsw_backward", 0),
|
||||
("rep_stosd_df_clear", 0),
|
||||
("rep_stosd_forward", 0),
|
||||
("rep_stosq_fault_df_clear", 0),
|
||||
("rep_stosq_fault_stops_at_failing_iteration", 0),
|
||||
("repe_cmpsb_fault_restores_flags", 0),
|
||||
("rep_lodsb_source_fault", 1),
|
||||
("rep_movsb_addr32_uses_32bit_registers", 1),
|
||||
("repe_cmpsb_fault_restores_flags", 1),
|
||||
("repe_cmpsb_fault_restores_flags_df_clear", 0),
|
||||
("repe_cmpsb_stops_at_difference", 0),
|
||||
("repe_cmpsb_stops_at_difference", 1),
|
||||
("repe_cmpsb_stops_at_difference_df_clear", 0),
|
||||
("repe_cmpsb_zero_count_keeps_flags", 0),
|
||||
("repne_scasb_finds_byte", 0),
|
||||
("repe_cmpsb_zero_count_keeps_flags", 1),
|
||||
("repne_scasb_finds_byte", 1),
|
||||
("repne_scasb_finds_byte_df_clear", 0),
|
||||
("repne_scasd_exhausts_count", 0),
|
||||
("rex_not_adjacent_to_opcode_is_ignored", 0),
|
||||
("repne_scasd_exhausts_count", 1),
|
||||
("roundps_uses_mxcsr_rc", 0),
|
||||
("roundsd_suppress_precision", 0),
|
||||
("roundss_imm_modes", 0),
|
||||
@@ -2779,19 +2782,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("shld32_by4", 0),
|
||||
("shld32_cl32_is_count_zero", 0),
|
||||
("shld64_by63", 0),
|
||||
("shr_rcr_128bit_right_shift", 1),
|
||||
("shrd32_by8", 0),
|
||||
("shrd64_by1_sign_change", 0),
|
||||
("shrd64_cl64_is_count_zero", 0),
|
||||
("xadd32_reg_reg", 0),
|
||||
("xadd64_memory", 0),
|
||||
("xadd64_memory_without_lock", 0),
|
||||
("xadd64_same_register_doubles", 0),
|
||||
("xadd8_al_ah", 0),
|
||||
("xadd_readonly_page_keeps_register", 0),
|
||||
("xchg_ax_r9w_preserves_both_uppers", 0),
|
||||
("xchg_eax_ebx_clears_both_uppers", 0),
|
||||
("xchg_rax_r8_is_not_nop", 0),
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -3462,6 +3455,11 @@ fn decoding() {
|
||||
check_group(DECODING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fences() {
|
||||
check_group(FENCES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_faults() {
|
||||
check_group(MEMORY_FAULTS);
|
||||
@@ -3541,9 +3539,8 @@ fn defect_overlong_instruction() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "known defect (#155): an exact unmasked overflow sets PE as well as OE"]
|
||||
fn defect_exact_unmasked_overflow() {
|
||||
check_group(DEFECT_EXACT_UNMASKED_OVERFLOW);
|
||||
fn exact_unmasked_overflow() {
|
||||
check_group(EXACT_UNMASKED_OVERFLOW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3627,6 +3624,7 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
let memory = start.image.load(&case.code);
|
||||
let text: Vec<&str> = case.asm.split(';').map(str::trim).collect();
|
||||
let mut routes = Vec::new();
|
||||
let mut repeats = false;
|
||||
for (index, &offset) in case.offsets.iter().enumerate() {
|
||||
let Ok(insn) = decode(CODE + offset as u64, |at| memory.fetch_instruction_byte(at))
|
||||
else {
|
||||
@@ -3634,6 +3632,7 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
};
|
||||
let name = text.get(index).copied().unwrap_or(case.asm);
|
||||
routes.push(is_native(&insn));
|
||||
repeats |= insn.rep;
|
||||
if is_native(&insn) {
|
||||
native.insert(name);
|
||||
} else {
|
||||
@@ -3648,13 +3647,13 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
};
|
||||
counts.entry(group).or_default()[kind] += 1;
|
||||
// Straight-line cases run each instruction once, so the counter must equal
|
||||
// the number of helper instructions.
|
||||
// the number of helper instructions. A REP form runs once per element.
|
||||
let labelled = text.iter().any(|piece| {
|
||||
piece
|
||||
.split_once(':')
|
||||
.is_some_and(|(label, _)| label.parse::<u8>().is_ok())
|
||||
});
|
||||
if !labelled && case.fault.is_empty() && routes.len() == case.offsets.len() {
|
||||
if !labelled && !repeats && case.fault.is_empty() && routes.len() == case.offsets.len() {
|
||||
let mut dbt = new_dbt();
|
||||
let mut memory = memory.clone();
|
||||
run_dbt(&mut dbt, &start.cpu, &mut memory, BUDGET);
|
||||
@@ -4070,11 +4069,7 @@ fn shift_and_rotate_sweep_matches_operation_pseudocode() {
|
||||
runs += bench.runs;
|
||||
}
|
||||
}
|
||||
let wanted: Vec<String> = ["rcl", "rcr"]
|
||||
.iter()
|
||||
.flat_map(|op| WIDTHS.map(|bits| format!("{op}{bits}")))
|
||||
.collect();
|
||||
assert_eq!(refused, wanted, "unsupported shift forms changed");
|
||||
assert_eq!(refused, Vec::<String>::new(), "a shift form is refused");
|
||||
println!("{runs} engine runs");
|
||||
}
|
||||
|
||||
@@ -4764,12 +4759,7 @@ fn deliver(
|
||||
}
|
||||
if lowest + precision - 1 > format.max_exponent() {
|
||||
if mxcsr & OM == 0 {
|
||||
// PE of an exact overflow is `defect_exact_unmasked_overflow`; this
|
||||
// sweep compares every other bit.
|
||||
return Outcome {
|
||||
open: if unbounded_exact { PE } else { 0 },
|
||||
..outcome(0, OE | unbounded_inexact)
|
||||
};
|
||||
return outcome(0, OE | unbounded_inexact);
|
||||
}
|
||||
let to_infinity = match mode {
|
||||
0 => true,
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! MOVS, STOS, REP and the direction flag (issue #129).
|
||||
//!
|
||||
//! Expected results come from a byte-array model written from the operation
|
||||
//! sections of the Intel SDM Vol. 2 for MOVS, STOS, REP, CLD and STD. The
|
||||
//! model never decodes or calls the production semantics. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
//! Nothing was compared with x86 hardware.
|
||||
//!
|
||||
//! A REP form runs one element per step and stays on the instruction until RCX
|
||||
//! is zero. The tests check that rule through the step counts, so a repeat can
|
||||
//! never outrun the step budget.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
use xenora_loader::x86_table::{FORMS, Op};
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// One writable page with nothing mapped on either side.
|
||||
const DATA: u64 = 0x8000;
|
||||
const PAGE: usize = 0x1000;
|
||||
const END: u64 = DATA + PAGE as u64;
|
||||
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RSI: usize = 6;
|
||||
const RDI: usize = 7;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Kind {
|
||||
Movs,
|
||||
Stos,
|
||||
}
|
||||
|
||||
/// `[rep] movs/stos` for an element of `size` bytes, in the assembler's order.
|
||||
fn encode(kind: Kind, size: u64, rep: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
if rep {
|
||||
code.push(0xF3);
|
||||
}
|
||||
match size {
|
||||
2 => code.push(0x66),
|
||||
8 => code.push(0x48),
|
||||
_ => {}
|
||||
}
|
||||
code.push(match (kind, size) {
|
||||
(Kind::Movs, 1) => 0xA4,
|
||||
(Kind::Movs, _) => 0xA5,
|
||||
(Kind::Stos, 1) => 0xAA,
|
||||
(Kind::Stos, _) => 0xAB,
|
||||
});
|
||||
code
|
||||
}
|
||||
|
||||
fn image(code: &[u8], data: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(DATA, PAGE, MemoryPermissions::READ_WRITE, data)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn bytes(memory: &GuestMemory) -> Vec<u8> {
|
||||
let mut out = vec![0; PAGE];
|
||||
memory.read_bytes(DATA, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
struct Run {
|
||||
name: &'static str,
|
||||
result: ExecutionResult,
|
||||
memory: GuestMemory,
|
||||
/// Instructions the DBT ran on the shared semantics.
|
||||
helpers: usize,
|
||||
}
|
||||
|
||||
/// The interpreter and the DBT, each from its own copy of the state.
|
||||
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
|
||||
let mut interpreted = memory.clone();
|
||||
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
|
||||
let mut translated = memory.clone();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut state = cpu.clone();
|
||||
let native = engine.run(&mut state, &mut translated, budget);
|
||||
[
|
||||
Run {
|
||||
name: "interpreter",
|
||||
result,
|
||||
memory: interpreted,
|
||||
helpers: 0,
|
||||
},
|
||||
Run {
|
||||
name: "DBT",
|
||||
result: native,
|
||||
memory: translated,
|
||||
helpers: engine.metrics.interpreter_fallbacks,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Deterministic generator (xorshift64*).
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
}
|
||||
|
||||
/// The architectural effect of `count` elements on a byte array: each element
|
||||
/// is read whole, then written, then the pointers move by its size.
|
||||
fn model(
|
||||
kind: Kind,
|
||||
size: u64,
|
||||
backward: bool,
|
||||
count: u64,
|
||||
data: &mut [u8],
|
||||
rax: u64,
|
||||
(mut rsi, mut rdi): (u64, u64),
|
||||
) -> (u64, u64) {
|
||||
let size_bytes = size as usize;
|
||||
for _ in 0..count {
|
||||
let element: Vec<u8> = match kind {
|
||||
Kind::Movs => {
|
||||
let from = (rsi - DATA) as usize;
|
||||
data[from..from + size_bytes].to_vec()
|
||||
}
|
||||
Kind::Stos => rax.to_le_bytes()[..size_bytes].to_vec(),
|
||||
};
|
||||
let to = (rdi - DATA) as usize;
|
||||
data[to..to + size_bytes].copy_from_slice(&element);
|
||||
if kind == Kind::Movs {
|
||||
rsi = if backward { rsi - size } else { rsi + size };
|
||||
}
|
||||
rdi = if backward { rdi - size } else { rdi + size };
|
||||
}
|
||||
(rsi, rdi)
|
||||
}
|
||||
|
||||
const FLAGS: RFlags = RFlags {
|
||||
cf: true,
|
||||
zf: false,
|
||||
sf: true,
|
||||
of: false,
|
||||
pf: true,
|
||||
af: false,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_form_matches_a_byte_array_model_and_counts_one_step_per_element() {
|
||||
let mut random = Random(0x1234_5678_9ABC_DEF1);
|
||||
for kind in [Kind::Movs, Kind::Stos] {
|
||||
for size in [1, 2, 4, 8] {
|
||||
for rep in [false, true] {
|
||||
for backward in [false, true] {
|
||||
for round in 0..40 {
|
||||
// Counts 0 to 9. Source and destination start within 24
|
||||
// bytes of each other, so the ranges often overlap.
|
||||
let count = round % 10;
|
||||
let rsi = DATA + 0x400 + random.next() % 0x100;
|
||||
let rdi = rsi + random.next() % 49 - 24;
|
||||
let rax = random.next();
|
||||
let data: Vec<u8> = (0..PAGE).map(|_| random.next() as u8).collect();
|
||||
|
||||
let mut code = encode(kind, size, rep);
|
||||
code.push(0xF4); // hlt
|
||||
let memory = image(&code, &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
for register in &mut cpu.gpr {
|
||||
*register = random.next();
|
||||
}
|
||||
cpu.gpr[RAX] = rax;
|
||||
cpu.gpr[RCX] = count;
|
||||
cpu.gpr[RSI] = rsi;
|
||||
cpu.gpr[RDI] = rdi;
|
||||
cpu.df = backward;
|
||||
cpu.flags = FLAGS;
|
||||
|
||||
// Without REP exactly one element moves and RCX is not
|
||||
// read or written.
|
||||
let elements = if rep { count } else { 1 };
|
||||
let mut wanted_data = data.clone();
|
||||
let (wanted_rsi, wanted_rdi) = model(
|
||||
kind,
|
||||
size,
|
||||
backward,
|
||||
elements,
|
||||
&mut wanted_data,
|
||||
rax,
|
||||
(rsi, rdi),
|
||||
);
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.rip = ENTRY + code.len() as u64;
|
||||
wanted.gpr[RSI] = wanted_rsi;
|
||||
wanted.gpr[RDI] = wanted_rdi;
|
||||
if rep {
|
||||
wanted.gpr[RCX] = 0;
|
||||
}
|
||||
// One step per element, one for a REP with a zero
|
||||
// count, and one for the HLT.
|
||||
let steps = elements.max(1) as usize + 1;
|
||||
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
let what = format!(
|
||||
"{kind:?} size {size} rep={rep} backward={backward} count={count} \
|
||||
on the {}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.exit_reason, ExitReason::Halt, "{what}");
|
||||
assert_eq!(run.result.final_state, wanted, "{what}");
|
||||
assert!(bytes(&run.memory) == wanted_data, "{what}: memory");
|
||||
assert_eq!(run.result.instructions_executed, steps, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_budget_stops_a_repeat_part_way_and_it_resumes() {
|
||||
// rep stosb; hlt
|
||||
let code = [0xF3, 0xAA, 0xF4];
|
||||
let memory = image(&code, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x5A;
|
||||
cpu.gpr[RCX] = 100;
|
||||
cpu.gpr[RDI] = DATA + 0x200;
|
||||
for run in both(&cpu, &memory, 10) {
|
||||
// Ten steps store ten bytes and leave RIP on the instruction.
|
||||
assert_eq!(
|
||||
run.result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.instructions_executed, 10, "{}", run.name);
|
||||
let state = &run.result.final_state;
|
||||
assert_eq!(
|
||||
(state.rip, state.gpr[RCX], state.gpr[RDI]),
|
||||
(ENTRY, 90, DATA + 0x20A),
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!(written[0x200..0x20A], [0x5A; 10], "{}", run.name);
|
||||
assert_eq!(written[0x20A..0x264], [0; 90], "{}", run.name);
|
||||
if run.name == "DBT" {
|
||||
assert_eq!(run.helpers, 10);
|
||||
}
|
||||
|
||||
// Resuming from that state finishes the remaining ninety and halts.
|
||||
let [rest, _] = both(state, &run.memory, 1000);
|
||||
assert_eq!(rest.result.exit_reason, ExitReason::Halt, "{}", run.name);
|
||||
assert_eq!(rest.result.instructions_executed, 91, "{}", run.name);
|
||||
assert_eq!(rest.result.final_state.gpr[RCX], 0, "{}", run.name);
|
||||
assert_eq!(
|
||||
bytes(&rest.memory)[0x200..0x264],
|
||||
[0x5A; 100],
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_is_all_of_rcx() {
|
||||
// rep stosb with a count above 32 bits: two steps take exactly two off it.
|
||||
let memory = image(&[0xF3, 0xAA, 0xF4], &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 0x0000_0001_0000_0001;
|
||||
cpu.gpr[RDI] = DATA;
|
||||
for run in both(&cpu, &memory, 2) {
|
||||
assert_eq!(
|
||||
run.result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(
|
||||
run.result.final_state.gpr[RCX], 0x0000_0000_FFFF_FFFF,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.final_state.rip, ENTRY, "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_keeps_the_elements_already_done() {
|
||||
// (code, RSI, RDI, backward, elements that complete before the fault)
|
||||
let cases: &[(&[u8], u64, u64, bool, u64)] = &[
|
||||
// rep movsq up to the end of the page: 19 bytes hold two elements, and
|
||||
// the third would end past the page.
|
||||
(&[0xF3, 0x48, 0xA5], DATA, END - 19, false, 2),
|
||||
// rep stosd down to the start of the page: elements at offsets 5 and 1
|
||||
// fit, the next would start before the page.
|
||||
(&[0xF3, 0xAB], 0, DATA + 5, true, 2),
|
||||
// rep movsw from a source that ends: three elements can be read.
|
||||
(&[0xF3, 0x66, 0xA5], END - 6, DATA + 0x100, false, 3),
|
||||
// rep movsb with no readable source at all.
|
||||
(&[0xF3, 0xA4], END, DATA + 0x100, false, 0),
|
||||
];
|
||||
let mut random = Random(77);
|
||||
for &(code, rsi, rdi, backward, done) in cases {
|
||||
let data: Vec<u8> = (0..PAGE).map(|_| random.next() as u8).collect();
|
||||
let memory = image(code, &data);
|
||||
let insn = decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
let (kind, size) = (
|
||||
if insn.op == Op::Movs {
|
||||
Kind::Movs
|
||||
} else {
|
||||
Kind::Stos
|
||||
},
|
||||
u64::from(insn.size),
|
||||
);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x1122_3344_5566_7788;
|
||||
cpu.gpr[RCX] = 9;
|
||||
cpu.gpr[RSI] = rsi;
|
||||
cpu.gpr[RDI] = rdi;
|
||||
cpu.df = backward;
|
||||
cpu.flags = FLAGS;
|
||||
|
||||
// The completed elements took effect. The faulting one changed
|
||||
// nothing, and RIP stays on the instruction so it can be restarted.
|
||||
let mut wanted_data = data.clone();
|
||||
let (wanted_rsi, wanted_rdi) = model(
|
||||
kind,
|
||||
size,
|
||||
backward,
|
||||
done,
|
||||
&mut wanted_data,
|
||||
cpu.gpr[RAX],
|
||||
(rsi, rdi),
|
||||
);
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.gpr[RCX] = 9 - done;
|
||||
wanted.gpr[RSI] = wanted_rsi;
|
||||
wanted.gpr[RDI] = wanted_rdi;
|
||||
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
let what = format!("{code:02X?} on the {}", run.name);
|
||||
assert!(
|
||||
matches!(run.result.exit_reason, ExitReason::MemoryFault(_)),
|
||||
"{what}: {:?}",
|
||||
run.result.exit_reason
|
||||
);
|
||||
assert_eq!(run.result.final_state, wanted, "{what}");
|
||||
assert!(bytes(&run.memory) == wanted_data, "{what}: memory");
|
||||
assert_eq!(run.result.instructions_executed, done as usize, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direction_flag_is_set_by_std_and_cleared_by_cld() {
|
||||
// std; stosb; cld; stosb; hlt
|
||||
let code = [0xFD, 0xAA, 0xFC, 0xAA, 0xF4];
|
||||
let memory = image(&code, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0xC3;
|
||||
cpu.gpr[RDI] = DATA + 0x80;
|
||||
cpu.flags = FLAGS;
|
||||
for run in both(&cpu, &memory, 16) {
|
||||
assert_eq!(run.result.exit_reason, ExitReason::Halt, "{}", run.name);
|
||||
// The first store steps down to 0x7F, the second back up to 0x80.
|
||||
assert_eq!(run.result.final_state.gpr[RDI], DATA + 0x80, "{}", run.name);
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!(written[0x7F..0x81], [0xC3, 0xC3], "{}", run.name);
|
||||
assert!(!run.result.final_state.df, "{}", run.name);
|
||||
// Neither instruction touches a status flag.
|
||||
assert_eq!(run.result.final_state.flags, FLAGS, "{}", run.name);
|
||||
}
|
||||
// The flag outlives the run that set it.
|
||||
for run in both(&cpu, &image(&[0xFD, 0xF4], &[0; PAGE]), 4) {
|
||||
assert!(run.result.final_state.df, "{}", run.name);
|
||||
assert_eq!(run.result.final_state.flags, FLAGS, "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_override_moves_the_source_only() {
|
||||
const BASE: u64 = 0x300;
|
||||
let mut data = vec![0u8; PAGE];
|
||||
data[0x10] = 0x11; // DATA + 0x10, what [RSI] names without a base
|
||||
data[0x310] = 0x22; // DATA + 0x10 + BASE, the same RSI under the FS or GS base
|
||||
for (code, uses_base) in [
|
||||
(&[0xA4][..], false), // movsb
|
||||
(&[0x64, 0xA4][..], true), // movsb with the source under FS
|
||||
(&[0x65, 0xA4][..], true), // movsb with the source under GS
|
||||
] {
|
||||
let memory = image(code, &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = BASE;
|
||||
cpu.gs_base = BASE;
|
||||
cpu.gpr[RSI] = DATA + 0x10;
|
||||
cpu.gpr[RDI] = DATA + 0x800;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!("{code:02X?} on the {}", run.name);
|
||||
// The destination is [RDI] with no base either way.
|
||||
let wanted = if uses_base { 0x22 } else { 0x11 };
|
||||
assert_eq!(bytes(&run.memory)[0x800], wanted, "{what}");
|
||||
assert_eq!(
|
||||
run.result.final_state.gpr[RSI],
|
||||
DATA + 0x11,
|
||||
"{what}: RSI moves by the element, not by the base"
|
||||
);
|
||||
}
|
||||
}
|
||||
// STOS has no source, and its destination takes no override.
|
||||
let memory = image(&[0x64, 0xAA], &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = BASE;
|
||||
cpu.gpr[RAX] = 0x77;
|
||||
cpu.gpr[RDI] = DATA + 0x800;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!((written[0x800], written[0xB00]), (0x77, 0), "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_the_declared_string_forms_decode() {
|
||||
let decode_bytes = |code: &[u8]| {
|
||||
decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
for kind in [Kind::Movs, Kind::Stos] {
|
||||
for size in [1, 2, 4, 8] {
|
||||
for rep in [false, true] {
|
||||
let code = encode(kind, size, rep);
|
||||
let insn =
|
||||
decode_bytes(&code).unwrap_or_else(|error| panic!("{code:02X?}: {error:?}"));
|
||||
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
|
||||
assert_eq!((u64::from(insn.size), insn.rep), (size, rep), "{code:02X?}");
|
||||
assert!(!is_native(&insn), "{code:02X?}");
|
||||
seen.insert(usize::from(insn.form));
|
||||
}
|
||||
}
|
||||
}
|
||||
for code in [[0xFC], [0xFD]] {
|
||||
seen.insert(usize::from(decode_bytes(&code).unwrap().form));
|
||||
}
|
||||
// Every declared form of these operations was reached above.
|
||||
for (index, form) in FORMS.iter().enumerate() {
|
||||
if matches!(form.op, Op::Movs | Op::Stos | Op::Cld | Op::Std) {
|
||||
assert!(seen.contains(&index), "{:?} {:?}", form.op, form.size);
|
||||
}
|
||||
}
|
||||
|
||||
let rejected: &[&[u8]] = &[
|
||||
&[0xF2, 0xA4], // repne movsb
|
||||
&[0xF2, 0xAB], // repne stosd
|
||||
&[0xF3, 0xF2, 0xA4], // both repeat prefixes
|
||||
&[0x67, 0xF3, 0xA4], // rep movsb with 32-bit addresses
|
||||
&[0xF0, 0xF3, 0xAA], // lock rep stosb
|
||||
&[0xF3, 0xFC], // rep cld
|
||||
&[0xA6], // cmpsb
|
||||
&[0xF3, 0xA6], // repe cmpsb
|
||||
&[0xAC], // lodsb
|
||||
&[0xAE], // scasb
|
||||
&[0xF2, 0xAE], // repne scasb
|
||||
];
|
||||
for code in rejected {
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let memory = image(&padded, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 3;
|
||||
cpu.gpr[RSI] = DATA;
|
||||
cpu.gpr[RDI] = DATA + 0x100;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert!(
|
||||
matches!(run.result.exit_reason, ExitReason::IllegalInstruction(_)),
|
||||
"{code:02X?} on the {}: {:?}",
|
||||
run.name,
|
||||
run.result.exit_reason
|
||||
);
|
||||
assert_eq!(run.result.final_state, cpu, "{code:02X?}");
|
||||
assert!(bytes(&run.memory) == vec![0; PAGE], "{code:02X?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,419 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Static probe reports for delay-loaded PE imports.
|
||||
//!
|
||||
//! The expected names and slot RVAs are read off the layout that
|
||||
//! `fixtures/pe/delay-imports.py` writes, not from the parser.
|
||||
//! `llvm-readobj --coff-imports` from LLVM 23.1.6 lists the same imports in
|
||||
//! the same order, with the address tables at RVA 0x2050, 0x3000 and 0x3020.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use xenora_loader::import_table::{DelayField, ImportTableError, parse_delay_imports};
|
||||
use xenora_loader::probe::{
|
||||
ImportedSymbol, ProbeConfig, ProbeReport, probe_pe_bytes, run_probe_and_export,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/delay-imports.exe");
|
||||
|
||||
/// DLL, symbol or ordinal, and import address table slot RVA.
|
||||
type Row = (&'static str, &'static str, u32);
|
||||
|
||||
const ORDINARY: [Row; 2] = [
|
||||
("fixture-ordinary.dll", "OrdinaryByName", 0x2050),
|
||||
("fixture-ordinary.dll", "Ordinal#3", 0x2058),
|
||||
];
|
||||
const DELAYED: [Row; 3] = [
|
||||
("fixture-delay-a.dll", "DelayedAlpha", 0x3000),
|
||||
("fixture-delay-a.dll", "Ordinal#7", 0x3008),
|
||||
("fixture-delay-b.dll", "DelayedBeta", 0x3020),
|
||||
];
|
||||
|
||||
// File offsets in the fixture.
|
||||
const NUMBER_OF_RVA_AND_SIZES: usize = 0x98 + 108;
|
||||
const DELAY_DIRECTORY_ENTRY: usize = 0x98 + 216;
|
||||
const DELAY_DIRECTORY_SIZE: usize = DELAY_DIRECTORY_ENTRY + 4;
|
||||
const RDATA_RAW_SIZE: usize = 0x188 + 40 + 16;
|
||||
/// The delay-load directory is at RVA 0x2200; `.rdata` maps RVA 0x2000 to 0x600.
|
||||
const FIRST_DESCRIPTOR: usize = 0x800;
|
||||
const SECOND_DESCRIPTOR: usize = 0x820;
|
||||
|
||||
fn rows(imports: &[ImportedSymbol]) -> Vec<(&str, &str, u32)> {
|
||||
imports
|
||||
.iter()
|
||||
.map(|import| (import.dll.as_str(), import.symbol.as_str(), import.iat_rva))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn put(pe: &mut [u8], offset: usize, value: u32) {
|
||||
pe[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Probe `pe` and return the report with the text files it exports.
|
||||
fn export(pe: &[u8], name: &str) -> (ProbeReport, BTreeMap<&'static str, String>) {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("xenora-probe-delay-{name}-{}", std::process::id()));
|
||||
let report = run_probe_and_export(pe, &dir, &ProbeConfig::default()).unwrap();
|
||||
let files = [
|
||||
"imports.csv",
|
||||
"missing_imports.csv",
|
||||
"candidate_static_report.json",
|
||||
"candidate_static_report.md",
|
||||
"runtime_gap_matrix.md",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|file| (file, std::fs::read_to_string(dir.join(file)).unwrap()))
|
||||
.collect();
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
(report, files)
|
||||
}
|
||||
|
||||
fn json_field(json: &str, name: &str) -> String {
|
||||
let prefix = format!("\"{name}\": ");
|
||||
json.lines()
|
||||
.find_map(|line| line.trim().strip_prefix(&prefix))
|
||||
.unwrap_or_else(|| panic!("no {name} in the JSON report"))
|
||||
.trim_end_matches(',')
|
||||
.trim_matches('"')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_and_delayed_imports_are_reported_apart() {
|
||||
let (report, files) = export(FIXTURE, "fixture");
|
||||
|
||||
assert_eq!(rows(&report.imports), ORDINARY);
|
||||
assert_eq!(rows(&report.delayed_imports), DELAYED);
|
||||
assert_eq!(report.import_error, None);
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
|
||||
let mut lines = files["imports.csv"].lines();
|
||||
let header = lines.next().unwrap();
|
||||
assert!(header.starts_with("module,symbol_or_ordinal,iat_rva,import_table,"));
|
||||
assert!(header.ends_with(",import_kind"));
|
||||
let columns = header.split(',').count();
|
||||
// The first four columns and the last one of every row.
|
||||
let listed: Vec<String> = lines
|
||||
.map(|line| {
|
||||
let fields: Vec<&str> = line.split(',').collect();
|
||||
assert_eq!(fields.len(), columns, "{line}");
|
||||
format!("{},{}", fields[..4].join(","), fields[columns - 1])
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,ordinary,name",
|
||||
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinary,ordinal",
|
||||
"\"fixture-delay-a.dll\",\"DelayedAlpha\",0x00003000,delayed,name",
|
||||
"\"fixture-delay-a.dll\",\"Ordinal#7\",0x00003008,delayed,ordinal",
|
||||
"\"fixture-delay-b.dll\",\"DelayedBeta\",0x00003020,delayed,name",
|
||||
]
|
||||
);
|
||||
|
||||
// Neither fixture DLL has a handler, so both ordinary imports are missing.
|
||||
// The delayed ones are not the binder's to resolve and stay off its list.
|
||||
assert_eq!(
|
||||
files["missing_imports.csv"].lines().collect::<Vec<_>>(),
|
||||
[
|
||||
"module,symbol_or_ordinal,iat_rva,import_kind",
|
||||
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,name",
|
||||
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinal",
|
||||
]
|
||||
);
|
||||
|
||||
let json = &files["candidate_static_report.json"];
|
||||
for (name, expected) in [
|
||||
("total_imports", "2"),
|
||||
("imported_dlls_count", "1"),
|
||||
("unresolved_imports", "2"),
|
||||
("distinct_import_keys", "2"),
|
||||
("delayed_imports", "3"),
|
||||
("delayed_imported_dlls_count", "2"),
|
||||
("delay_import_error", "none"),
|
||||
] {
|
||||
assert_eq!(json_field(json, name), expected, "{name}");
|
||||
}
|
||||
|
||||
let md = &files["candidate_static_report.md"];
|
||||
assert!(md.contains("- **Total Imported Thunks**: `2`"));
|
||||
assert!(md.contains("- **Delay-Loaded Import Slots**: `3` across `2` DLLs."));
|
||||
assert!(!md.contains("Delay-load import table is malformed"));
|
||||
assert!(
|
||||
files["runtime_gap_matrix.md"]
|
||||
.contains("The delay-load import tables contain 3 more slots across 2 DLLs.")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_decodes_the_entry_point_and_follows_no_delay_slot() {
|
||||
let report = probe_pe_bytes(FIXTURE, &ProbeConfig::default()).unwrap();
|
||||
|
||||
// The entry point is a lone RET at RVA 0x1000. The three delay-load slots
|
||||
// hold the addresses of INT3 stubs at 0x1010, 0x1018 and 0x1020. Reaching
|
||||
// one would mean the probe followed a slot, so none may be decoded.
|
||||
let decoded: Vec<(u32, &[u8])> = report
|
||||
.instruction_records
|
||||
.iter()
|
||||
.map(|record| (record.rva, record.bytes.as_slice()))
|
||||
.collect();
|
||||
assert_eq!(decoded, [(0x1000, &[0xc3][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_without_a_delay_directory_keeps_its_ordinary_imports() {
|
||||
// `fixtures/pe/trusted-runner.py` writes one import, `xenora.dll!fixture_draw`,
|
||||
// with its slot at RVA 0x2040 and no delay import descriptor.
|
||||
let runner = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
let (report, files) = export(runner, "runner");
|
||||
assert_eq!(
|
||||
rows(&report.imports),
|
||||
[("xenora.dll", "fixture_draw", 0x2040)]
|
||||
);
|
||||
assert_eq!(report.import_error, None);
|
||||
assert!(report.delayed_imports.is_empty());
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
|
||||
let listed: Vec<&str> = files["imports.csv"].lines().skip(1).collect();
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert!(listed[0].starts_with("\"xenora.dll\",\"fixture_draw\",0x00002040,ordinary,"));
|
||||
let json = &files["candidate_static_report.json"];
|
||||
assert_eq!(json_field(json, "total_imports"), "1");
|
||||
assert_eq!(json_field(json, "imported_dlls_count"), "1");
|
||||
assert_eq!(json_field(json, "delayed_imports"), "0");
|
||||
assert_eq!(json_field(json, "delayed_imported_dlls_count"), "0");
|
||||
assert_eq!(json_field(json, "delay_import_error"), "none");
|
||||
assert!(!files["runtime_gap_matrix.md"].contains("delay-load"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_directory_beyond_the_declared_count_is_not_read() {
|
||||
// With 13 data directories the header has no delay import descriptor, so
|
||||
// the bytes at its offset mean nothing.
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
put(&mut pe, NUMBER_OF_RVA_AND_SIZES, 13);
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(rows(&report.imports), ORDINARY);
|
||||
assert!(report.delayed_imports.is_empty());
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
|
||||
type Case = (
|
||||
&'static str,
|
||||
fn(&mut Vec<u8>),
|
||||
usize,
|
||||
ImportTableError,
|
||||
&'static str,
|
||||
);
|
||||
// (name, damage, delayed imports still listed, error, message)
|
||||
let cases: [Case; 13] = [
|
||||
(
|
||||
"directory-out-of-range",
|
||||
|pe| put(pe, DELAY_DIRECTORY_ENTRY, 0x9000),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// `.rdata` keeps 0x230 bytes: the first descriptor and half the second.
|
||||
"section-data-ends-inside-descriptor",
|
||||
|pe| put(pe, RDATA_RAW_SIZE, 0x230),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x2220 },
|
||||
"import data at RVA 0x00002220 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// The file ends where `.data` and its address tables would begin.
|
||||
"file-ends-before-address-table",
|
||||
|pe| pe.truncate(0xa00),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x3000 },
|
||||
"import data at RVA 0x00003000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"name-table-out-of-range",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR + 16, 0x9000),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"address-table-out-of-range",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 12, 0x9000),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// The second DLL's name table becomes the empty entry that ends the
|
||||
// first one, at RVA 0x2110, so no import reads the address table.
|
||||
"address-table-out-of-range-without-imports",
|
||||
|pe| {
|
||||
put(pe, SECOND_DESCRIPTOR + 16, 0x2110);
|
||||
put(pe, SECOND_DESCRIPTOR + 12, 0x9000);
|
||||
},
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"dll-name-out-of-range",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x9000),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// RVA 0x2028 is zero padding after the ordinary import directory.
|
||||
"dll-name-empty",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x2028),
|
||||
2,
|
||||
ImportTableError::MalformedName { rva: 0x2028 },
|
||||
"malformed import name at RVA 0x00002028",
|
||||
),
|
||||
(
|
||||
"dll-name-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::DllName,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002220 has no DLL name",
|
||||
),
|
||||
(
|
||||
"address-table-missing",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR + 12, 0),
|
||||
0,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2200,
|
||||
field: DelayField::AddressTable,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002200 has no import address table",
|
||||
),
|
||||
(
|
||||
"name-table-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 16, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::NameTable,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002220 has no import name table",
|
||||
),
|
||||
(
|
||||
"reserved-attribute-bit",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR, 3),
|
||||
0,
|
||||
ImportTableError::DelayReservedBits { rva: 0x2200 },
|
||||
"reserved attribute bits set in the delay-load descriptor at RVA 0x00002200",
|
||||
),
|
||||
(
|
||||
"virtual-address-form",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR, 0),
|
||||
2,
|
||||
ImportTableError::DelayVirtualAddresses { rva: 0x2220 },
|
||||
"delay-load descriptor at RVA 0x00002220 holds virtual addresses, not RVAs, and is not read",
|
||||
),
|
||||
];
|
||||
|
||||
for (name, damage, listed, error, message) in cases {
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
damage(&mut pe);
|
||||
let (report, files) = export(&pe, name);
|
||||
|
||||
assert_eq!(rows(&report.imports), ORDINARY, "{name}");
|
||||
assert_eq!(report.import_error, None, "{name}");
|
||||
assert_eq!(rows(&report.delayed_imports), DELAYED[..listed], "{name}");
|
||||
assert_eq!(report.delay_import_error, Some(error), "{name}");
|
||||
assert_eq!(error.to_string(), message, "{name}");
|
||||
|
||||
let json = &files["candidate_static_report.json"];
|
||||
assert_eq!(json_field(json, "total_imports"), "2", "{name}");
|
||||
assert_eq!(
|
||||
json_field(json, "delayed_imports"),
|
||||
listed.to_string(),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(json_field(json, "delay_import_error"), message, "{name}");
|
||||
assert!(
|
||||
files["candidate_static_report.md"].contains(&format!(
|
||||
"- **Delay-load import table is malformed**: {message}. Only the delay-loaded imports before it are listed."
|
||||
)),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_directory_size_bounds_the_table() {
|
||||
// The fixture declares 96 bytes at RVA 0x2200: two descriptors and the
|
||||
// empty one. A descriptor counts only if the declared size holds all of
|
||||
// it, and the size must reach the empty descriptor.
|
||||
let end = |rva| Some(ImportTableError::DelayDirectoryEnd { rva });
|
||||
for (size, listed, error) in [
|
||||
(0, 0, end(0x2200)),
|
||||
(31, 0, end(0x221f)),
|
||||
(32, 2, end(0x2220)),
|
||||
(63, 2, end(0x223f)),
|
||||
(64, 3, end(0x2240)),
|
||||
(95, 3, end(0x225f)),
|
||||
(96, 3, None),
|
||||
(97, 3, None),
|
||||
(0x1000, 3, None),
|
||||
// The directory would run past the end of the address space.
|
||||
(
|
||||
u32::MAX,
|
||||
0,
|
||||
Some(ImportTableError::OutOfBounds { rva: 0x2200 }),
|
||||
),
|
||||
] {
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
put(&mut pe, DELAY_DIRECTORY_SIZE, size);
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(rows(&report.imports), ORDINARY, "size {size}");
|
||||
assert_eq!(
|
||||
rows(&report.delayed_imports),
|
||||
DELAYED[..listed],
|
||||
"size {size}"
|
||||
);
|
||||
assert_eq!(report.delay_import_error, error, "size {size}");
|
||||
}
|
||||
assert_eq!(
|
||||
ImportTableError::DelayDirectoryEnd { rva: 0x2240 }.to_string(),
|
||||
"delay-load directory ends at RVA 0x00002240 before its empty descriptor"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endless_delay_table_is_refused() {
|
||||
// Every descriptor RVA maps onto the same 32 bytes, so the table never
|
||||
// reaches its empty entry within the megabyte it declares. The descriptor
|
||||
// names module "a" at RVA 0x1000, an empty name table at RVA 0x2000 and an
|
||||
// address table at RVA 0x3000.
|
||||
let mut bytes = vec![0u8; 48];
|
||||
put(&mut bytes, 0, 1);
|
||||
put(&mut bytes, 4, 0x1000);
|
||||
put(&mut bytes, 12, 0x3000);
|
||||
put(&mut bytes, 16, 0x2000);
|
||||
bytes[32] = b'a';
|
||||
let (imports, error) = parse_delay_imports(&bytes, 0x10_0000, 0x10_0000, |rva| match rva {
|
||||
0x1000..0x1002 => Some(32 + (rva - 0x1000) as usize),
|
||||
0x2000..0x2008 => Some(40 + (rva - 0x2000) as usize),
|
||||
0x3000..0x3008 => Some(40 + (rva - 0x3000) as usize),
|
||||
0x10_0000.. => Some((rva % 32) as usize),
|
||||
_ => None,
|
||||
});
|
||||
assert!(imports.is_empty());
|
||||
assert_eq!(error, Some(ImportTableError::TooManyDescriptors));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_never_panics_on_a_truncated_delay_fixture() {
|
||||
for len in 1..=FIXTURE.len() {
|
||||
// The probe may reject the file or report unreadable imports, but it
|
||||
// must not panic.
|
||||
let _ = probe_pe_bytes(&FIXTURE[..len], &ProbeConfig::default());
|
||||
}
|
||||
}
|
||||
@@ -120,17 +120,24 @@ fn build(imports: &[(&str, Symbol)]) -> Image {
|
||||
}
|
||||
|
||||
fn standard(clock: u64) -> (ImportRegistry, Arc<MockClock>) {
|
||||
let clock = Arc::new(MockClock::new(clock));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone())));
|
||||
let (registry, clock, _) = standard_with_state(clock);
|
||||
(registry, clock)
|
||||
}
|
||||
|
||||
fn standard_with_state(clock: u64) -> (ImportRegistry, Arc<MockClock>, Arc<ServicesState>) {
|
||||
let clock = Arc::new(MockClock::new(clock));
|
||||
let state = Arc::new(ServicesState::new(clock.clone()));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, state.clone());
|
||||
(registry, clock, state)
|
||||
}
|
||||
|
||||
/// A guest whose image imports every generated service from its own library.
|
||||
struct Guest {
|
||||
engine: DbtEngine,
|
||||
memory: GuestMemory,
|
||||
clock: Arc<MockClock>,
|
||||
state: Arc<ServicesState>,
|
||||
teb: u64,
|
||||
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
|
||||
xmm: [u128; 4],
|
||||
@@ -151,7 +158,7 @@ impl Guest {
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
|
||||
let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678);
|
||||
let bound = registry
|
||||
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
|
||||
.unwrap();
|
||||
@@ -162,6 +169,7 @@ impl Guest {
|
||||
engine,
|
||||
memory,
|
||||
clock,
|
||||
state,
|
||||
teb: 0,
|
||||
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
|
||||
}
|
||||
@@ -554,6 +562,48 @@ fn last_error_isolated_across_guest_thread_switches() {
|
||||
assert_eq!(guest.last_error(), 6);
|
||||
}
|
||||
|
||||
/// The last-error code is documented as kept per thread, and most functions
|
||||
/// set it only when they fail (errhandlingapi.h GetLastError).
|
||||
#[test]
|
||||
fn a_successful_call_keeps_another_threads_error_and_its_own() {
|
||||
let mut guest = Guest::new();
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0);
|
||||
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
|
||||
guest.teb = 0x20000;
|
||||
guest.call("SetLastError", &[0xFFFF_FFFF]);
|
||||
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
|
||||
assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104);
|
||||
assert_eq!(
|
||||
guest.last_error(),
|
||||
0xFFFF_FFFF,
|
||||
"success keeps a nonzero error"
|
||||
);
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.last_error(), 87);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() {
|
||||
let mut guest = Guest::new();
|
||||
guest.teb = 0x10000;
|
||||
guest.call("SetLastError", &[998]);
|
||||
guest.teb = 0x20000;
|
||||
guest.call("CloseHandle", &[0x1234]);
|
||||
|
||||
assert!(guest.state.retire_thread_last_error(0x10000));
|
||||
assert!(!guest.state.retire_thread_last_error(0x10000));
|
||||
assert!(
|
||||
!guest.state.retire_thread_last_error(0x30000),
|
||||
"a thread that never failed holds no value"
|
||||
);
|
||||
assert_eq!(guest.last_error(), 6, "the other thread is untouched");
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.last_error(), 0);
|
||||
guest.call("SetLastError", &[5]);
|
||||
assert_eq!(guest.last_error(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_error_is_set_by_failures_and_by_the_guest() {
|
||||
let mut guest = Guest::new();
|
||||
|
||||
@@ -54,7 +54,7 @@ def cases():
|
||||
for bits in (8, 16, 32, 64):
|
||||
out += [f"{op} {reg(1, bits)}", f"{op} {reg(9, bits)}", f"{op} {mem(bits)}"]
|
||||
out.append(f"{op} ch")
|
||||
for op in "rol ror shl shr sar".split():
|
||||
for op in "rol ror rcl rcr shl shr sar".split():
|
||||
for bits in (8, 16, 32, 64):
|
||||
for count in ("1", "3", "7", "cl"):
|
||||
out += [f"{op} {reg(3, bits)}, {count}", f"{op} {mem(bits)}, {count}"]
|
||||
@@ -84,11 +84,27 @@ def cases():
|
||||
f"mov {mem(bits)}, {reg(2, bits)}", f"mov {reg(14, bits)}, 0x5a",
|
||||
f"mov {mem(bits)}, 0x5a", f"xchg {reg(3, bits)}, {reg(9, bits)}",
|
||||
f"xchg {mem(bits)}, {reg(2, bits)}"]
|
||||
for op in ("xadd", "cmpxchg"):
|
||||
for bits in (8, 16, 32, 64):
|
||||
# Destination RAX always matches the accumulator; a register with
|
||||
# itself keeps the sum. LOCK is valid only with a memory destination.
|
||||
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
|
||||
f"{op} {reg(0, bits)}, {reg(2, bits)}", f"{op} {reg(3, bits)}, {reg(3, bits)}",
|
||||
f"{op} {mem(bits)}, {reg(2, bits)}", f"lock {op} {mem(bits)}, {reg(2, bits)}",
|
||||
f"lock {op} {mem(bits)}, {reg(0, bits)}"]
|
||||
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
|
||||
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
|
||||
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop",
|
||||
"nop dword ptr [rax + 8]", "pause", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
|
||||
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
|
||||
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
|
||||
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
|
||||
# The accumulator short form of XCHG: 91..97, and 90 with REX.B.
|
||||
for index in range(1, 16):
|
||||
bits = (16, 32, 64)[index % 3]
|
||||
out.append(f"xchg {reg(0, bits)}, {reg(index, bits)}")
|
||||
out += ["xchg r8w, ax", "xchg r8, rax", "xchg r8d, eax", "xchg ecx, eax", "xchg r15w, ax"]
|
||||
return list(dict.fromkeys(out))
|
||||
|
||||
|
||||
@@ -163,7 +179,13 @@ def assemble(lines):
|
||||
subprocess.run(["clang", "-target", "x86_64-apple-macos", "-c", source, "-o", obj], check=True)
|
||||
# One line per instruction: objdump never wraps its raw bytes.
|
||||
listing = subprocess.run(["objdump", "-d", obj], check=True, capture_output=True, text=True).stdout
|
||||
rows = [m.group(1).split() for m in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)", listing, re.M)]
|
||||
rows, prefix = [], []
|
||||
for match in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)(.*)$", listing, re.M):
|
||||
row = prefix + match.group(1).split()
|
||||
# objdump lists a leading LOCK prefix on a row of its own.
|
||||
prefix = row if match.group(2).strip() == "lock" else []
|
||||
if not prefix:
|
||||
rows.append(row)
|
||||
if len(rows) != len(lines):
|
||||
sys.exit(f"{len(lines)} instructions assembled to {len(rows)} rows")
|
||||
return "".join(f"{' '.join(row)} | {line}\n" for row, line in zip(rows, lines))
|
||||
|
||||
@@ -547,6 +547,86 @@ d3 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], cl
|
||||
48 d3 4c be 10 | ror qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 cd 3f | ror r13, 63
|
||||
49 c1 cd 00 | ror r13, 0
|
||||
d0 d3 | rcl bl, 1
|
||||
d0 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 d3 03 | rcl bl, 3
|
||||
c0 54 be 10 03 | rcl byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 d3 07 | rcl bl, 7
|
||||
c0 54 be 10 07 | rcl byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 d3 | rcl bl, cl
|
||||
d2 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 d5 07 | rcl r13b, 7
|
||||
41 c0 d5 00 | rcl r13b, 0
|
||||
66 d1 d3 | rcl bx, 1
|
||||
66 d1 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 d3 03 | rcl bx, 3
|
||||
66 c1 54 be 10 03 | rcl word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 d3 07 | rcl bx, 7
|
||||
66 c1 54 be 10 07 | rcl word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 d3 | rcl bx, cl
|
||||
66 d3 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 d5 0f | rcl r13w, 15
|
||||
66 41 c1 d5 00 | rcl r13w, 0
|
||||
d1 d3 | rcl ebx, 1
|
||||
d1 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 d3 03 | rcl ebx, 3
|
||||
c1 54 be 10 03 | rcl dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 d3 07 | rcl ebx, 7
|
||||
c1 54 be 10 07 | rcl dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 d3 | rcl ebx, cl
|
||||
d3 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 d5 1f | rcl r13d, 31
|
||||
41 c1 d5 00 | rcl r13d, 0
|
||||
48 d1 d3 | rcl rbx, 1
|
||||
48 d1 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 d3 03 | rcl rbx, 3
|
||||
48 c1 54 be 10 03 | rcl qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 d3 07 | rcl rbx, 7
|
||||
48 c1 54 be 10 07 | rcl qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 d3 | rcl rbx, cl
|
||||
48 d3 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 d5 3f | rcl r13, 63
|
||||
49 c1 d5 00 | rcl r13, 0
|
||||
d0 db | rcr bl, 1
|
||||
d0 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 db 03 | rcr bl, 3
|
||||
c0 5c be 10 03 | rcr byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 db 07 | rcr bl, 7
|
||||
c0 5c be 10 07 | rcr byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 db | rcr bl, cl
|
||||
d2 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 dd 07 | rcr r13b, 7
|
||||
41 c0 dd 00 | rcr r13b, 0
|
||||
66 d1 db | rcr bx, 1
|
||||
66 d1 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 db 03 | rcr bx, 3
|
||||
66 c1 5c be 10 03 | rcr word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 db 07 | rcr bx, 7
|
||||
66 c1 5c be 10 07 | rcr word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 db | rcr bx, cl
|
||||
66 d3 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 dd 0f | rcr r13w, 15
|
||||
66 41 c1 dd 00 | rcr r13w, 0
|
||||
d1 db | rcr ebx, 1
|
||||
d1 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 db 03 | rcr ebx, 3
|
||||
c1 5c be 10 03 | rcr dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 db 07 | rcr ebx, 7
|
||||
c1 5c be 10 07 | rcr dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 db | rcr ebx, cl
|
||||
d3 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 dd 1f | rcr r13d, 31
|
||||
41 c1 dd 00 | rcr r13d, 0
|
||||
48 d1 db | rcr rbx, 1
|
||||
48 d1 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 db 03 | rcr rbx, 3
|
||||
48 c1 5c be 10 03 | rcr qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 db 07 | rcr rbx, 7
|
||||
48 c1 5c be 10 07 | rcr qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 db | rcr rbx, cl
|
||||
48 d3 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 dd 3f | rcr r13, 63
|
||||
49 c1 dd 00 | rcr r13, 0
|
||||
d0 e3 | shl bl, 1
|
||||
d0 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 e3 03 | shl bl, 3
|
||||
@@ -953,6 +1033,68 @@ c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
|
||||
48 c7 44 be 10 5a 00 00 00 | mov qword ptr [rsi + 4*rdi + 16], 0x5a
|
||||
49 87 d9 | xchg rbx, r9
|
||||
48 87 54 be 10 | xchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
0f c0 cb | xadd bl, cl
|
||||
45 0f c0 e1 | xadd r9b, r12b
|
||||
0f c0 d0 | xadd al, dl
|
||||
0f c0 db | xadd bl, bl
|
||||
0f c0 54 be 10 | xadd byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f c0 54 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f c0 44 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], al
|
||||
66 0f c1 cb | xadd bx, cx
|
||||
66 45 0f c1 e1 | xadd r9w, r12w
|
||||
66 0f c1 d0 | xadd ax, dx
|
||||
66 0f c1 db | xadd bx, bx
|
||||
66 0f c1 54 be 10 | xadd word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f c1 54 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f c1 44 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], ax
|
||||
0f c1 cb | xadd ebx, ecx
|
||||
45 0f c1 e1 | xadd r9d, r12d
|
||||
0f c1 d0 | xadd eax, edx
|
||||
0f c1 db | xadd ebx, ebx
|
||||
0f c1 54 be 10 | xadd dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f c1 54 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f c1 44 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], eax
|
||||
48 0f c1 cb | xadd rbx, rcx
|
||||
4d 0f c1 e1 | xadd r9, r12
|
||||
48 0f c1 d0 | xadd rax, rdx
|
||||
48 0f c1 db | xadd rbx, rbx
|
||||
48 0f c1 54 be 10 | xadd qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f c1 54 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f c1 44 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rax
|
||||
0f c0 dc | xadd ah, bl
|
||||
0f c0 f1 | xadd cl, dh
|
||||
0f c0 6c be 10 | xadd byte ptr [rsi + 4*rdi + 16], ch
|
||||
0f b0 cb | cmpxchg bl, cl
|
||||
45 0f b0 e1 | cmpxchg r9b, r12b
|
||||
0f b0 d0 | cmpxchg al, dl
|
||||
0f b0 db | cmpxchg bl, bl
|
||||
0f b0 54 be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f b0 54 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f b0 44 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], al
|
||||
66 0f b1 cb | cmpxchg bx, cx
|
||||
66 45 0f b1 e1 | cmpxchg r9w, r12w
|
||||
66 0f b1 d0 | cmpxchg ax, dx
|
||||
66 0f b1 db | cmpxchg bx, bx
|
||||
66 0f b1 54 be 10 | cmpxchg word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f b1 54 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f b1 44 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], ax
|
||||
0f b1 cb | cmpxchg ebx, ecx
|
||||
45 0f b1 e1 | cmpxchg r9d, r12d
|
||||
0f b1 d0 | cmpxchg eax, edx
|
||||
0f b1 db | cmpxchg ebx, ebx
|
||||
0f b1 54 be 10 | cmpxchg dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f b1 54 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f b1 44 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], eax
|
||||
48 0f b1 cb | cmpxchg rbx, rcx
|
||||
4d 0f b1 e1 | cmpxchg r9, r12
|
||||
48 0f b1 d0 | cmpxchg rax, rdx
|
||||
48 0f b1 db | cmpxchg rbx, rbx
|
||||
48 0f b1 54 be 10 | cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f b1 54 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f b1 44 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rax
|
||||
0f b0 dc | cmpxchg ah, bl
|
||||
0f b0 f1 | cmpxchg cl, dh
|
||||
0f b0 6c be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], ch
|
||||
88 dc | mov ah, bl
|
||||
88 ea | mov dl, ch
|
||||
b7 21 | mov bh, 0x21
|
||||
@@ -972,8 +1114,16 @@ f8 | clc
|
||||
f9 | stc
|
||||
f5 | cmc
|
||||
90 | nop
|
||||
0f a2 | cpuid
|
||||
0f 1f 40 08 | nop dword ptr [rax + 8]
|
||||
f3 90 | pause
|
||||
0f ae e8 | lfence
|
||||
0f ae f0 | mfence
|
||||
0f ae f8 | sfence
|
||||
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
|
||||
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
|
||||
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
|
||||
4c 0f c3 74 be 10 | movnti qword ptr [rsi + 4*rdi + 16], r14
|
||||
41 51 | push r9
|
||||
53 | push rbx
|
||||
6a fb | push -5
|
||||
@@ -983,3 +1133,23 @@ ff 74 be 10 | push qword ptr [rsi + 4*rdi + 16]
|
||||
41 5c | pop r12
|
||||
8f 44 be 10 | pop qword ptr [rsi + 4*rdi + 16]
|
||||
c9 | leave
|
||||
91 | xchg eax, ecx
|
||||
48 92 | xchg rax, rdx
|
||||
66 93 | xchg ax, bx
|
||||
94 | xchg eax, esp
|
||||
48 95 | xchg rax, rbp
|
||||
66 96 | xchg ax, si
|
||||
97 | xchg eax, edi
|
||||
49 90 | xchg rax, r8
|
||||
66 41 91 | xchg ax, r9w
|
||||
41 92 | xchg eax, r10d
|
||||
49 93 | xchg rax, r11
|
||||
66 41 94 | xchg ax, r12w
|
||||
41 95 | xchg eax, r13d
|
||||
49 96 | xchg rax, r14
|
||||
66 41 97 | xchg ax, r15w
|
||||
66 41 90 | xchg r8w, ax
|
||||
49 90 | xchg r8, rax
|
||||
41 90 | xchg r8d, eax
|
||||
91 | xchg ecx, eax
|
||||
66 41 97 | xchg r15w, ax
|
||||
@@ -0,0 +1,376 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! XADD, CMPXCHG and the LOCK prefix (issue #198).
|
||||
//!
|
||||
//! Expected values follow the operation sections of the Intel SDM Vol. 2 for
|
||||
//! XADD, CMPXCHG and LOCK, stated here as literal results. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
//! Nothing was compared with x86 hardware.
|
||||
//!
|
||||
//! Both engines run one guest instruction at a time on one host thread, so
|
||||
//! these tests establish the single-thread results that any later guest
|
||||
//! scheduler has to preserve. They say nothing about concurrent execution.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// Two writable pages. Nothing is mapped after them unless a test says so.
|
||||
const DATA: u64 = 0x4000;
|
||||
const PAGE: u64 = 0x1000;
|
||||
const END: u64 = DATA + 2 * PAGE;
|
||||
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RDX: usize = 2;
|
||||
const RBX: usize = 3;
|
||||
const RSI: usize = 6;
|
||||
|
||||
fn image(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(DATA, 2 * PAGE as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn data(memory: &GuestMemory) -> Vec<u8> {
|
||||
let mut out = vec![0; 2 * PAGE as usize];
|
||||
memory.read_bytes(DATA, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
struct Run {
|
||||
name: &'static str,
|
||||
cpu: CpuState,
|
||||
exit: ExitReason,
|
||||
memory: GuestMemory,
|
||||
/// Instructions the DBT ran on the shared semantics.
|
||||
helpers: usize,
|
||||
}
|
||||
|
||||
/// The interpreter and the DBT, each from its own copy of `cpu` and `memory`.
|
||||
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
|
||||
let mut interpreted = memory.clone();
|
||||
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
|
||||
let mut translated = memory.clone();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut state = cpu.clone();
|
||||
let native = engine.run(&mut state, &mut translated, budget);
|
||||
[
|
||||
Run {
|
||||
name: "interpreter",
|
||||
cpu: result.final_state,
|
||||
exit: result.exit_reason,
|
||||
memory: interpreted,
|
||||
helpers: 0,
|
||||
},
|
||||
Run {
|
||||
name: "DBT",
|
||||
cpu: native.final_state,
|
||||
exit: native.exit_reason,
|
||||
memory: translated,
|
||||
helpers: engine.metrics.interpreter_fallbacks,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn flags(cf: bool, zf: bool, sf: bool, of: bool, pf: bool, af: bool) -> RFlags {
|
||||
RFlags {
|
||||
cf,
|
||||
zf,
|
||||
sf,
|
||||
of,
|
||||
pf,
|
||||
af,
|
||||
}
|
||||
}
|
||||
|
||||
fn low(bits: u32) -> u64 {
|
||||
u64::MAX >> (64 - bits)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_is_accepted_only_on_xadd_and_cmpxchg_with_a_memory_destination() {
|
||||
let accepted: &[&[u8]] = &[
|
||||
&[0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], ecx
|
||||
&[0xF0, 0x0F, 0xB1, 0x0E], // lock cmpxchg [rsi], ecx
|
||||
&[0x66, 0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], cx, in LLVM's prefix order
|
||||
&[0xF0, 0x66, 0x0F, 0xC1, 0x0E], // the same with LOCK first
|
||||
&[0x65, 0xF0, 0x0F, 0xB0, 0x0E], // lock cmpxchg gs:[rsi], cl
|
||||
&[0xF0, 0x48, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], rcx
|
||||
];
|
||||
for code in accepted {
|
||||
let lock = code.iter().position(|byte| *byte == 0xF0).unwrap();
|
||||
let mut unlocked = code.to_vec();
|
||||
unlocked.remove(lock);
|
||||
let insn = decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(insn.lock && !is_native(&insn), "{code:02X?}");
|
||||
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
|
||||
|
||||
// The accumulator matches the operand, so each exchange stores RCX.
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x2122_2324_2526_2728;
|
||||
cpu.gpr[RCX] = 0x1112_1314_1516_1718;
|
||||
cpu.gpr[RSI] = DATA + 0x40;
|
||||
let mut memory = image(code);
|
||||
memory
|
||||
.write_u64(DATA + 0x40, 0x2122_2324_2526_2728)
|
||||
.unwrap();
|
||||
let mut plain = image(&unlocked);
|
||||
plain.write_u64(DATA + 0x40, 0x2122_2324_2526_2728).unwrap();
|
||||
|
||||
// LOCK changes no result here: only the instruction is a byte longer.
|
||||
for (locked, wanted) in both(&cpu, &memory, 1).iter().zip(both(&cpu, &plain, 1)) {
|
||||
assert_eq!(locked.exit, ExitReason::StepLimitExceeded, "{code:02X?}");
|
||||
assert_eq!(locked.cpu.rip, ENTRY + code.len() as u64, "{code:02X?}");
|
||||
let mut shifted = wanted.cpu.clone();
|
||||
shifted.rip += 1;
|
||||
assert_eq!(locked.cpu, shifted, "{code:02X?} on the {}", locked.name);
|
||||
assert_eq!(data(&locked.memory), data(&wanted.memory), "{code:02X?}");
|
||||
assert_ne!(data(&locked.memory), data(&memory), "{code:02X?}");
|
||||
}
|
||||
}
|
||||
|
||||
let rejected: &[&[u8]] = &[
|
||||
&[0xF0, 0x0F, 0xC1, 0xC8], // lock xadd eax, ecx: register destination
|
||||
&[0xF0, 0x0F, 0xB1, 0xCB], // lock cmpxchg ebx, ecx: register destination
|
||||
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx: outside the locked subset
|
||||
&[0xF0, 0x87, 0x0E], // lock xchg [rsi], ecx: outside the locked subset
|
||||
&[0xF0, 0x0F, 0xC7, 0x0E], // lock cmpxchg8b [rsi]: not implemented
|
||||
&[0xF0, 0x8B, 0x06], // lock mov eax, [rsi]: never lockable
|
||||
&[0xF0, 0x90], // lock nop
|
||||
];
|
||||
for code in rejected {
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = DATA;
|
||||
let memory = image(&padded);
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert!(
|
||||
matches!(run.exit, ExitReason::IllegalInstruction(_)),
|
||||
"{code:02X?} on the {}: {:?}",
|
||||
run.name,
|
||||
run.exit
|
||||
);
|
||||
assert_eq!(run.cpu, cpu, "{code:02X?}");
|
||||
assert_eq!(data(&run.memory), data(&memory), "{code:02X?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_exchange_takes_each_branch_at_every_width() {
|
||||
// Destination [rsi] or RBX, source RCX, accumulator RAX.
|
||||
let forms: &[(&[u8], u32, bool)] = &[
|
||||
(&[0xF0, 0x0F, 0xB0, 0x0E], 8, true), // lock cmpxchg [rsi], cl
|
||||
(&[0x66, 0xF0, 0x0F, 0xB1, 0x0E], 16, true), // lock cmpxchg [rsi], cx
|
||||
(&[0xF0, 0x0F, 0xB1, 0x0E], 32, true), // lock cmpxchg [rsi], ecx
|
||||
(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E], 64, true), // lock cmpxchg [rsi], rcx
|
||||
(&[0x0F, 0xB0, 0xCB], 8, false), // cmpxchg bl, cl
|
||||
(&[0x66, 0x0F, 0xB1, 0xCB], 16, false), // cmpxchg bx, cx
|
||||
(&[0x0F, 0xB1, 0xCB], 32, false), // cmpxchg ebx, ecx
|
||||
(&[0x48, 0x0F, 0xB1, 0xCB], 64, false), // cmpxchg rbx, rcx
|
||||
];
|
||||
const ACCUMULATOR: u64 = 0x1111_2222_3333_4444;
|
||||
const SOURCE: u64 = 0xAAAA_BBBB_CCCC_DDDD;
|
||||
const ABOVE: u64 = 0x5555_6666_7777_8888;
|
||||
for &(code, bits, in_memory) in forms {
|
||||
let mask = low(bits);
|
||||
for matches in [true, false] {
|
||||
// The destination holds the accumulator's low bits, or differs in
|
||||
// bit 0, under bits the operation must not read.
|
||||
let old = (ABOVE & !mask) | ((ACCUMULATOR ^ u64::from(!matches)) & mask);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = ACCUMULATOR;
|
||||
cpu.gpr[RCX] = SOURCE;
|
||||
cpu.gpr[RBX] = old;
|
||||
cpu.gpr[RSI] = DATA + 0x80;
|
||||
// accumulator - destination is 0, or -1 when the destination is
|
||||
// one more. Start from the opposite flags so each must be written.
|
||||
let after = if matches {
|
||||
flags(false, true, false, false, true, false)
|
||||
} else {
|
||||
flags(true, false, true, false, true, true)
|
||||
};
|
||||
cpu.flags = flags(
|
||||
!after.cf, !after.zf, !after.sf, !after.of, !after.pf, !after.af,
|
||||
);
|
||||
let mut memory = image(code);
|
||||
memory.write_u64(DATA + 0x80, old).unwrap();
|
||||
|
||||
// A match stores the source. A mismatch stores the old value back
|
||||
// and loads it into the accumulator. An 8- or 16-bit register write
|
||||
// keeps the bits above it, a 32-bit one clears them, and a memory
|
||||
// write touches only its own bytes.
|
||||
let stored = if matches { SOURCE & mask } else { old & mask };
|
||||
let merged = |before: u64, value: u64| match bits {
|
||||
32 => value,
|
||||
_ => (before & !mask) | value,
|
||||
};
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.rip = ENTRY + code.len() as u64;
|
||||
wanted.flags = after;
|
||||
if !matches {
|
||||
wanted.gpr[RAX] = merged(ACCUMULATOR, old & mask);
|
||||
}
|
||||
let wanted_memory = if in_memory {
|
||||
(old & !mask) | stored
|
||||
} else {
|
||||
wanted.gpr[RBX] = merged(old, stored);
|
||||
old
|
||||
};
|
||||
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!("{code:02X?} matches={matches} on the {}", run.name);
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{what}");
|
||||
assert_eq!(run.cpu, wanted, "{what}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(DATA + 0x80).unwrap(),
|
||||
wanted_memory,
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_operands_may_be_unaligned_and_span_two_regions() {
|
||||
// No alignment is required of a locked operand (SDM Vol. 2, "LOCK"). The
|
||||
// last address straddles the data and a second writable region after it.
|
||||
let spanning = |code: &[u8]| {
|
||||
let mut memory = image(code);
|
||||
memory
|
||||
.map_region(END, PAGE as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
};
|
||||
for at in [DATA + 1, DATA + 0x33, DATA + PAGE - 3, END - 8, END - 3] {
|
||||
// lock xadd [rsi], rcx
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 0x0000_0001_0000_0003;
|
||||
cpu.gpr[RSI] = at;
|
||||
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xC1, 0x0E]);
|
||||
memory.write_u64(at, 0xFFFF_FFFF_FFFF_FFFE).unwrap();
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
|
||||
assert_eq!(run.cpu.gpr[RCX], 0xFFFF_FFFF_FFFF_FFFE, "{at:#x}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(at).unwrap(),
|
||||
0x0000_0001_0000_0001,
|
||||
"{at:#x}"
|
||||
);
|
||||
// 0xFFFF_FFFF_FFFF_FFFE + 0x0000_0001_0000_0003 carries out of bit
|
||||
// 63 and bit 3; the sum is positive, nonzero and ends in 0x01.
|
||||
assert_eq!(
|
||||
run.cpu.flags,
|
||||
flags(true, false, false, false, false, true),
|
||||
"{at:#x}"
|
||||
);
|
||||
}
|
||||
|
||||
// lock cmpxchg [rsi], rcx, with a matching accumulator
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x8877_6655_4433_2211;
|
||||
cpu.gpr[RCX] = 0x0102_0304_0506_0708;
|
||||
cpu.gpr[RSI] = at;
|
||||
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E]);
|
||||
memory.write_u64(at, 0x8877_6655_4433_2211).unwrap();
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
|
||||
assert_eq!(run.cpu.gpr[RAX], 0x8877_6655_4433_2211, "{at:#x}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(at).unwrap(),
|
||||
0x0102_0304_0506_0708,
|
||||
"{at:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_on_any_byte_of_the_operand_changes_nothing() {
|
||||
let xadd: &[u8] = &[0xF0, 0x48, 0x0F, 0xC1, 0x0E]; // lock xadd [rsi], rcx
|
||||
let cmpxchg: &[u8] = &[0xF0, 0x48, 0x0F, 0xB1, 0x0E]; // lock cmpxchg [rsi], rcx
|
||||
// The last three bytes of writable memory, then five bytes that are
|
||||
// unmapped or read-only.
|
||||
let at = END - 3;
|
||||
for code in [xadd, cmpxchg] {
|
||||
for read_only_tail in [false, true] {
|
||||
// Accumulators that match and that do not match the operand's
|
||||
// writable bytes: a failed compare needs the write access too.
|
||||
for accumulator in [0x0000_0000_00CC_BBAA_u64, 7] {
|
||||
let mut memory = image(code);
|
||||
memory.write_bytes(at, &[0xAA, 0xBB, 0xCC]).unwrap();
|
||||
if read_only_tail {
|
||||
memory
|
||||
.map_region(END, PAGE as usize, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
}
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = accumulator;
|
||||
cpu.gpr[RCX] = 0x1122_3344_5566_7788;
|
||||
cpu.gpr[RSI] = at;
|
||||
cpu.flags = flags(true, false, true, false, true, false);
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!(
|
||||
"{code:02X?} tail read-only={read_only_tail} rax={accumulator:#x} on the {}",
|
||||
run.name
|
||||
);
|
||||
assert!(
|
||||
matches!(run.exit, ExitReason::MemoryFault(_)),
|
||||
"{what}: {:?}",
|
||||
run.exit
|
||||
);
|
||||
assert_eq!(run.cpu, cpu, "{what}");
|
||||
assert_eq!(data(&run.memory), data(&memory), "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_swap_loop_retries_then_fetch_and_add_follows() {
|
||||
// retry: lea rcx, [rax + 1]
|
||||
// lock cmpxchg [rsi], rcx
|
||||
// jne retry
|
||||
// mov edx, 5
|
||||
// lock xadd [rsi], rdx
|
||||
// hlt
|
||||
let code = [
|
||||
0x48, 0x8D, 0x48, 0x01, 0xF0, 0x48, 0x0F, 0xB1, 0x0E, 0x75, 0xF5, 0xBA, 0x05, 0x00, 0x00,
|
||||
0x00, 0xF0, 0x48, 0x0F, 0xC1, 0x16, 0xF4,
|
||||
];
|
||||
const COUNTER: u64 = DATA + 0x100;
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
// A stale expectation: the first exchange fails and reloads RAX, the
|
||||
// second succeeds.
|
||||
cpu.gpr[RAX] = 0xDEAD;
|
||||
cpu.gpr[RSI] = COUNTER;
|
||||
let mut memory = image(&code);
|
||||
memory.write_u64(COUNTER, 41).unwrap();
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
assert_eq!(run.exit, ExitReason::Halt, "{}", run.name);
|
||||
assert_eq!(run.cpu.gpr[RAX], 41, "{}", run.name);
|
||||
assert_eq!(run.cpu.gpr[RCX], 42, "{}", run.name);
|
||||
// XADD returns the value before its addition.
|
||||
assert_eq!(run.cpu.gpr[RDX], 42, "{}", run.name);
|
||||
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 47, "{}", run.name);
|
||||
assert_eq!(run.cpu.rip, ENTRY + code.len() as u64, "{}", run.name);
|
||||
// Two exchanges and one addition, none lowered to ARM64 yet.
|
||||
if run.name == "DBT" {
|
||||
assert_eq!(run.helpers, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,8 @@ enum Outcome {
|
||||
}
|
||||
|
||||
fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
// LOCK changes no result on a machine that runs one instruction at a time.
|
||||
let text = text.strip_prefix("lock ").unwrap_or(text);
|
||||
let (name, rest) = text.split_once(' ').unwrap_or((text, ""));
|
||||
let places: Vec<Place> = if rest.is_empty() || name == "lea" || name == "nop" {
|
||||
Vec::new()
|
||||
@@ -395,7 +397,7 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
write(m, places[0], (1u128 << bits) - 1 - a);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"shl" | "shr" | "sar" | "rol" | "ror" => {
|
||||
"shl" | "shr" | "sar" | "rol" | "ror" | "rcl" | "rcr" => {
|
||||
let count = match rest.split(", ").nth(1) {
|
||||
Some("cl") => u32::from(m.gpr[1] as u8),
|
||||
_ => read(m, places[1], 8) as u32,
|
||||
@@ -403,13 +405,22 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
let start = read(m, places[0], bits);
|
||||
let mut value = start;
|
||||
let top = 1u128 << (bits - 1);
|
||||
let mut carry = m.flags.cf;
|
||||
for _ in 0..count {
|
||||
let carry_in = m.flags.cf;
|
||||
let mut carry = carry_in;
|
||||
// RCL and RCR rotate through CF, so `bits + 1` steps come round again.
|
||||
let steps = if matches!(name, "rcl" | "rcr") {
|
||||
count % (bits + 1)
|
||||
} else {
|
||||
count
|
||||
};
|
||||
for _ in 0..steps {
|
||||
// One step at a time, as the SDM loop does.
|
||||
let (high, low) = (bit(value, bits - 1), bit(value, 0));
|
||||
(value, carry) = match name {
|
||||
"shl" => (truncate(value * 2, bits), high),
|
||||
"rol" => (truncate(value * 2, bits) + u128::from(high), high),
|
||||
"rcl" => (truncate(value * 2, bits) + u128::from(carry), high),
|
||||
"rcr" => (value / 2 + if carry { top } else { 0 }, low),
|
||||
"shr" => (value / 2, low),
|
||||
"sar" => (value / 2 + if high { top } else { 0 }, low),
|
||||
_ => (value / 2 + if low { top } else { 0 }, low),
|
||||
@@ -422,7 +433,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
let (msb, next) = (bit(value, bits - 1), bit(value, bits - 2));
|
||||
if count == 1 {
|
||||
m.flags.of = match name {
|
||||
"shl" | "rol" => msb != carry,
|
||||
"shl" | "rol" | "rcl" => msb != carry,
|
||||
"rcr" => bit(start, bits - 1) != carry_in,
|
||||
"shr" => bit(start, bits - 1),
|
||||
"sar" => false,
|
||||
_ => msb != next,
|
||||
@@ -625,7 +637,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
..none
|
||||
})
|
||||
}
|
||||
"mov" | "movabs" => {
|
||||
// MOVNTI stores like MOV; the non-temporal hint changes no result.
|
||||
"mov" | "movabs" | "movnti" => {
|
||||
let value = read(m, places[1], bits);
|
||||
write(m, places[0], value);
|
||||
Outcome::Done(none)
|
||||
@@ -659,6 +672,28 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
write(m, places[1], a);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"xadd" => {
|
||||
// TEMP := SRC + DEST; SRC := DEST; DEST := TEMP.
|
||||
let (a, b) = (read(m, places[0], bits), read(m, places[1], bits));
|
||||
let sum = arithmetic(m, a, b, false, false, bits);
|
||||
write(m, places[1], a);
|
||||
write(m, places[0], sum);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"cmpxchg" => {
|
||||
// The accumulator is compared with DEST as CMP would. On a match
|
||||
// DEST := SRC; otherwise accumulator := DEST and DEST := DEST.
|
||||
let accumulator = read(m, rax(bits), bits);
|
||||
let (destination, source) = (read(m, places[0], bits), read(m, places[1], bits));
|
||||
arithmetic(m, accumulator, destination, true, false, bits);
|
||||
if accumulator == destination {
|
||||
write(m, places[0], source);
|
||||
} else {
|
||||
write(m, rax(bits), destination);
|
||||
write(m, places[0], destination);
|
||||
}
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"bswap" => {
|
||||
let value = read(m, places[0], bits);
|
||||
let bytes = bits / 8;
|
||||
@@ -704,7 +739,26 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
m.flags.cf = !m.flags.cf;
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"nop" | "pause" => Outcome::Done(none),
|
||||
// The fences order memory accesses and compute nothing.
|
||||
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
|
||||
"cpuid" => {
|
||||
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
|
||||
// and the four features whose every instruction exists, CMOV and
|
||||
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
|
||||
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
|
||||
let values = match m.gpr[RAX] as u32 {
|
||||
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
|
||||
1 => [0, 0, 1 << 23, 1 << 15],
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
|
||||
_ => [0; 4],
|
||||
};
|
||||
// EAX, EBX, ECX and EDX, each zero-extended.
|
||||
for (index, value) in [0, 3, 1, 2].into_iter().zip(values) {
|
||||
m.gpr[index] = u64::from(value);
|
||||
}
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"push" => {
|
||||
m.pushed = read(m, places[0], 64) as u64;
|
||||
m.gpr[4] -= 8;
|
||||
@@ -935,7 +989,9 @@ fn every_declared_form_is_executed_by_a_fixture() {
|
||||
.unwrap_or_else(|error| panic!("{line}: {error:?}"));
|
||||
seen.insert(usize::from(insn.form));
|
||||
}
|
||||
// Control flow and exits are covered by the tests below.
|
||||
// Control flow and exits are covered by the tests below. String
|
||||
// instructions and the direction flag need their own memory layout and
|
||||
// are covered form by form in `tests/cpu_rep.rs`.
|
||||
let separate = [
|
||||
Op::Ldmxcsr,
|
||||
Op::Jcc,
|
||||
@@ -944,6 +1000,10 @@ fn every_declared_form_is_executed_by_a_fixture() {
|
||||
Op::Ret,
|
||||
Op::Hlt,
|
||||
Op::Syscall,
|
||||
Op::Movs,
|
||||
Op::Stos,
|
||||
Op::Cld,
|
||||
Op::Std,
|
||||
];
|
||||
let mut missing: BTreeMap<&str, Vec<String>> = BTreeMap::new();
|
||||
for (index, form) in FORMS.iter().enumerate() {
|
||||
@@ -1166,17 +1226,21 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
|
||||
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx
|
||||
&[0xF2, 0x90], // repne nop
|
||||
&[0xF3, 0xC3], // rep ret
|
||||
&[0xF3, 0xA4], // rep movsb
|
||||
&[0xF2, 0xA4], // repne movsb
|
||||
&[0xF3, 0xA6], // repe cmpsb
|
||||
&[0x67, 0x8B, 0x06], // address-size override
|
||||
&[0x64, 0x2E, 0x8B, 0x06], // CS after FS
|
||||
&[0x66, 0x50], // push ax
|
||||
&[0x66, 0xE8, 0, 0], // call rel16
|
||||
&[0x66, 0x0F, 0xC9], // bswap cx (undefined)
|
||||
&[0x66, 0x63, 0xC1], // 16-bit movsxd
|
||||
&[0x41, 0x90], // xchg r8, rax
|
||||
&[0xF3, 0x41, 0x90], // F3 on xchg r8, rax
|
||||
&[0x8D, 0xC0], // lea with a register operand
|
||||
&[0x0F, 0xAE, 0x2E], // 0F AE /5 with a memory operand
|
||||
&[0x0F, 0xAE, 0x36], // 0F AE /6 with a memory operand
|
||||
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
|
||||
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
|
||||
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
|
||||
&[0xC0, 0xD0, 0x01], // rcl al, 1
|
||||
&[0xC6, 0xC8, 0x01], // C6 /1
|
||||
&[0xFF, 0xF8], // FF /7
|
||||
&[0xFE, 0xD0], // FE /2
|
||||
@@ -1298,6 +1362,107 @@ fn division_accepts_exactly_the_representable_quotients() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit scans and the bit test keep the destination and the flags where
|
||||
/// the architecture puts them.
|
||||
///
|
||||
/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT":
|
||||
/// BSF writes the index of the lowest set bit of the source and BSR the index
|
||||
/// of the highest set bit, and both set the zero flag when the source is
|
||||
/// zero, in which case the destination is undefined and keeps its value. BT
|
||||
/// sets the carry flag from the tested bit, leaves the other flags alone and
|
||||
/// masks the bit index to the operand width.
|
||||
///
|
||||
/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD
|
||||
/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9),
|
||||
/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w`
|
||||
/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM
|
||||
/// 23.1.6 `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn bit_scans_and_bit_tests_follow_the_architecture() {
|
||||
const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9
|
||||
const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9
|
||||
const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9
|
||||
const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d
|
||||
const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d
|
||||
const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d
|
||||
const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w
|
||||
const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w
|
||||
|
||||
/// A machine with R9 and RBX set and every other register zero.
|
||||
fn machine(source: u64, destination: u64) -> Machine {
|
||||
let mut gpr = [0; 16];
|
||||
gpr[3] = destination;
|
||||
gpr[9] = source;
|
||||
Machine {
|
||||
gpr,
|
||||
flags: Flags::default(),
|
||||
operand: 0,
|
||||
pushed: 0,
|
||||
top: STACK_TOP,
|
||||
}
|
||||
}
|
||||
|
||||
// The lowest set bit of the source is the index BSF writes.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// The highest set bit of the source is the index BSR writes.
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 63);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// A zero source sets the zero flag and leaves the destination alone.
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
|
||||
// A 32-bit destination holds a 32-bit index and clears the half above it.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1);
|
||||
assert_eq!(state.gpr[3], 31);
|
||||
|
||||
// A 16-bit destination keeps the bits above it.
|
||||
let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008);
|
||||
|
||||
// BT reports the tested bit in the carry flag and leaves the bit string
|
||||
// alone.
|
||||
let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1);
|
||||
assert!(!state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
|
||||
// The bit index is masked to the operand width, so 64 selects bit 0 of a
|
||||
// 64-bit bit string and 32 selects bit 0 of a 32-bit one.
|
||||
let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1);
|
||||
assert!(state.flags.cf);
|
||||
|
||||
// The bit scans and the register form of the bit test are lowered to
|
||||
// ARM64 instead of falling back to the shared semantics.
|
||||
for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] {
|
||||
let insn = decode(ENTRY, |address| {
|
||||
code.get((address - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.expect("decode");
|
||||
assert!(is_native(&insn), "{code:02X?} is not native");
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let (mut cpu, mut memory) = load(&machine(0x28, 0), code);
|
||||
engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() {
|
||||
let machine = Random(17).machine();
|
||||
|
||||
@@ -10,6 +10,12 @@
|
||||
# decodable; a form counts as implemented only once its operation has semantics
|
||||
# and independent tests. Forms not listed here are rejected.
|
||||
#
|
||||
# enc = "string" is a string instruction: its source is [RSI], which FS or GS
|
||||
# may override, its destination is [RDI], and it accepts the REP prefix (F3).
|
||||
#
|
||||
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
|
||||
# Every other use of LOCK is rejected, as the architecture's #UD.
|
||||
#
|
||||
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
|
||||
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
|
||||
# A 16-byte memory operand must be aligned unless unaligned = true.
|
||||
@@ -48,11 +54,15 @@ movsx = { ref = "sdm MOVSX/MOVSXD" }
|
||||
movsxd = { ref = "sdm MOVSX/MOVSXD" }
|
||||
lea = { ref = "sdm LEA" }
|
||||
xchg = { ref = "sdm XCHG" }
|
||||
xadd = { writes = "cf zf sf of pf af", ref = "sdm XADD" }
|
||||
cmpxchg = { writes = "cf zf sf of pf af", ref = "sdm CMPXCHG" }
|
||||
bswap = { ref = "sdm BSWAP" }
|
||||
cwde = { ref = "sdm CBW/CWDE/CDQE" }
|
||||
cdq = { ref = "sdm CWD/CDQ/CQO" }
|
||||
rol = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
ror = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
rcl = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
rcr = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
shl = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
shr = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
sar = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
@@ -85,6 +95,12 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
|
||||
clc = { writes = "cf", ref = "sdm CLC" }
|
||||
stc = { writes = "cf", ref = "sdm STC" }
|
||||
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
|
||||
cpuid = { ref = "sdm CPUID" }
|
||||
cld = { ref = "sdm CLD" }
|
||||
std = { ref = "sdm STD" }
|
||||
# A REP form repeats by leaving RIP on itself, so these end a translated block.
|
||||
movs = { terminator = true, ref = "sdm MOVS/MOVSB/MOVSW/MOVSD/MOVSQ" }
|
||||
stos = { terminator = true, ref = "sdm STOS/STOSB/STOSW/STOSD/STOSQ" }
|
||||
|
||||
# SSE and SSE2 moves and packed integer operations. None reads or writes RFLAGS.
|
||||
movaps = { ref = "sdm MOVAPS" }
|
||||
@@ -92,6 +108,7 @@ movups = { ref = "sdm MOVUPS" }
|
||||
movdqa = { ref = "sdm MOVDQA" }
|
||||
movdqu = { ref = "sdm MOVDQU" }
|
||||
movntdq = { ref = "sdm MOVNTDQ" }
|
||||
movnti = { ref = "sdm MOVNTI" }
|
||||
movntps = { ref = "sdm MOVNTPS/MOVNTPD" }
|
||||
movss = { ref = "sdm MOVSS" }
|
||||
movsd = { ref = "sdm MOVSD (scalar double)" }
|
||||
@@ -169,6 +186,9 @@ shufpd = { ref = "sdm SHUFPD" }
|
||||
pinsrw = { ref = "sdm PINSRW" }
|
||||
pextrw = { ref = "sdm PEXTRW" }
|
||||
ldmxcsr = { ref = "sdm LDMXCSR" }
|
||||
lfence = { ref = "sdm LFENCE" }
|
||||
mfence = { ref = "sdm MFENCE" }
|
||||
sfence = { ref = "sdm SFENCE" }
|
||||
stmxcsr = { ref = "sdm STMXCSR" }
|
||||
|
||||
# Floating point. Every form can raise a SIMD floating-point exception.
|
||||
@@ -387,6 +407,51 @@ opcode = 0x87
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
|
||||
# The accumulator with the register in the opcode. Opcode 0x90 is NOP; with
|
||||
# REX.B the decoder reads it as 0x91 with register 0, which is then r8. A row
|
||||
# of eight would have to start at 0x90, so each opcode is its own form.
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x91
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x92
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x93
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x94
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x95
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x96
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x97
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "mov"
|
||||
opcode = 0x88
|
||||
@@ -562,6 +627,49 @@ opcode = 0x05
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "cpuid"
|
||||
map = "0f"
|
||||
opcode = 0xA2
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "movs"
|
||||
opcode = 0xA4
|
||||
enc = "string"
|
||||
size = "b"
|
||||
|
||||
[[form]]
|
||||
op = "movs"
|
||||
opcode = 0xA5
|
||||
enc = "string"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "stos"
|
||||
opcode = 0xAA
|
||||
enc = "string"
|
||||
size = "b"
|
||||
|
||||
[[form]]
|
||||
op = "stos"
|
||||
opcode = 0xAB
|
||||
enc = "string"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "cld"
|
||||
opcode = 0xFC
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "std"
|
||||
opcode = 0xFD
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "movzx"
|
||||
map = "0f"
|
||||
@@ -674,6 +782,38 @@ enc = "rm_reg"
|
||||
size = "v"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "cmpxchg"
|
||||
map = "0f"
|
||||
opcode = 0xB0
|
||||
enc = "rm_reg"
|
||||
size = "b"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "cmpxchg"
|
||||
map = "0f"
|
||||
opcode = 0xB1
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "xadd"
|
||||
map = "0f"
|
||||
opcode = 0xC0
|
||||
enc = "rm_reg"
|
||||
size = "b"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "xadd"
|
||||
map = "0f"
|
||||
opcode = 0xC1
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
lock = true
|
||||
|
||||
# Groups whose digits select an operation: [opcode, size, immediate, encoding].
|
||||
[[group]]
|
||||
map = "0f"
|
||||
@@ -690,7 +830,7 @@ digits = { 0 = "inc", 1 = "dec" }
|
||||
|
||||
[[group]]
|
||||
opcodes = [[0xC0, "b", "ib", "rm_imm"], [0xC1, "v", "ib", "rm_imm"], [0xD0, "b", "", "rm_one"], [0xD1, "v", "", "rm_one"], [0xD2, "b", "", "rm_cl"], [0xD3, "v", "", "rm_cl"]]
|
||||
digits = { 0 = "rol", 1 = "ror", 4 = "shl", 5 = "shr", 7 = "sar" }
|
||||
digits = { 0 = "rol", 1 = "ror", 2 = "rcl", 3 = "rcr", 4 = "shl", 5 = "shr", 7 = "sar" }
|
||||
|
||||
# SSE and SSE2 moves and packed integer forms.
|
||||
|
||||
@@ -814,6 +954,14 @@ size = "x"
|
||||
src = "x"
|
||||
memory_only = true
|
||||
|
||||
[[form]]
|
||||
op = "movnti"
|
||||
map = "0f"
|
||||
opcode = 0xC3
|
||||
enc = "rm_reg"
|
||||
size = "y"
|
||||
memory_only = true
|
||||
|
||||
[[form]]
|
||||
op = "movntps"
|
||||
map = "0f"
|
||||
@@ -1831,6 +1979,36 @@ size = "n"
|
||||
src = "d"
|
||||
memory_only = true
|
||||
|
||||
# The fences are the register forms of digits 5 to 7; the r/m field is ignored.
|
||||
# The memory forms of those digits (the XSAVE family and CLFLUSH) are not
|
||||
# declared.
|
||||
[[form]]
|
||||
op = "lfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 5
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "mfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 6
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "sfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 7
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
# SSE and SSE2 floating-point forms. RCP and RSQRT approximations are not
|
||||
# architecturally exact and are left out.
|
||||
|
||||
|
||||
@@ -101,7 +101,43 @@ impl NativeCompute {
|
||||
colors,
|
||||
[width, height],
|
||||
clear,
|
||||
sampled,
|
||||
sampled.map(|(texture, sampler)| (texture.raw(), sampler)),
|
||||
)
|
||||
.map(|(pixels, _)| pixels)
|
||||
}
|
||||
|
||||
/// As [`Self::render_rgba8_sampled`], with level 0 of a BC1 upload bound
|
||||
/// natively as a `BC1_RGBA` texture to fragment texture slot 0 and the
|
||||
/// sampler to fragment sampler slot 0.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`Self::render_rgba8_sampled`], and for an invalid BC1 level.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn render_rgba8_sampled_bc1(
|
||||
&self,
|
||||
source: &str,
|
||||
entries: [&str; 2],
|
||||
vertices: &[[f32; 4]; 3],
|
||||
colors: &[[f32; 4]; 3],
|
||||
extent: [usize; 2],
|
||||
clear: [u8; 4],
|
||||
texture: &Bc1Upload<'_>,
|
||||
sampler: &crate::sampler::MetalSampler,
|
||||
) -> Result<Vec<u8>, MetalError> {
|
||||
let level = texture
|
||||
.subresource(0, 0)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
self.validate_bc_extent(level.width, level.height, "BC1")?;
|
||||
let bc1 = self.new_bc1_texture(&level)?;
|
||||
self.render_rgba8_internal(
|
||||
source,
|
||||
entries,
|
||||
vertices,
|
||||
colors,
|
||||
extent,
|
||||
clear,
|
||||
Some((&bc1, sampler)),
|
||||
)
|
||||
.map(|(pixels, _)| pixels)
|
||||
}
|
||||
@@ -116,7 +152,7 @@ impl NativeCompute {
|
||||
[width, height]: [usize; 2],
|
||||
clear: [u8; 4],
|
||||
sampled: Option<(
|
||||
&crate::texture_pipeline::MetalRgba8Texture,
|
||||
&ProtocolObject<dyn MTLTexture>,
|
||||
&crate::sampler::MetalSampler,
|
||||
)>,
|
||||
) -> Result<(Vec<u8>, Option<f64>), MetalError> {
|
||||
@@ -228,7 +264,7 @@ impl NativeCompute {
|
||||
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
|
||||
encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1);
|
||||
if let Some((tex, samp)) = sampled {
|
||||
encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0);
|
||||
encoder.setFragmentTexture_atIndex(Some(tex), 0);
|
||||
encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0);
|
||||
}
|
||||
encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3);
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
use xenora_texture::{Bc1Upload, Bc1UploadDesc, SamplerDesc, decode_bc1};
|
||||
|
||||
use super::{context, native};
|
||||
|
||||
/// The translated `image_sample_lz` pixel stage samples a native BC1
|
||||
/// texture bound by `render_rgba8_sampled_bc1`. Each of the 8×8 texture's
|
||||
/// four blocks selects only its two endpoints, which expand exactly to 0 or
|
||||
/// 255, so the image is known without a decoder: selector 1 (the second
|
||||
/// endpoint) where `x == 0 || y == 3` within a block, else selector 0.
|
||||
#[test]
|
||||
fn translated_image_sample_lz_reads_bound_bc1_texture() {
|
||||
let blocks: [[u8; 8]; 4] = [
|
||||
[0x00, 0xF8, 0x1F, 0x00, 0x01, 0x01, 0x01, 0x55], // red, blue
|
||||
[0xE0, 0x07, 0x00, 0x00, 0x01, 0x01, 0x01, 0x55], // green, black
|
||||
[0xFF, 0xFF, 0x1F, 0xF8, 0x01, 0x01, 0x01, 0x55], // white, magenta
|
||||
[0xE0, 0xFF, 0xFF, 0x07, 0x01, 0x01, 0x01, 0x55], // yellow, cyan
|
||||
];
|
||||
let endpoints: [[[u8; 4]; 2]; 4] = [
|
||||
[[255, 0, 0, 255], [0, 0, 255, 255]],
|
||||
[[0, 255, 0, 255], [0, 0, 0, 255]],
|
||||
[[255, 255, 255, 255], [255, 0, 255, 255]],
|
||||
[[255, 255, 0, 255], [0, 255, 255, 255]],
|
||||
];
|
||||
let mut expected = Vec::new();
|
||||
for y in 0..8 {
|
||||
for x in 0..8 {
|
||||
let selector = usize::from(x % 4 == 0 || y % 4 == 3);
|
||||
expected.extend(endpoints[(y / 4) * 2 + x / 4][selector]);
|
||||
}
|
||||
}
|
||||
for (index, block) in blocks.into_iter().enumerate() {
|
||||
let (bx, by) = (index % 2 * 4, index / 2 * 4);
|
||||
for (i, texel) in decode_bc1(block).iter().enumerate() {
|
||||
let at = ((by + i / 4) * 8 + bx + i % 4) * 4;
|
||||
assert_eq!(texel, &expected[at..at + 4], "decoder, block {index}");
|
||||
}
|
||||
}
|
||||
|
||||
let ps: Vec<u8> = [
|
||||
&[0x00, 0x00, 0x08, 0xc8][..], // v_interp_p1_f32 v2, v0, attr0.x
|
||||
&[0x01, 0x00, 0x09, 0xc8], // v_interp_p2_f32 v2, v1, attr0.x
|
||||
&[0x00, 0x01, 0x0c, 0xc8], // v_interp_p1_f32 v3, v0, attr0.y
|
||||
&[0x01, 0x01, 0x0d, 0xc8], // v_interp_p2_f32 v3, v1, attr0.y
|
||||
&[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00], // image_sample_lz
|
||||
&[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07], // exp mrt0
|
||||
&[0x00, 0x00, 0x81, 0xbf], // s_endpgm
|
||||
]
|
||||
.concat();
|
||||
let compiled = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"),
|
||||
&ps,
|
||||
)
|
||||
.expect("compile translated image_sample_lz shader");
|
||||
let gpu = context();
|
||||
let upload = Bc1Upload::new(
|
||||
blocks.as_flattened(),
|
||||
Bc1UploadDesc {
|
||||
width: 8,
|
||||
height: 8,
|
||||
mips: 1,
|
||||
layers: 1,
|
||||
format: 1,
|
||||
usage: 1,
|
||||
row_pitch: 16,
|
||||
slice_pitch: 32,
|
||||
},
|
||||
)
|
||||
.expect("valid BC1 upload");
|
||||
let sampler = native(xenora_metal::sampler::MetalSampler::new(
|
||||
gpu.device(),
|
||||
SamplerDesc::nearest_clamp(),
|
||||
));
|
||||
// Pixel (x, y) of the 8×8 target samples uv ((x + 0.5) / 8, (y + 0.5) / 8).
|
||||
let positions = [
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
];
|
||||
let uvs = [
|
||||
[0.0, 1.0, 0.0, 1.0],
|
||||
[2.0, 1.0, 0.0, 1.0],
|
||||
[0.0, -1.0, 0.0, 1.0],
|
||||
];
|
||||
let pixels = native(gpu.render_rgba8_sampled_bc1(
|
||||
&compiled.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&positions,
|
||||
&uvs,
|
||||
[8, 8],
|
||||
[19, 43, 93, 251],
|
||||
&upload,
|
||||
&sampler,
|
||||
));
|
||||
assert_eq!(pixels, expected);
|
||||
}
|
||||
@@ -26,6 +26,8 @@ mod texture_bc_alpha;
|
||||
mod texture_bc_channel;
|
||||
#[path = "native/texture_sampling.rs"]
|
||||
mod texture_sampling;
|
||||
#[path = "native/translated_bc1.rs"]
|
||||
mod translated_bc1;
|
||||
#[path = "native/translated_render.rs"]
|
||||
mod translated_render;
|
||||
|
||||
|
||||
+219
-14
@@ -57,6 +57,8 @@ pub enum Op {
|
||||
MoveScalar(u8, u8),
|
||||
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
|
||||
Compare(Comparison, CompareSource, u8),
|
||||
/// VOP3A integer compare writing a Wave32 mask to SDST.
|
||||
CompareVop3(u8, Comparison, CompareSource, u8),
|
||||
/// VOPC 16- or 64-bit integer compare writing the Wave32 mask to
|
||||
/// `vcc_lo`. For 64-bit forms a `Vector` or `Scalar` source and VSRC1 name
|
||||
/// the low register of a pair.
|
||||
@@ -68,13 +70,15 @@ pub enum Op {
|
||||
/// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing
|
||||
/// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11.
|
||||
ScalarCompare(Comparison, Source, Source),
|
||||
/// SOPK operation on SGPR `SDST` (s0-s105) and the raw SIMM16.
|
||||
ScalarImmediate(ScalarImmediate, u8, u16),
|
||||
Branch {
|
||||
target: usize,
|
||||
condition: BranchCondition,
|
||||
},
|
||||
Vector(VectorAlu, u8, u8, u8),
|
||||
/// VOP2 32-bit integer form: VDST, SRC0 (VGPR, SGPR, `vcc_lo`, inline
|
||||
/// integer or literal) and VSRC1. Writes neither VCC nor SCC.
|
||||
/// integer or literal) and VSRC1, with implicit VCC for select/carry forms.
|
||||
VectorInteger(VectorInteger, u8, CompareSource, u8),
|
||||
/// VOP1 32-bit integer or bit form: VDST and SRC0 (VGPR, SGPR, `vcc_lo`,
|
||||
/// inline integer or literal). Writes neither VCC nor SCC.
|
||||
@@ -185,6 +189,8 @@ pub enum BranchCondition {
|
||||
SccZero,
|
||||
/// Take the branch when the low half of VCC is clear.
|
||||
VccZero,
|
||||
/// Take the branch when the low half of VCC is nonzero.
|
||||
VccNonzero,
|
||||
/// Take the branch when the low half of EXEC is clear.
|
||||
ExecZero,
|
||||
}
|
||||
@@ -281,6 +287,23 @@ pub enum ScalarUnary {
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// SOPK operations decoded by the reference interpreter (RDNA 2 ISA guide
|
||||
/// 12.2; SCC per Tables 11, 12, 13 and 14).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarImmediate {
|
||||
/// 0 `s_movk_i32`: D = signext(SIMM16).
|
||||
Move,
|
||||
/// 2 `s_cmovk_i32`: if SCC, D = signext(SIMM16); SCC unchanged.
|
||||
ConditionalMove,
|
||||
/// 3-14 `s_cmpk_*`: SCC = (D <relation> K), K = signext(SIMM16) for the
|
||||
/// signed forms 3-8 and SIMM16 zero-extended for the unsigned 9-14.
|
||||
Compare(Comparison),
|
||||
/// 15 `s_addk_i32`: D = D + signext(SIMM16), SCC = signed overflow.
|
||||
Add,
|
||||
/// 16 `s_mulk_i32`: D = low 32 bits of D * signext(SIMM16); SCC unchanged.
|
||||
Multiply,
|
||||
}
|
||||
|
||||
/// VOP2 operations decoded by the reference interpreter.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorAlu {
|
||||
@@ -298,6 +321,12 @@ pub enum VectorAlu {
|
||||
/// section 12.7). None has a carry-in or carry-out.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorInteger {
|
||||
/// 1: select S1 when the lane's VCC bit is set.
|
||||
Select,
|
||||
/// 40: unsigned add with carry input and output.
|
||||
AddCarry,
|
||||
/// 41 / 42: unsigned subtract with borrow input and output.
|
||||
SubtractBorrow { reversed: bool },
|
||||
/// 9 / 11: D = low 32 bits of S0[23:0] * S1[23:0], sign-extended from
|
||||
/// bit 23 when `signed`.
|
||||
Multiply24 { signed: bool },
|
||||
@@ -321,6 +350,11 @@ impl VectorInteger {
|
||||
/// Opcode bits 30-25 of the VOP2 word.
|
||||
fn from_opcode(opcode: u8) -> Option<Self> {
|
||||
Some(match opcode {
|
||||
1 => Self::Select,
|
||||
40 => Self::AddCarry,
|
||||
41 | 42 => Self::SubtractBorrow {
|
||||
reversed: opcode == 42,
|
||||
},
|
||||
9 => Self::Multiply24 { signed: true },
|
||||
10 => Self::MultiplyHigh24 { signed: true },
|
||||
11 => Self::Multiply24 { signed: false },
|
||||
@@ -337,6 +371,34 @@ impl VectorInteger {
|
||||
})
|
||||
}
|
||||
|
||||
fn reads_vcc(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Select | Self::AddCarry | Self::SubtractBorrow { .. }
|
||||
)
|
||||
}
|
||||
|
||||
fn writes_vcc(self) -> bool {
|
||||
matches!(self, Self::AddCarry | Self::SubtractBorrow { .. })
|
||||
}
|
||||
|
||||
// Guide 12.7: carry/borrow is determined from the exact mathematical result.
|
||||
fn apply_vcc(self, a: u32, b: u32, bit: u32) -> (u32, bool) {
|
||||
match self {
|
||||
Self::Select => (if bit == 0 { a } else { b }, false),
|
||||
Self::AddCarry => {
|
||||
let exact = u64::from(a) + u64::from(b) + u64::from(bit);
|
||||
(exact as u32, exact > u64::from(u32::MAX))
|
||||
}
|
||||
Self::SubtractBorrow { reversed } => {
|
||||
let (minuend, subtrahend) = if reversed { (b, a) } else { (a, b) };
|
||||
let exact = i64::from(minuend) - i64::from(subtrahend) - i64::from(bit);
|
||||
(exact as u32, exact < 0)
|
||||
}
|
||||
_ => unreachable!("VOP2 operation does not read VCC"),
|
||||
}
|
||||
}
|
||||
|
||||
/// D for S0 = `a`, S1 = `b`, from exact i64 arithmetic reduced modulo 2^32.
|
||||
fn apply(self, a: u32, b: u32) -> u32 {
|
||||
let field = |bits: u32, signed: bool| {
|
||||
@@ -374,6 +436,9 @@ impl VectorInteger {
|
||||
Self::Add => a.wrapping_add(b),
|
||||
Self::Subtract => a.wrapping_sub(b),
|
||||
Self::SubtractReverse => b.wrapping_sub(a),
|
||||
Self::Select | Self::AddCarry | Self::SubtractBorrow { .. } => {
|
||||
unreachable!("VOP2 operation requires VCC")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -589,6 +654,26 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
};
|
||||
(op, left_length.max(right_length))
|
||||
}
|
||||
// SOPK (guide 13.1.2): ENCODING 0b1011 in bits 28-31, OP 23-27,
|
||||
// SDST 16-22 (s0-s105 only), SIMM16 0-15. The format never takes
|
||||
// a literal dword (guide 12.2), so the word is always 4 bytes.
|
||||
[lo, hi, low, high @ 0xb0..=0xb8, ..]
|
||||
if low & 0x7f <= 105 && matches!((high & 0xf) << 1 | low >> 7, 0 | 2..=16) =>
|
||||
{
|
||||
let kind = match (high & 0xf) << 1 | low >> 7 {
|
||||
0 => ScalarImmediate::Move,
|
||||
2 => ScalarImmediate::ConditionalMove,
|
||||
// EQ, LG, GT, GE, LT, LE as VOPC relation offsets (see SOPC).
|
||||
op @ 3..=14 => ScalarImmediate::Compare(Comparison {
|
||||
offset: [2, 5, 4, 6, 1, 3][usize::from((op - 3) % 6)],
|
||||
signed: op <= 8,
|
||||
}),
|
||||
15 => ScalarImmediate::Add,
|
||||
_ => ScalarImmediate::Multiply,
|
||||
};
|
||||
let simm16 = u16::from_le_bytes([*lo, *hi]);
|
||||
(Op::ScalarImmediate(kind, low & 0x7f, simm16), 4)
|
||||
}
|
||||
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
|
||||
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
|
||||
if (*left, *right) != (255, 255)
|
||||
@@ -638,7 +723,13 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
left_length.max(right_length),
|
||||
)
|
||||
}
|
||||
[lo, hi, opcode @ (0x82 | 0x84 | 0x86 | 0x88), 0xbf, ..] => {
|
||||
[
|
||||
lo,
|
||||
hi,
|
||||
opcode @ (0x82 | 0x84 | 0x86 | 0x87 | 0x88),
|
||||
0xbf,
|
||||
..,
|
||||
] => {
|
||||
let words = i16::from_le_bytes([*lo, *hi]);
|
||||
let words = usize::try_from(words).map_err(|_| error(offset, "backward branch"))?;
|
||||
(
|
||||
@@ -647,6 +738,7 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
condition: match opcode {
|
||||
0x84 => BranchCondition::SccZero,
|
||||
0x86 => BranchCondition::VccZero,
|
||||
0x87 => BranchCondition::VccNonzero,
|
||||
0x88 => BranchCondition::ExecZero,
|
||||
_ => BranchCondition::Always,
|
||||
},
|
||||
@@ -674,9 +766,50 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
let src1 = (second >> 1) | ((third & 1) << 7);
|
||||
(Op::Vector(kind, dst, *first, src1), 4)
|
||||
}
|
||||
[dst, 0, 0x25, 0xd5, lo, middle, hi @ 2..=3, 0x02, ..] if middle & 1 == 1 => {
|
||||
// Guide §§12.7.1, 12.9.1, 12.12 and 13.3.4: VOP3A extends
|
||||
// VOP2 by 0x100 and preserves the VOPC opcode. This subset
|
||||
// fixes unused SRC2 to inline 0 and excludes FP ABS/NEG/OMOD,
|
||||
// halfword OP_SEL, and CLAMP (integer saturation or FP compare
|
||||
// exceptions, §6.5).
|
||||
[
|
||||
dst,
|
||||
0,
|
||||
op,
|
||||
tag @ (0xd4 | 0xd5),
|
||||
lo,
|
||||
middle,
|
||||
hi @ 2..=3,
|
||||
0x02,
|
||||
..,
|
||||
] if middle & 1 != 0 => {
|
||||
let src0 = CompareSource::Vector(*lo);
|
||||
let src1 = (middle >> 1) | ((hi & 1) << 7);
|
||||
(Op::Add(*dst, *lo, src1), 8)
|
||||
match tag {
|
||||
0xd4 if matches!(op, 128..=135 | 192..=199) && *dst <= 106 => (
|
||||
Op::CompareVop3(
|
||||
*dst,
|
||||
Comparison {
|
||||
offset: op & 7,
|
||||
signed: *op < 192,
|
||||
},
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
8,
|
||||
),
|
||||
0xd5 if *op == 37 => (Op::Add(*dst, *lo, src1), 8),
|
||||
0xd5 => (
|
||||
Op::VectorInteger(
|
||||
VectorInteger::from_opcode(*op)
|
||||
.ok_or_else(|| error(offset, "unsupported VOP3 opcode"))?,
|
||||
*dst,
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
8,
|
||||
),
|
||||
_ => return Err(error(offset, "unsupported VOP3 opcode or destination")),
|
||||
}
|
||||
}
|
||||
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
|
||||
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
|
||||
@@ -1048,13 +1181,33 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
check(src1)?;
|
||||
}
|
||||
let incoming = if exec != 0 && kind.reads_vcc() {
|
||||
read_scalar(Source::Register(VCC_LO as u8))?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut outgoing = 0;
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
let s0 = match src0 {
|
||||
CompareSource::Vector(register) => read(lane, register)?,
|
||||
CompareSource::Scalar(register) => read_scalar(Source::Register(register))?,
|
||||
CompareSource::Immediate(bits) => bits,
|
||||
};
|
||||
results[lane] = Some((dst, kind.apply(s0, read(lane, src1)?)));
|
||||
let s1 = read(lane, src1)?;
|
||||
let value = if kind.reads_vcc() {
|
||||
let (value, carry) = kind.apply_vcc(s0, s1, (incoming >> lane) & 1);
|
||||
outgoing |= u32::from(carry) << lane;
|
||||
value
|
||||
} else {
|
||||
kind.apply(s0, s1)
|
||||
};
|
||||
results[lane] = Some((dst, value));
|
||||
}
|
||||
// Guide 3.9: only executing lanes can contribute a carry.
|
||||
if kind.writes_vcc() {
|
||||
scalars[VCC_LO] = Some(outgoing);
|
||||
scalars[VCC_HI] = None;
|
||||
lane_derived_vcc = exec != 0;
|
||||
}
|
||||
}
|
||||
Op::VectorUnary(kind, dst, src0) => {
|
||||
@@ -1158,6 +1311,48 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
Op::ScalarCompare(comparison, lhs, rhs) => {
|
||||
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
|
||||
}
|
||||
// Guide 12.2: SDST is also the second source; SIMM16 is
|
||||
// sign-extended except by the unsigned compares.
|
||||
Op::ScalarImmediate(kind, dst, simm16) => {
|
||||
let extended = i32::from(simm16 as i16);
|
||||
if let ScalarImmediate::Compare(comparison) = kind {
|
||||
let constant = if comparison.signed {
|
||||
extended as u32
|
||||
} else {
|
||||
u32::from(simm16)
|
||||
};
|
||||
let value = read_scalar(Source::Register(dst))?;
|
||||
scc = Some(comparison.holds(value, constant));
|
||||
} else {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
}
|
||||
let value = match kind {
|
||||
ScalarImmediate::ConditionalMove
|
||||
if !scc
|
||||
.ok_or_else(|| error(offset, "move on uninitialized SCC"))? =>
|
||||
{
|
||||
None
|
||||
}
|
||||
ScalarImmediate::Add => {
|
||||
let exact = i64::from(read_scalar(Source::Register(dst))? as i32)
|
||||
+ i64::from(extended);
|
||||
// SCC = the exact signed sum does not fit in i32.
|
||||
scc = Some(i32::try_from(exact).is_err());
|
||||
Some(exact as u32)
|
||||
}
|
||||
ScalarImmediate::Multiply => {
|
||||
let exact = i64::from(read_scalar(Source::Register(dst))? as i32)
|
||||
* i64::from(extended);
|
||||
Some(exact.rem_euclid(1 << 32) as u32)
|
||||
}
|
||||
_ => Some(extended as u32),
|
||||
};
|
||||
if let Some(value) = value {
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Scalar(kind, dst, lhs, rhs) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -1291,13 +1486,16 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
}
|
||||
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
|
||||
Op::Compare(..) | Op::WideCompare(..) => {
|
||||
let (comparison, width, src0, src1) = match op {
|
||||
Op::Compare(..) | Op::WideCompare(..) | Op::CompareVop3(..) => {
|
||||
let (dst, comparison, width, src0, src1) = match op {
|
||||
Op::Compare(comparison, src0, src1) => {
|
||||
(comparison, CompareWidth::Word, src0, src1)
|
||||
(VCC_LO, comparison, CompareWidth::Word, src0, src1)
|
||||
}
|
||||
Op::CompareVop3(dst, comparison, src0, src1) => {
|
||||
(usize::from(dst), comparison, CompareWidth::Word, src0, src1)
|
||||
}
|
||||
Op::WideCompare(comparison, width, src0, src1) => {
|
||||
(comparison, width, src0, src1)
|
||||
(VCC_LO, comparison, width, src0, src1)
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
@@ -1358,18 +1556,24 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
}
|
||||
}
|
||||
scalars[VCC_LO] = Some(mask);
|
||||
scalars[VCC_HI] = None;
|
||||
lane_derived_vcc = exec != 0;
|
||||
scalars[dst] = Some(mask);
|
||||
if dst == VCC_LO {
|
||||
scalars[VCC_HI] = None;
|
||||
lane_derived_vcc = exec != 0;
|
||||
}
|
||||
}
|
||||
Op::Branch {
|
||||
target: destination,
|
||||
condition,
|
||||
} => {
|
||||
if condition == BranchCondition::VccZero && scalars[VCC_LO].is_none() {
|
||||
let tests_vcc = matches!(
|
||||
condition,
|
||||
BranchCondition::VccZero | BranchCondition::VccNonzero
|
||||
);
|
||||
if tests_vcc && scalars[VCC_LO].is_none() {
|
||||
return Err(error(offset, "branch with uninitialized VCC_LO"));
|
||||
}
|
||||
if condition == BranchCondition::VccZero && lane_derived_vcc {
|
||||
if tests_vcc && lane_derived_vcc {
|
||||
check_runtime_region(
|
||||
&program[position + 1..],
|
||||
destination,
|
||||
@@ -1386,6 +1590,7 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
!scc.ok_or_else(|| error(offset, "branch with uninitialized SCC"))?
|
||||
}
|
||||
BranchCondition::VccZero => scalars[VCC_LO] == Some(0),
|
||||
BranchCondition::VccNonzero => scalars[VCC_LO] != Some(0),
|
||||
BranchCondition::ExecZero => exec == 0,
|
||||
};
|
||||
if take_branch {
|
||||
|
||||
+508
-143
@@ -8,9 +8,11 @@ mod graphics;
|
||||
pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
pub use xenora_decoder::Architecture;
|
||||
use xenora_decoder::SoppControlOp;
|
||||
use xenora_decoder::{
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorAluVop3Op,
|
||||
VectorBinary, VectorCompareOp, VectorSource,
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, ScalarUnaryOp, VectorAluOp,
|
||||
VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorLowering, VectorSource, VectorUnary,
|
||||
VectorVcc,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`.
|
||||
@@ -92,12 +94,24 @@ enum Op {
|
||||
Load,
|
||||
Constant(u32),
|
||||
Binary(Binary, Value, Value),
|
||||
Unary(VectorUnary, Value),
|
||||
MergeLanes {
|
||||
mask: u32,
|
||||
active: Value,
|
||||
inactive: Value,
|
||||
},
|
||||
Store(Value),
|
||||
VccArithmetic {
|
||||
primitive: VectorVcc,
|
||||
left: Value,
|
||||
right: Value,
|
||||
mask: Value,
|
||||
flag: bool,
|
||||
},
|
||||
CarryMask {
|
||||
flag: Value,
|
||||
exec: u32,
|
||||
},
|
||||
ScalarBranch {
|
||||
target: usize,
|
||||
taken: bool,
|
||||
@@ -106,8 +120,13 @@ enum Op {
|
||||
/// The value is wave-uniform; every thread computes it for its own wave.
|
||||
LaneMask {
|
||||
op: VectorCompareOp,
|
||||
/// Assembly name of the decoded encoding (`_e32` or `_e64`).
|
||||
name: &'static str,
|
||||
/// The explicit SGPR destination of the VOP3A encoding (IR text only).
|
||||
sdst: Option<usize>,
|
||||
src0: Value,
|
||||
src1: Value,
|
||||
high: Option<(Value, Value)>,
|
||||
exec: u32,
|
||||
},
|
||||
/// `s_cbranch_vccz` on a lane-derived VCC_LO (IR annotation only).
|
||||
@@ -129,12 +148,25 @@ impl Op {
|
||||
match self {
|
||||
Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(),
|
||||
Self::Binary(_, left, right) => vec![left, right],
|
||||
Self::Unary(_, source) => vec![source],
|
||||
Self::MergeLanes {
|
||||
active, inactive, ..
|
||||
} => vec![active, inactive],
|
||||
Self::Store(value) => vec![value],
|
||||
Self::LaneMask { src0, src1, .. } => vec![src0, src1],
|
||||
Self::LaneMask {
|
||||
src0, src1, high, ..
|
||||
} => {
|
||||
let mut operands = vec![src0, src1];
|
||||
if let Some((left, right)) = high {
|
||||
operands.extend([left, right]);
|
||||
}
|
||||
operands
|
||||
}
|
||||
Self::RuntimeBranch { mask, .. } => vec![mask],
|
||||
Self::VccArithmetic {
|
||||
left, right, mask, ..
|
||||
} => vec![left, right, mask],
|
||||
Self::CarryMask { flag, .. } => vec![flag],
|
||||
Self::JoinVccz {
|
||||
mask,
|
||||
fallthrough,
|
||||
@@ -149,6 +181,21 @@ impl Op {
|
||||
match self {
|
||||
Self::Load => format!("input[{index}]"),
|
||||
Self::Constant(value) => format!("0x{value:08x}u"),
|
||||
Self::Unary(op, source) => {
|
||||
let src = name(source);
|
||||
// AMD guide 12.8: all three scans return -1 if no bit matches.
|
||||
match op {
|
||||
VectorUnary::Not => format!("~{src}"),
|
||||
VectorUnary::ReverseBits => format!("reverse_bits({src})"),
|
||||
VectorUnary::FindHighUnsigned => {
|
||||
format!("{src} == 0u ? 0xffffffffu : clz({src})")
|
||||
}
|
||||
VectorUnary::FindLow => format!("{src} == 0u ? 0xffffffffu : ctz({src})"),
|
||||
VectorUnary::FindHighSigned => format!(
|
||||
"({src} == 0u || {src} == 0xffffffffu) ? 0xffffffffu : clz({src} ^ (0u - ({src} >> 31u)))"
|
||||
),
|
||||
}
|
||||
}
|
||||
Self::Binary(operator, left, right) => {
|
||||
let (left, right) = (name(left), name(right));
|
||||
let (_, symbol) = operator.operator();
|
||||
@@ -178,8 +225,32 @@ impl Op {
|
||||
name(fallthrough),
|
||||
name(taken)
|
||||
),
|
||||
Self::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag,
|
||||
} => {
|
||||
let (left, right) = (name(left), name(right));
|
||||
let bit = format!("(({} >> {lane}) & 1u)", name(mask));
|
||||
// Guide 12.7: widen the carry/borrow check before adding the input bit.
|
||||
match (primitive, flag) {
|
||||
(VectorVcc::Select, false) => format!("{bit} != 0u ? {right} : {left}"),
|
||||
(VectorVcc::AddCarry, false) => format!("{left} + {right} + {bit}"),
|
||||
(VectorVcc::AddCarry, true) => {
|
||||
format!("uint((ulong({left}) + ulong({right}) + {bit}) >> 32u)")
|
||||
}
|
||||
(VectorVcc::SubtractBorrow, false) => format!("{left} - {right} - {bit}"),
|
||||
(VectorVcc::SubtractBorrow, true) => {
|
||||
format!("uint(ulong({right}) + {bit} > ulong({left}))")
|
||||
}
|
||||
_ => unreachable!("not a VCC arithmetic operation"),
|
||||
}
|
||||
}
|
||||
Self::Store(_)
|
||||
| Self::ScalarBranch { .. }
|
||||
| Self::CarryMask { .. }
|
||||
| Self::LaneMask { .. }
|
||||
| Self::RuntimeBranch { .. } => unreachable!("not a per-thread expression"),
|
||||
}
|
||||
@@ -199,7 +270,19 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
|
||||
CompareRelation::False => return "false".to_owned(),
|
||||
CompareRelation::True => return "true".to_owned(),
|
||||
};
|
||||
if op.signed() {
|
||||
if op.semantics().width == 16 {
|
||||
// Guide §§6.2, 6.2.5 and 6.8: the e32 form reads the low half.
|
||||
let half = |value| {
|
||||
if op.signed() {
|
||||
format!("as_type<short>(ushort({value}))")
|
||||
} else {
|
||||
format!("ushort({value})")
|
||||
}
|
||||
};
|
||||
format!("{} {symbol} {}", half(left), half(right))
|
||||
} else if op.signed() && op.semantics().width == 64 {
|
||||
format!("as_type<long>({left}) {symbol} as_type<long>({right})")
|
||||
} else if op.signed() {
|
||||
format!("as_type<int>({left}) {symbol} as_type<int>({right})")
|
||||
} else {
|
||||
format!("{left} {symbol} {right}")
|
||||
@@ -401,7 +484,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
let mut ir = String::new();
|
||||
let has_mask = operations
|
||||
.iter()
|
||||
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. }));
|
||||
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. } | Op::CarryMask { .. }));
|
||||
let grid = if has_mask {
|
||||
",\n uint grid [[threads_per_grid]]"
|
||||
} else {
|
||||
@@ -423,8 +506,8 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
for (index, &(offset, operation)) in operations.iter().enumerate() {
|
||||
let dest = Value(index);
|
||||
uniform.push(match operation {
|
||||
Op::Constant(_) | Op::LaneMask { .. } => true,
|
||||
Op::Load | Op::MergeLanes { .. } => false,
|
||||
Op::Constant(_) | Op::LaneMask { .. } | Op::CarryMask { .. } => true,
|
||||
Op::Load | Op::MergeLanes { .. } | Op::VccArithmetic { .. } => false,
|
||||
_ => operation.operands().iter().all(|value| uniform[value.0]),
|
||||
});
|
||||
let thread = |value: Value| value.to_string();
|
||||
@@ -440,6 +523,19 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
format!("{dest} = const.u32 0x{value:08x}"),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
),
|
||||
Op::Unary(operator, source) => {
|
||||
let mnemonic = match operator {
|
||||
VectorUnary::Not => "not.b32",
|
||||
VectorUnary::ReverseBits => "brev.b32",
|
||||
VectorUnary::FindHighUnsigned => "ffbh.u32",
|
||||
VectorUnary::FindLow => "ffbl.b32",
|
||||
VectorUnary::FindHighSigned => "ffbh.i32",
|
||||
};
|
||||
(
|
||||
format!("{dest} = {mnemonic} {source}"),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
)
|
||||
}
|
||||
Op::Binary(operator, left, right) => (
|
||||
format!("{dest} = {} {left}, {right}", operator.operator().0),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
@@ -474,18 +570,88 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
format!("{dest} = join.vccz {mask}, {fallthrough}, {taken}"),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
),
|
||||
Op::LaneMask {
|
||||
op,
|
||||
src0,
|
||||
src1,
|
||||
exec,
|
||||
} => {
|
||||
Op::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag,
|
||||
} => (
|
||||
format!(
|
||||
"{dest} = vcc.{primitive:?}{suffix} {left}, {right}, {mask}",
|
||||
suffix = if flag { ".flag" } else { "" }
|
||||
),
|
||||
format!(
|
||||
"uint {dest} = {};",
|
||||
operation.expression(&thread, "", "(index & 31u)")
|
||||
),
|
||||
),
|
||||
Op::CarryMask { flag, exec } => {
|
||||
let _ = writeln!(
|
||||
ir,
|
||||
"{offset:04x}: {dest} = wave.mask {} {src0}, {src1} exec=0x{exec:08x}",
|
||||
op.assembly_name()
|
||||
"{offset:04x}: {dest} = wave.carry {flag} exec=0x{exec:08x}"
|
||||
);
|
||||
emit_lane_mask(
|
||||
&mut msl,
|
||||
&operations,
|
||||
&uniform,
|
||||
index,
|
||||
exec,
|
||||
vec![flag],
|
||||
|name| name(flag),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Op::LaneMask {
|
||||
op,
|
||||
name,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
high,
|
||||
exec,
|
||||
} => {
|
||||
let target = match sdst {
|
||||
None => String::new(),
|
||||
Some(VCC_LO) => " -> vcc_lo".to_string(),
|
||||
Some(register) => format!(" -> s{register}"),
|
||||
};
|
||||
let (left, right) = if let Some((hi0, hi1)) = high {
|
||||
(format!("{src0}:{hi0}"), format!("{src1}:{hi1}"))
|
||||
} else {
|
||||
(src0.to_string(), src1.to_string())
|
||||
};
|
||||
let _ = writeln!(
|
||||
ir,
|
||||
"{offset:04x}: {dest} = wave.mask {name} {left}, {right}{target} exec=0x{exec:08x}"
|
||||
);
|
||||
let inputs = if matches!(
|
||||
op.relation(),
|
||||
xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True
|
||||
) {
|
||||
Vec::new()
|
||||
} else {
|
||||
operation.operands()
|
||||
};
|
||||
emit_lane_mask(
|
||||
&mut msl,
|
||||
&operations,
|
||||
&uniform,
|
||||
index,
|
||||
exec,
|
||||
inputs,
|
||||
|name| {
|
||||
let (left, right) = if let Some((hi0, hi1)) = high {
|
||||
let pair = |lo, hi| {
|
||||
format!("((ulong({}) << 32u) | ulong({}))", name(hi), name(lo))
|
||||
};
|
||||
(pair(src0, hi0), pair(src1, hi1))
|
||||
} else {
|
||||
(name(src0), name(src1))
|
||||
};
|
||||
format!("({}) ? 1u : 0u", compare_expression(op, &left, &right))
|
||||
},
|
||||
);
|
||||
emit_lane_mask(&mut msl, &operations, &uniform, index, op, src0, src1, exec);
|
||||
continue;
|
||||
}
|
||||
Op::Store(value) => (
|
||||
@@ -505,31 +671,20 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
})
|
||||
}
|
||||
|
||||
/// Emit a Wave32 compare mask without any cross-thread operation: the thread
|
||||
/// Emit a Wave32 predicate mask without any cross-thread operation: the thread
|
||||
/// recomputes the lane-dependent operands of each lane of its own RDNA wave
|
||||
/// (dispatch indices `(index & ~31) + n`) from those lanes' input words.
|
||||
/// Absent lanes of a final partial wave contribute 0.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn emit_lane_mask(
|
||||
msl: &mut String,
|
||||
operations: &[(usize, Op)],
|
||||
uniform: &[bool],
|
||||
index: usize,
|
||||
op: VectorCompareOp,
|
||||
src0: Value,
|
||||
src1: Value,
|
||||
exec: u32,
|
||||
mut pending: Vec<Value>,
|
||||
predicate: impl FnOnce(&dyn Fn(Value) -> String) -> String,
|
||||
) {
|
||||
let mut cone = vec![false; index];
|
||||
// F and T do not depend on the operands, so their lanes compute none.
|
||||
let mut pending = if matches!(
|
||||
op.relation(),
|
||||
xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True
|
||||
) {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![src0, src1]
|
||||
};
|
||||
while let Some(value) = pending.pop() {
|
||||
if uniform[value.0] || cone[value.0] {
|
||||
continue;
|
||||
@@ -561,8 +716,8 @@ fn emit_lane_mask(
|
||||
}
|
||||
let _ = writeln!(
|
||||
msl,
|
||||
" uint pass = ({}) ? 1u : 0u;\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
|
||||
compare_expression(op, &name(src0), &name(src1))
|
||||
" uint pass = {};\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
|
||||
predicate(&name)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -576,6 +731,13 @@ fn decode_fixture(
|
||||
xenora_decoder::decode(architecture, bytes).map_err(CompileError::Decode)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ScalarValue {
|
||||
Uninitialized,
|
||||
Known(u32),
|
||||
RuntimeMask,
|
||||
}
|
||||
|
||||
fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, Op)>, CompileError> {
|
||||
let mut operations = Vec::new();
|
||||
let mut registers = [None::<Value>; 256];
|
||||
@@ -583,12 +745,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
let mut pending_load = None;
|
||||
let mut stored = false;
|
||||
let mut store_pending = false;
|
||||
let mut scalars = [None; 128];
|
||||
let mut scalars = [ScalarValue::Uninitialized; 128];
|
||||
let mut exec = u32::MAX; // The fixture starts with full Wave32 EXEC.
|
||||
scalars[126] = Some(exec);
|
||||
scalars[126] = ScalarValue::Known(exec);
|
||||
let mut scc = None;
|
||||
let mut skip_before = 0;
|
||||
// Set while VCC_LO holds a lane-derived compare mask (scalars[VCC_LO] is then None).
|
||||
// VCC_LO can forward a lane-derived mask to its supported runtime consumers.
|
||||
let mut lane_vcc: Option<Value> = None;
|
||||
// An open runtime `s_cbranch_vccz` region: its end, mask and the VGPRs at the branch.
|
||||
let mut region: Option<(usize, Value, [Option<Value>; 256])> = None;
|
||||
@@ -597,18 +759,18 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
// contract, even when a known branch skips it.
|
||||
for (index, instruction) in decoded.iter().enumerate() {
|
||||
let offset = instruction.offset;
|
||||
if let Some(target) = instruction.branch_target()
|
||||
&& (target <= offset
|
||||
|| decoded
|
||||
.binary_search_by_key(&target, |instruction| instruction.offset)
|
||||
.is_err())
|
||||
{
|
||||
return Err(CompileError::Verify {
|
||||
offset,
|
||||
reason: "branch target must be a forward instruction boundary",
|
||||
});
|
||||
}
|
||||
let reason = match instruction.instruction {
|
||||
Instruction::Branch { target }
|
||||
| Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target }
|
||||
if target <= offset
|
||||
|| decoded
|
||||
.binary_search_by_key(&target, |instruction| instruction.offset)
|
||||
.is_err() =>
|
||||
{
|
||||
"branch target must be a forward instruction boundary"
|
||||
}
|
||||
Instruction::BufferLoadDword {
|
||||
index, resource, ..
|
||||
} if (index, resource) != (0, 0) => "unsupported resource or buffer index",
|
||||
@@ -720,20 +882,54 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
}
|
||||
let read_scalar = |source| match source {
|
||||
ScalarSource::Immediate(value) => Ok(value),
|
||||
ScalarSource::Register(register) => scalars
|
||||
.get(usize::from(register))
|
||||
.copied()
|
||||
.flatten()
|
||||
.ok_or_else(|| error("scalar source has no known value")),
|
||||
ScalarSource::Register(register) => match scalars.get(usize::from(register)) {
|
||||
Some(ScalarValue::Known(value)) => Ok(*value),
|
||||
Some(ScalarValue::RuntimeMask) => Err(error(
|
||||
"scalar source reads a runtime-only SGPR compare mask",
|
||||
)),
|
||||
Some(ScalarValue::Uninitialized) | None => {
|
||||
Err(error("scalar source has no known value"))
|
||||
}
|
||||
},
|
||||
};
|
||||
let read_vector = |source, operations: &mut Vec<_>, facts: &mut Vec<_>| {
|
||||
Ok(match source {
|
||||
VectorSource::Register(register) => read(register)?,
|
||||
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
|
||||
match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, ScalarValue::Known(bits)) => {
|
||||
constant(operations, facts, offset, bits)
|
||||
}
|
||||
(None, _) => {
|
||||
return Err(error("vector ALU reads uninitialized VCC_LO"));
|
||||
}
|
||||
}
|
||||
}
|
||||
VectorSource::Scalar(register) => {
|
||||
let bits = read_scalar(ScalarSource::Register(register))?;
|
||||
constant(operations, facts, offset, bits)
|
||||
}
|
||||
VectorSource::Immediate(bits) => constant(operations, facts, offset, bits),
|
||||
})
|
||||
};
|
||||
// Scalar instructions and waits still execute when all lanes are inactive.
|
||||
if exec == 0 {
|
||||
match instruction.instruction {
|
||||
Instruction::VectorAlu { op, .. } if op.writes_vcc() => {
|
||||
// Guide 3.9: inactive lanes contribute zero to carry-out.
|
||||
lane_vcc = None;
|
||||
scalars[VCC_LO] = ScalarValue::Known(0);
|
||||
scalars[VCC_HI] = ScalarValue::Uninitialized;
|
||||
continue;
|
||||
}
|
||||
Instruction::MoveB32 { .. }
|
||||
| Instruction::VectorAluVop3 { .. }
|
||||
| Instruction::VectorAddF32 { .. }
|
||||
| Instruction::VectorMulF32 { .. }
|
||||
| Instruction::VectorAlu { .. } => continue,
|
||||
| Instruction::VectorAlu { .. }
|
||||
| Instruction::VectorUnary { .. }
|
||||
| Instruction::VectorSwap { .. } => continue,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -745,6 +941,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
{
|
||||
return Err(error("vector memory requires full Wave32 EXEC"));
|
||||
}
|
||||
if let Instruction::BufferLoadDword { resource, .. }
|
||||
| Instruction::BufferStoreDword { resource, .. } = instruction.instruction
|
||||
{
|
||||
let start = usize::from(resource);
|
||||
if scalars[start..start + 4]
|
||||
.iter()
|
||||
.any(|value| matches!(value, ScalarValue::RuntimeMask))
|
||||
{
|
||||
return Err(error(
|
||||
"resource descriptor reads a runtime-only SGPR compare mask",
|
||||
));
|
||||
}
|
||||
}
|
||||
let next = Value(operations.len());
|
||||
let (dest, operation) = match instruction.instruction {
|
||||
Instruction::BufferLoadDword { data, .. } => {
|
||||
@@ -766,12 +975,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
store_pending = true;
|
||||
(None, Op::Store(read(data)?))
|
||||
}
|
||||
Instruction::WaitLoad => {
|
||||
if let Some((register, value)) = pending_load.take() {
|
||||
registers[register] = Some(value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::WaitStore => {
|
||||
store_pending = false;
|
||||
continue;
|
||||
@@ -843,13 +1046,17 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
} else {
|
||||
(read(src0)?, read(src1)?)
|
||||
};
|
||||
(
|
||||
Some(dst),
|
||||
Op::Binary(Binary::Vector(op.lowering()), left, right),
|
||||
)
|
||||
let VectorLowering::Binary(binary) = op.lowering() else {
|
||||
return Err(error("VOP3 with a lane condition is unsupported"));
|
||||
};
|
||||
(Some(dst), Op::Binary(Binary::Vector(binary), left, right))
|
||||
}
|
||||
Instruction::ScalarMoveB32 { dst, src } => {
|
||||
let value = read_scalar(src)?;
|
||||
Instruction::ScalarUnary {
|
||||
op: op @ ScalarUnaryOp::MovB32,
|
||||
dst,
|
||||
src,
|
||||
} => {
|
||||
let (value, _) = op.evaluate(read_scalar(src)?);
|
||||
if dst < 8 {
|
||||
return Err(error("scalar move would modify a resource descriptor"));
|
||||
}
|
||||
@@ -862,7 +1069,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
*slot = ScalarValue::Known(value);
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
@@ -874,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
*slot = ScalarValue::Known(value);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
@@ -899,7 +1106,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
*slot = ScalarValue::Known(value);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
@@ -909,12 +1116,76 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/scalar-immediate.md.
|
||||
Instruction::ScalarImmediate { op, dst, simm16 } => {
|
||||
if dst < 8 {
|
||||
return Err(error("scalar immediate would modify a resource descriptor"));
|
||||
}
|
||||
let scc_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("SOPK SCC input reads uninitialized SCC"))?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
let old = if op.reads_dst() {
|
||||
match *slot {
|
||||
ScalarValue::Known(value) => value,
|
||||
ScalarValue::RuntimeMask => {
|
||||
return Err(error("SOPK reads a runtime-only SGPR compare mask"));
|
||||
}
|
||||
ScalarValue::Uninitialized => {
|
||||
return Err(error("SOPK reads an uninitialized SGPR"));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let (value, flag) = op.evaluate(old, simm16, scc_in);
|
||||
if let Some(value) = value {
|
||||
*slot = ScalarValue::Known(value);
|
||||
}
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarImmediateCompare { op, src, simm16 } => {
|
||||
scc = Some(op.test(read_scalar(ScalarSource::Register(src))?, simm16));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/vector-compare.md sections 3 and 5.
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
// Both encodings share the Wave32 lane mask implementation.
|
||||
compare @ (Instruction::VectorCompare { .. }
|
||||
| Instruction::VectorCompareVop3 { .. }) => {
|
||||
let (op, name, explicit, sdst, src0, src1) = match compare {
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
(op, op.assembly_name(), false, VCC_LO, src0, src1)
|
||||
}
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
} => (
|
||||
op.base(),
|
||||
op.assembly_name(),
|
||||
true,
|
||||
usize::from(sdst),
|
||||
VectorSource::Register(src0),
|
||||
src1,
|
||||
),
|
||||
_ => unreachable!("only vector compares reach this arm"),
|
||||
};
|
||||
if exec == 0 {
|
||||
scalars[VCC_HI] = None;
|
||||
scalars[VCC_LO] = Some(0);
|
||||
lane_vcc = None;
|
||||
if sdst == VCC_LO {
|
||||
scalars[VCC_HI] = ScalarValue::Uninitialized;
|
||||
scalars[VCC_LO] = ScalarValue::Known(0);
|
||||
lane_vcc = None;
|
||||
} else {
|
||||
scalars[sdst] = ScalarValue::RuntimeMask;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let constant =
|
||||
@@ -924,13 +1195,32 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
facts.push(KnownBits::constant(bits));
|
||||
value
|
||||
};
|
||||
let high = if op.semantics().width == 64 {
|
||||
// Guide §3.6.3 and contract §2a put the high word at base + 1.
|
||||
let left = match src0 {
|
||||
VectorSource::Register(base) => read(base + 1)?,
|
||||
VectorSource::Scalar(base) => {
|
||||
let bits = read_scalar(ScalarSource::Register(base + 1))?;
|
||||
constant(&mut operations, &mut facts, bits)
|
||||
}
|
||||
VectorSource::Immediate(bits) => {
|
||||
let high = ((bits as i32) >> 31) as u32;
|
||||
constant(&mut operations, &mut facts, high)
|
||||
}
|
||||
};
|
||||
Some((left, read(src1 + 1)?))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(register) => read(register)?,
|
||||
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
|
||||
match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, Some(bits)) => constant(&mut operations, &mut facts, bits),
|
||||
(None, None) => {
|
||||
(None, ScalarValue::Known(bits)) => {
|
||||
constant(&mut operations, &mut facts, bits)
|
||||
}
|
||||
(None, _) => {
|
||||
return Err(error("compare reads uninitialized VCC_LO"));
|
||||
}
|
||||
}
|
||||
@@ -947,54 +1237,87 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
offset,
|
||||
Op::LaneMask {
|
||||
op,
|
||||
name,
|
||||
sdst: explicit.then_some(sdst),
|
||||
src0,
|
||||
src1,
|
||||
high,
|
||||
exec,
|
||||
},
|
||||
));
|
||||
facts.push(KnownBits::UNKNOWN);
|
||||
scalars[VCC_LO] = None;
|
||||
scalars[VCC_HI] = None;
|
||||
lane_vcc = Some(mask);
|
||||
if sdst == VCC_LO {
|
||||
scalars[VCC_LO] = ScalarValue::Uninitialized;
|
||||
scalars[VCC_HI] = ScalarValue::Uninitialized;
|
||||
lane_vcc = Some(mask);
|
||||
} else {
|
||||
scalars[sdst] = ScalarValue::RuntimeMask;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::BranchVccZero { target } if let Some(mask) = lane_vcc => {
|
||||
if pending_load.is_some() {
|
||||
return Err(error(
|
||||
"a runtime s_cbranch_vccz requires no outstanding vector load",
|
||||
));
|
||||
}
|
||||
region = Some((target, mask, registers));
|
||||
(None, Op::RuntimeBranch { mask, target })
|
||||
}
|
||||
Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } => {
|
||||
let taken = match instruction.instruction {
|
||||
Instruction::BranchSccZero { .. } => {
|
||||
!scc.ok_or_else(|| error("conditional branch reads uninitialized SCC"))?
|
||||
Instruction::Branch { .. }
|
||||
| Instruction::BranchSccZero { .. }
|
||||
| Instruction::BranchExecZero { .. }
|
||||
| Instruction::BranchVccZero { .. }
|
||||
| Instruction::WaitLoad
|
||||
| Instruction::EndProgram => {
|
||||
match instruction
|
||||
.instruction
|
||||
.sopp_control()
|
||||
.expect("decoded SOPP control")
|
||||
{
|
||||
SoppControlOp::WaitLoad => {
|
||||
if let Some((register, value)) = pending_load.take() {
|
||||
registers[register] = Some(value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::BranchVccZero { .. } => {
|
||||
scalars[106]
|
||||
.ok_or_else(|| error("conditional branch reads uninitialized VCC_LO"))?
|
||||
== 0
|
||||
SoppControlOp::EndProgram => {
|
||||
if !stored || store_pending || pending_load.is_some() {
|
||||
return Err(error(
|
||||
"termination requires one completed store and no pending loads",
|
||||
));
|
||||
}
|
||||
return Ok(operations);
|
||||
}
|
||||
op => {
|
||||
let target = instruction.branch_target().expect("decoded SOPP branch");
|
||||
if op == SoppControlOp::BranchVccZero
|
||||
&& let Some(mask) = lane_vcc
|
||||
{
|
||||
if pending_load.is_some() {
|
||||
return Err(error(
|
||||
"a runtime s_cbranch_vccz requires no outstanding vector load",
|
||||
));
|
||||
}
|
||||
region = Some((target, mask, registers));
|
||||
(None, Op::RuntimeBranch { mask, target })
|
||||
} else {
|
||||
let taken = match op {
|
||||
SoppControlOp::Branch => true,
|
||||
SoppControlOp::BranchSccZero => !scc.ok_or_else(|| {
|
||||
error("conditional branch reads uninitialized SCC")
|
||||
})?,
|
||||
SoppControlOp::BranchVccZero => {
|
||||
let ScalarValue::Known(bits) = scalars[VCC_LO] else {
|
||||
return Err(error(
|
||||
"conditional branch reads uninitialized VCC_LO",
|
||||
));
|
||||
};
|
||||
bits == 0
|
||||
}
|
||||
SoppControlOp::BranchExecZero => exec == 0,
|
||||
SoppControlOp::WaitLoad | SoppControlOp::EndProgram => {
|
||||
unreachable!()
|
||||
}
|
||||
};
|
||||
if taken {
|
||||
skip_before = target;
|
||||
}
|
||||
(None, Op::ScalarBranch { target, taken })
|
||||
}
|
||||
}
|
||||
_ => exec == 0,
|
||||
};
|
||||
if taken {
|
||||
skip_before = target;
|
||||
}
|
||||
(None, Op::ScalarBranch { target, taken })
|
||||
}
|
||||
Instruction::Branch { target } => {
|
||||
skip_before = target;
|
||||
(
|
||||
None,
|
||||
Op::ScalarBranch {
|
||||
target,
|
||||
taken: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
@@ -1002,37 +1325,87 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(register) => read(register)?,
|
||||
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
|
||||
match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, Some(bits)) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
(None, None) => {
|
||||
return Err(error("vector ALU reads uninitialized VCC_LO"));
|
||||
}
|
||||
}
|
||||
}
|
||||
VectorSource::Scalar(register) => {
|
||||
let bits = read_scalar(ScalarSource::Register(register))?;
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
VectorSource::Immediate(bits) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
};
|
||||
let src0 = read_vector(src0, &mut operations, &mut facts)?;
|
||||
let src1 = read(src1)?;
|
||||
let (left, right) = if op.swaps_sources() {
|
||||
(src1, src0)
|
||||
} else {
|
||||
(src0, src1)
|
||||
};
|
||||
(
|
||||
Some(dst),
|
||||
Op::Binary(Binary::Vector(op.lowering()), left, right),
|
||||
)
|
||||
match op.lowering() {
|
||||
VectorLowering::Binary(binary) => {
|
||||
(Some(dst), Op::Binary(Binary::Vector(binary), left, right))
|
||||
}
|
||||
VectorLowering::Vcc(primitive) => {
|
||||
let mask = match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, ScalarValue::Known(bits)) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
(None, _) => {
|
||||
return Err(error("vector ALU reads uninitialized VCC_LO"));
|
||||
}
|
||||
};
|
||||
if op.writes_vcc() {
|
||||
let flag = Value(operations.len());
|
||||
operations.push((
|
||||
offset,
|
||||
Op::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag: true,
|
||||
},
|
||||
));
|
||||
facts.push(KnownBits::UNKNOWN);
|
||||
lane_vcc = Some(Value(operations.len()));
|
||||
operations.push((offset, Op::CarryMask { flag, exec }));
|
||||
facts.push(KnownBits::UNKNOWN);
|
||||
scalars[VCC_LO] = ScalarValue::Uninitialized;
|
||||
scalars[VCC_HI] = ScalarValue::Uninitialized;
|
||||
}
|
||||
(
|
||||
Some(dst),
|
||||
Op::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Instruction::VectorUnary { op, dst, src } => {
|
||||
let source = read_vector(src, &mut operations, &mut facts)?;
|
||||
(Some(dst), Op::Unary(op.lowering(), source))
|
||||
}
|
||||
Instruction::VectorSwap { dst, src, .. } => {
|
||||
// Guide 12.8: capture both old values before updating either VGPR.
|
||||
// read() also rejects v0 and registers with outstanding loads.
|
||||
let old_dst = read(dst)?;
|
||||
let old_src = read(src)?;
|
||||
if dst != src {
|
||||
registers[usize::from(dst)] = Some(merge_lanes(
|
||||
&mut operations,
|
||||
&mut facts,
|
||||
offset,
|
||||
exec,
|
||||
old_src,
|
||||
Some(old_dst),
|
||||
)?);
|
||||
registers[usize::from(src)] = Some(merge_lanes(
|
||||
&mut operations,
|
||||
&mut facts,
|
||||
offset,
|
||||
exec,
|
||||
old_dst,
|
||||
Some(old_src),
|
||||
)?);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::VectorAddF32 { dst, src0, src1 } => (
|
||||
Some(dst),
|
||||
@@ -1049,14 +1422,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
"graphics instruction is unsupported in a compute fixture",
|
||||
));
|
||||
}
|
||||
Instruction::EndProgram => {
|
||||
if !stored || store_pending || pending_load.is_some() {
|
||||
return Err(error(
|
||||
"termination requires one completed store and no pending loads",
|
||||
));
|
||||
}
|
||||
return Ok(operations);
|
||||
}
|
||||
};
|
||||
let value_bits = match operation {
|
||||
Op::Constant(bits) => KnownBits::constant(bits),
|
||||
|
||||
@@ -14,6 +14,110 @@ fn compiles_original_fixture() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_compare_to_vcc_lo_drives_a_runtime_vccz_branch() {
|
||||
let code: Vec<_> = [
|
||||
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
|
||||
0x7e04_0282, // v_mov_b32_e32 v2, 2
|
||||
0xd4c2_006a, // v_cmp_eq_u32_e64 vcc_lo, v1, v2
|
||||
0x0202_0501,
|
||||
0xbf86_0001, // s_cbranch_vccz 1
|
||||
0x7e02_0302, // v_mov_b32_e32 v1, v2
|
||||
]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.chain(FIXTURE[28..].iter().copied())
|
||||
.collect();
|
||||
let shader = compile(Architecture::Gfx1030, &code).unwrap();
|
||||
assert!(
|
||||
shader
|
||||
.disassembly
|
||||
.contains("v_cmp_eq_u32_e64 vcc_lo, v1, v2")
|
||||
);
|
||||
assert!(shader.ir.contains("0008: t2 = wave.mask"));
|
||||
assert!(shader.ir.contains("0010: branch.vccz t2 -> 0x0018"));
|
||||
assert!(shader.ir.contains("join.vccz t2"));
|
||||
assert!(shader.msl.contains("lane_index >= grid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_compare_to_s4_rejects_later_scalar_reads() {
|
||||
for (setup, offset) in [
|
||||
(&[0x7e02_0281u32, 0x7e04_0282][..], 16), // Initialize both VGPRs.
|
||||
(&[0xbefe_0380][..], 12), // Empty EXEC. The VGPRs need not be initialized.
|
||||
] {
|
||||
let code: Vec<_> = setup
|
||||
.iter()
|
||||
.copied()
|
||||
.chain([
|
||||
0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2
|
||||
0x0202_0501,
|
||||
0xbf06_8004, // s_cmp_eq_u32 s4, 0
|
||||
0xbefe_03c1, // s_mov_b32 exec_lo, -1
|
||||
0x7e02_0281, // v_mov_b32_e32 v1, 1
|
||||
])
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.chain(FIXTURE[28..].iter().copied())
|
||||
.collect();
|
||||
let error = compile(Architecture::Gfx1030, &code).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error,
|
||||
CompileError::Verify {
|
||||
offset: actual,
|
||||
reason: "scalar source reads a runtime-only SGPR compare mask",
|
||||
} if actual == offset
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_compare_mask_cannot_be_read_as_a_buffer_descriptor() {
|
||||
let code: Vec<_> = [
|
||||
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
|
||||
0x7e04_0282, // v_mov_b32_e32 v2, 2
|
||||
0xd4c2_0004, // v_cmp_eq_u32_e64 s4, v1, v2
|
||||
0x0202_0501,
|
||||
]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.chain(FIXTURE[28..].iter().copied())
|
||||
.collect();
|
||||
assert!(matches!(
|
||||
compile(Architecture::Gfx1030, &code),
|
||||
Err(CompileError::Verify {
|
||||
offset: 16,
|
||||
reason: "resource descriptor reads a runtime-only SGPR compare mask",
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_compare_to_normal_sgpr_preserves_vcc_and_can_be_overwritten() {
|
||||
let code: Vec<_> = [
|
||||
0x7e02_0281u32, // v_mov_b32_e32 v1, 1
|
||||
0x7e04_0282, // v_mov_b32_e32 v2, 2
|
||||
0xbeea_0381, // s_mov_b32 vcc_lo, 1
|
||||
0xd4c2_0008, // v_cmp_eq_u32_e64 s8, v1, v2
|
||||
0x0202_0501,
|
||||
0xbf86_0001, // s_cbranch_vccz 1
|
||||
0xbe88_0381, // s_mov_b32 s8, 1
|
||||
0xbf06_8008, // s_cmp_eq_u32 s8, 0
|
||||
]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.chain(FIXTURE[28..].iter().copied())
|
||||
.collect();
|
||||
let shader = compile(Architecture::Gfx1030, &code).unwrap();
|
||||
assert!(
|
||||
shader
|
||||
.ir
|
||||
.contains("0014: branch.uniform 0x001c taken=false")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_wait_is_required_before_using_loaded_data() {
|
||||
let mut code = FIXTURE.to_vec();
|
||||
@@ -308,6 +412,20 @@ fn scalar_compare_results_resolve_every_branch() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_results_resolve_every_branch() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-immediate.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-immediate.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
|
||||
@@ -350,6 +468,20 @@ fn vector_integer_forms_lower_to_per_lane_templates() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_integer_forms_lower_to_per_lane_templates() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/vop3-integer.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/vop3-integer.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_f_and_t_compares_lower_to_operand_free_wave_masks() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin");
|
||||
@@ -377,3 +509,45 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
include_str!("../../../fixtures/golden/vector-compare.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_compare_forms_lower_to_wave_masks() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vop3-compare.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/vop3-compare.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/vop3-compare.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_vcc_fixture_matches_ir_and_msl_goldens() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-vcc.bin");
|
||||
let result = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
result.ir,
|
||||
include_str!("../../../fixtures/golden/vector-vcc.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
result.msl,
|
||||
include_str!("../../../fixtures/golden/vector-vcc.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop1_integer_fixture_lowers_unary_and_masked_swap() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-unary.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/vector-unary.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/vector-unary.metal")
|
||||
);
|
||||
}
|
||||
+47
-10
@@ -27,6 +27,8 @@ pub use upload::{
|
||||
|
||||
const BLOCK_BYTES: usize = 8;
|
||||
const TILE_BLOCKS: usize = 2;
|
||||
const TILE_ROW_BYTES: usize = TILE_BLOCKS * BLOCK_BYTES;
|
||||
const TILE_BYTES: usize = TILE_BLOCKS * TILE_ROW_BYTES;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum TextureError {
|
||||
@@ -91,19 +93,30 @@ impl<'a> TiledBc1<'a> {
|
||||
/// Copies one subresource as tightly packed row-major BC1 block rows.
|
||||
/// Padded tile slots are excluded, including at partial texel blocks.
|
||||
pub fn linearize(&self, layer: usize, mip: u32) -> Result<Vec<u8>, TextureError> {
|
||||
if layer >= self.layers {
|
||||
if layer >= self.layers || mip >= self.mips {
|
||||
return Err(TextureError::OutOfBounds);
|
||||
}
|
||||
self.mip_extent(mip)?;
|
||||
let (width, height) = mip_blocks(self.width, self.height, mip);
|
||||
let base = self.mip_base(layer, mip)?;
|
||||
let tile_row_stride = width.div_ceil(TILE_BLOCKS) * TILE_BYTES;
|
||||
let full_tiles = width / TILE_BLOCKS;
|
||||
let edge_bytes = (width % TILE_BLOCKS) * BLOCK_BYTES;
|
||||
let mut blocks = Vec::new();
|
||||
// Construction checked the larger, padded byte count.
|
||||
blocks
|
||||
.try_reserve_exact(width * height * BLOCK_BYTES)
|
||||
.map_err(|_| TextureError::AllocationFailed)?;
|
||||
// Construction requires the exact padded length, so each selected tile row is in bounds.
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
blocks.extend_from_slice(&self.block(layer, mip, x, y)?);
|
||||
let row_start =
|
||||
base + (y / TILE_BLOCKS) * tile_row_stride + (y % TILE_BLOCKS) * TILE_ROW_BYTES;
|
||||
for tile in 0..full_tiles {
|
||||
let start = row_start + tile * TILE_BYTES;
|
||||
blocks.extend_from_slice(&self.bytes[start..start + TILE_ROW_BYTES]);
|
||||
}
|
||||
if edge_bytes != 0 {
|
||||
let start = row_start + full_tiles * TILE_BYTES;
|
||||
blocks.extend_from_slice(&self.bytes[start..start + edge_bytes]);
|
||||
}
|
||||
}
|
||||
Ok(blocks)
|
||||
@@ -124,19 +137,24 @@ impl<'a> TiledBc1<'a> {
|
||||
if x >= width || y >= height {
|
||||
return Err(TextureError::OutOfBounds);
|
||||
}
|
||||
let mut base = layer * self.layer_bytes;
|
||||
for prior in 0..mip {
|
||||
base += mip_bytes(self.width, self.height, prior)?;
|
||||
}
|
||||
let base = self.mip_base(layer, mip)?;
|
||||
// Construction checked the full padded size for every level and layer.
|
||||
let tile = (y / TILE_BLOCKS) * width.div_ceil(TILE_BLOCKS) + x / TILE_BLOCKS;
|
||||
let within_tile = (y % TILE_BLOCKS) * TILE_BLOCKS + x % TILE_BLOCKS;
|
||||
let offset = base + (tile * TILE_BLOCKS.pow(2) + within_tile) * BLOCK_BYTES;
|
||||
let offset = base + tile * TILE_BYTES + within_tile * BLOCK_BYTES;
|
||||
self.bytes
|
||||
.get(offset..offset + BLOCK_BYTES)
|
||||
.and_then(|bytes| bytes.try_into().ok())
|
||||
.ok_or(TextureError::InvalidByteLength)
|
||||
}
|
||||
|
||||
fn mip_base(&self, layer: usize, mip: u32) -> Result<usize, TextureError> {
|
||||
let mut base = layer * self.layer_bytes;
|
||||
for prior in 0..mip {
|
||||
base += mip_bytes(self.width, self.height, prior)?;
|
||||
}
|
||||
Ok(base)
|
||||
}
|
||||
}
|
||||
|
||||
fn mip_blocks(width: usize, height: usize, mip: u32) -> (usize, usize) {
|
||||
@@ -151,7 +169,7 @@ fn mip_bytes(width: usize, height: usize, mip: u32) -> Result<usize, TextureErro
|
||||
width
|
||||
.div_ceil(TILE_BLOCKS)
|
||||
.checked_mul(height.div_ceil(TILE_BLOCKS))
|
||||
.and_then(|tiles| tiles.checked_mul(TILE_BLOCKS.pow(2) * BLOCK_BYTES))
|
||||
.and_then(|tiles| tiles.checked_mul(TILE_BYTES))
|
||||
.ok_or(TextureError::SizeOverflow)
|
||||
}
|
||||
|
||||
@@ -216,6 +234,7 @@ mod tests {
|
||||
assert_eq!(tex.linearize(1, 0).unwrap(), logical_blocks.as_flattened());
|
||||
assert_eq!(tex.linearize(1, 1).unwrap(), [20; 8]);
|
||||
assert_eq!(tex.linearize(2, 0), Err(TextureError::OutOfBounds));
|
||||
assert_eq!(tex.linearize(0, 2), Err(TextureError::OutOfBounds));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -242,6 +261,24 @@ mod tests {
|
||||
assert_eq!(texture.block(0, 0, 2, 2), Ok([12; 8]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linearizes_odd_tile_edges_in_each_layer() {
|
||||
// A 21×21 texture uses 9, 4 and 1 tiles across the three mips.
|
||||
// Mip 1 is 10×10 texels, so only nine of its sixteen slots are logical.
|
||||
let block = |slot: u8| [slot, 1, 2, 3, 4, 5, 6, !slot];
|
||||
let bytes: Vec<_> = (0..112).flat_map(block).collect();
|
||||
let texture = TiledBc1::new(&bytes, 21, 21, 3, 2).unwrap();
|
||||
for (layer, first_slot) in [(0, 36), (1, 92)] {
|
||||
let expected: Vec<_> = [0, 1, 4, 2, 3, 6, 8, 9, 12]
|
||||
.into_iter()
|
||||
.flat_map(|slot| block(first_slot + slot))
|
||||
.collect();
|
||||
assert_eq!(texture.linearize(layer, 1).unwrap(), expected);
|
||||
let last_mip: Vec<_> = (16..20).flat_map(|slot| block(first_slot + slot)).collect();
|
||||
assert_eq!(texture.linearize(layer, 2).unwrap(), last_mip);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_opaque_and_transparent_bc1_palettes() {
|
||||
let opaque = decode_bc1([0, 0xf8, 31, 0, 0xe4, 0xe4, 0xe4, 0xe4]);
|
||||
|
||||
@@ -25,6 +25,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
|
||||
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
|
||||
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
|
||||
- [VOP1 vector unary and swap](shaders/vector-unary.md) — Wave32 integer bit operations, register exchange, and operand limits.
|
||||
- [VOP2 select and carry](shaders/vector-vcc.md) — Wave32 lane selection, carry and borrow through the vector condition code.
|
||||
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
|
||||
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
|
||||
|
||||
@@ -38,6 +40,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
|
||||
## Testing, validation, and benchmarks
|
||||
|
||||
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
|
||||
<title id="title">Xenora · recorded progress</title>
|
||||
<desc id="description">Decoded gfx1030 forms: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 185 of 185. Accepted Metal forms · Apple M5: 18 of 185. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
|
||||
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
|
||||
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
|
||||
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">104 / 104</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">185 / 185</text>
|
||||
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 104</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 185</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="84.81" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="47.68" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
|
||||
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
|
||||
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -40,11 +40,68 @@ XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `Cpu
|
||||
|
||||
- a denormal dividend over zero raises divide-by-zero only, not also denormal-operand;
|
||||
- flush-to-zero also flushes a tiny result that is exact, raising underflow and precision;
|
||||
- DAZ applies before conversion to an integer;
|
||||
- an unmasked overflow also records precision.
|
||||
- DAZ applies before conversion to an integer.
|
||||
|
||||
An unmasked overflow records precision only when rounding with an unbounded exponent is inexact (Intel SDM Vol. 1, D.4.2.3, Table D-16). The known-answer cases in `tests/cpu_known_answers.rs` assert this.
|
||||
|
||||
None of it has been compared with x86 hardware.
|
||||
|
||||
## Locked instructions
|
||||
|
||||
XADD and CMPXCHG exist for 8-, 16-, 32- and 64-bit register and memory destinations. The LOCK prefix (F0) is accepted on exactly the forms the registry marks `lock = true`, and only when the destination is memory. Today those are the memory forms of XADD and CMPXCHG. LOCK anywhere else is an illegal instruction, as the Intel SDM (Vol. 2, "LOCK") specifies for a register destination or an instruction that cannot be locked. LOCK on the other instructions the SDM allows (ADD, ADC, AND, BTC, BTR, BTS, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR and XCHG), CMPXCHG8B and CMPXCHG16B are not implemented and stay rejected.
|
||||
|
||||
These rules hold for both engines and are what a guest scheduler has to preserve:
|
||||
|
||||
- **Ordering.** Each engine runs one guest instruction at a time on one host thread, and an instruction either completes or changes nothing. A locked instruction is therefore indivisible and totally ordered with every other guest access, and LOCK changes no result: the locked and unlocked encodings leave identical state. A scheduler that switches guest threads only between instructions keeps this. One that runs guest threads on several host threads does not, and must first make each locked instruction atomic against every access to its operand, with x86's ordering rather than ARM64's weaker one. Nothing here provides or tests that.
|
||||
- **Alignment.** A locked operand may have any alignment and may span two mapped regions.
|
||||
- **Compare failure.** CMPXCHG compares the accumulator with the destination as CMP would and sets all six status flags from it. On a match it stores the source and leaves the accumulator alone. On a mismatch it loads the destination into the accumulator and stores the destination's old value back, so the destination is written either way and a mismatch on memory that cannot be written still faults. With a 32-bit register destination both stores clear the upper half of that register, following the SDM's operation text.
|
||||
- **Faults.** If any byte of the operand cannot be read or written, the instruction faults before memory, registers or flags change.
|
||||
- **Lowering.** The DBT runs these forms on the shared semantics. They are not lowered to ARM64 atomic instructions, which could only be judged against concurrent guest threads.
|
||||
|
||||
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/x86_atomic.rs` adds the LOCK rules, both compare outcomes at every width, unaligned operands and faults. None of it has been compared with x86 hardware, and nothing here establishes multi-thread behaviour.
|
||||
|
||||
## Memory ordering and fences
|
||||
|
||||
Guest memory accesses are totally ordered today. Each engine runs one guest instruction at a time on one host thread, and every load and store of an instruction completes before the next instruction starts. There is no store buffer and nothing is reordered, so a load always sees the latest earlier store. That is stronger than the ordering the Intel SDM (Vol. 3A, "Memory Ordering") gives a real processor, where a store may sit in a buffer while later loads from other locations run.
|
||||
|
||||
MFENCE, LFENCE and SFENCE (`0F AE` with a register ModRM byte and digit 6, 5 or 7; the SDM states that the r/m field is ignored) are therefore accepted and change no register, flag or memory. They have nothing left to enforce. Non-temporal stores are ordinary stores, so SFENCE has no weakly ordered store to wait for either. The memory forms that share those digits, the XSAVE family and CLFLUSH, stay rejected.
|
||||
|
||||
This holds only while guest threads do not run on several host threads. ARM64 orders memory more weakly than x86, so an engine that ran guest threads in parallel would have to restore x86's ordering for ordinary accesses and give the fences a real effect. Nothing here provides or tests that. `tests/cpu_known_answers.rs` holds the single-thread cases: a store, a fence and a later load in program order, and no change to any other state. None of it has been compared with x86 hardware.
|
||||
|
||||
## String instructions
|
||||
|
||||
MOVS and STOS exist for 8-, 16-, 32- and 64-bit elements, alone and with REP (F3), together with the direction flag and CLD and STD. `CpuState::df` holds the flag. It is not one of the six status flags the registry tracks.
|
||||
|
||||
- **One element per step.** A REP form moves one element, decrements RCX and, while RCX is not zero, leaves RIP on the instruction. Each element is a step of its own in both engines and counts against the step budget, so a repeat cannot outrun the budget and can stop part-way and resume. A zero count touches no memory and no register. Without REP, RCX is not read. Step counts therefore count elements, not instructions, for a REP form.
|
||||
- **Direction.** RSI and RDI move up by the element size when the flag is clear and down when it is set. Each element is read whole and then written, so overlapping ranges behave as that order dictates.
|
||||
- **Faults.** An element completes or changes nothing. A fault keeps the elements already done, leaves RSI, RDI and RCX at the element that faulted, and leaves RIP on the instruction.
|
||||
- **Segments.** An FS or GS override applies to the MOVS source. The destination, and STOS as a whole, take no override.
|
||||
- **Lowering.** The DBT runs these forms on the shared semantics, one helper call per element, and a string instruction ends its translated block. There is no bulk-copy path, so large copies are slow.
|
||||
|
||||
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count, the step accounting, faults and the segment rule. None of it has been compared with x86 hardware.
|
||||
|
||||
## Guest CPUID
|
||||
|
||||
CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a synthetic processor: the vendor string is `Xenora guest`, not Intel's or AMD's, and leaf 1 reports no family, model or stepping.
|
||||
|
||||
| Leaf (EAX) | EAX | EBX | ECX | EDX |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 0 | 1, the highest basic leaf | `Xeno` | `uest` | `ra g` |
|
||||
| 1 | 0 | 0 | POPCNT (bit 23) | CMOV (bit 15) |
|
||||
| 0x8000_0000 | 0x8000_0001, the highest extended leaf | 0 | 0 | 0 |
|
||||
| 0x8000_0001 | 0 | 0 | LZCNT (bit 5) | long mode (bit 29) |
|
||||
| any other | 0 | 0 | 0 | 0 |
|
||||
|
||||
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
|
||||
|
||||
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
|
||||
- The table is therefore truthful about Xenora, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
|
||||
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
|
||||
|
||||
`xenora_loader::cpu::cpuid` is the one copy of the table. A runtime service that reports processor features should read it rather than keep its own list.
|
||||
|
||||
`tests/cpu_features.rs` pins every leaf in both engines. For each reported feature it requires the feature's whole instruction set among the fixtures that `tests/x86_integer.rs` executes. For each feature software commonly tests that is not reported, it holds one instruction of that feature that both engines must refuse. To report a new feature: implement all of its instructions, remove its witness, add its instruction list to the reported set, then set the bit. The pairing of instructions with feature bits follows the Intel SDM; nothing was compared with a processor.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, atomics and fences. The DBT also refuses raw SYSCALL.
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
|
||||
+75
-10
@@ -69,16 +69,37 @@ storage, invokes its callbacks and runs the entry point. The fixture entry point
|
||||
uses a Win64-aligned stack and terminates with HLT. The result includes the loaded
|
||||
guest memory and the entry execution outcome.
|
||||
|
||||
`xenora probe --mode static` inventories ordinary PE imports without guest
|
||||
execution. `missing_imports.csv` lists unresolved keys with their import address
|
||||
table relative virtual addresses. The full inventory records whether each key is registered, its implementation
|
||||
status, and the canonical module behind API-set aliases. Runtime-loaded modules
|
||||
and services require separate analysis. The coverage matrix groups unresolved
|
||||
imports by shared startup prerequisites. Static imports do not reveal call
|
||||
order. The JSON report counts import slots, DLL and symbol keys, distinct
|
||||
names with DLL-scoped ordinals, and canonical registered handlers separately.
|
||||
The unresolved total includes explicitly tracked unsupported APIs and other
|
||||
missing handlers. Existing stubs remain visible in the full inventory.
|
||||
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
|
||||
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
|
||||
with their import address table relative virtual addresses. The full inventory,
|
||||
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
|
||||
column and records whether each key is registered, its implementation
|
||||
status, and the canonical module behind API-set aliases. Modules and services
|
||||
loaded by other means at run time require separate analysis. The coverage matrix
|
||||
groups unresolved ordinary imports by shared startup prerequisites. Static
|
||||
imports do not reveal call order. The JSON report counts import slots, DLL and
|
||||
symbol keys, distinct names with DLL-scoped ordinals, and canonical registered
|
||||
handlers separately. The unresolved total includes explicitly tracked
|
||||
unsupported APIs and other missing handlers. Existing stubs remain visible in
|
||||
the full inventory.
|
||||
|
||||
Delay-loaded imports come from the PE32+ delay-load directory, data directory
|
||||
13 in Microsoft's PE format. The probe reports each one with its DLL, symbol or
|
||||
ordinal, and slot in the delay import address table, after the ordinary rows.
|
||||
Binding does not resolve them: the PE format leaves that to a delay-load helper
|
||||
inside the image. The totals above and `missing_imports.csv` therefore cover
|
||||
ordinary imports only, and the JSON report counts delayed slots and DLLs in
|
||||
`delayed_imports` and `delayed_imported_dlls_count`. `xenora imports sync`
|
||||
leaves delayed rows out of its backlog for the same reason.
|
||||
|
||||
The probe reads only descriptors that lie wholly inside the directory's
|
||||
declared size, and expects that size to hold the empty descriptor that ends the
|
||||
table. It reads descriptors whose `RvaBased` attribute is set, and requires each
|
||||
one's DLL name, import address table and import name table to be present and to
|
||||
start in section data. A table that breaks one of these rules, sets a reserved
|
||||
attribute bit, is truncated, or uses the earlier virtual-address descriptor form
|
||||
is reported in `delay_import_error` and in the Markdown report, together with
|
||||
the entries read before it.
|
||||
|
||||
The synthetic process registry supports the current-process pseudo handle and
|
||||
its process ID. The priority boost setter and getter record and query a guest
|
||||
@@ -477,3 +498,47 @@ compare function. Colour and the stored depth are both read back.
|
||||
|
||||
These passes are checked on the GPU with Metal validation against expectations
|
||||
derived independently from the public semantics; synthetic fixtures only.
|
||||
|
||||
### Guest texture binding (descriptor tables)
|
||||
|
||||
`GraphicsContext` lets a guest command list sample one texture in the pixel
|
||||
stage through a D3D12-shaped binding. A draw samples only if a root signature
|
||||
is bound. Draws without one keep the flat-colour path. The supported subset
|
||||
is fixed. Anything outside it fails with `GraphicsError::Unsupported` when the
|
||||
object is created, or with an error at execution. A rejected draw never
|
||||
reaches the backend. Draws recorded before it in the same list have already
|
||||
run.
|
||||
|
||||
| Object | Supported |
|
||||
| --- | --- |
|
||||
| `create_descriptor_heap` | Shader-visible `CBV_SRV_UAV` (0) or `SAMPLER` (1) heaps of 1–64 descriptors. RTV, DSV and CPU-only heaps are unsupported. |
|
||||
| `create_committed_texture2d` | One level of `R8G8B8A8_UNORM` (28) or `BC1_UNORM` (71), 1–64 texels per side. BC1 sizes must be multiples of four. Rows are linear: 4 bytes per texel, or 8 bytes per 4×4 block. Xbox tiling is not handled. |
|
||||
| `create_shader_resource_view` | A `Texture2D` view of mip 0 of a single-level, single-slice 2D texture, in the resource's own format. |
|
||||
| `create_sampler` | Point filtering (`MIN_MAG_MIP_POINT`), clamp addressing on U, V and W, no LOD bias and a minimum LOD of 0. |
|
||||
| `create_root_signature` | Exactly two pixel-visibility descriptor tables, in either order: one with a single SRV range for `t0`, and one with a single sampler range for `s0` (one descriptor each, space 0). Root constants, root descriptors, CBV and UAV ranges, extra tables or ranges and static samplers are unsupported. |
|
||||
| `cmd_set_descriptor_heaps` | At most one heap of each type. |
|
||||
| `cmd_set_graphics_root_descriptor_table` | The base must be a GPU handle to a slot of the bound heap of the table's type. The slot must hold a descriptor when a draw reads it. Changing the heaps or binding a different root signature clears every table. Setting the same heaps or the same root signature again keeps them. |
|
||||
|
||||
Descriptor handles follow D3D12 pointer arithmetic: the heap start plus
|
||||
`index × GetDescriptorHandleIncrementSize` (32 here; guests must query the
|
||||
value). `offset` returns `None` rather than carry into the next heap. CPU and
|
||||
GPU handles are separate spaces. A textured draw is a `DrawInstanced` of
|
||||
one instance of three vertices with start instance 0, starting at any vertex. Zero vertices or
|
||||
instances draw nothing. The sampled texture must be in `COMMON` or a read-only state that includes
|
||||
`PIXEL_SHADER_RESOURCE`. The software reference draws at most 4096 pixels. Each vertex record holds a float4 position
|
||||
at byte 0 and a float4 texture coordinate at byte 16, with a stride of at
|
||||
least 32. Textured indexed draws are unsupported.
|
||||
|
||||
The native backend receives a `TexturedDraw` with the bound level and must
|
||||
bind it to fragment texture 0 and sampler 0, which are the `tex0` and `samp0` arguments of
|
||||
the translated `image_sample_lz` pixel stage. `NativeCompute::render_rgba8_sampled_bc1`
|
||||
binds a BC1 level natively for that purpose. The software reference has no
|
||||
clipping or depth test. A pixel is covered when its centre lies inside or on
|
||||
an edge of the triangle. The texture coordinate is interpolated affinely, so
|
||||
`w = 1` is required, and point sampled with
|
||||
`min(floor(clamp(u, 0, 1) × width), width − 1)`. It decodes BC1 with the
|
||||
spec-exact `xenora_texture::decode_bc1`. Apple's hardware rounds BC1's two
|
||||
interpolated palette entries differently (171/84 against 170/85, measured
|
||||
on an M5 Pro), so the tests use endpoint colours only. Pipeline
|
||||
state objects do not exist yet, so the backend, not the guest, chooses the
|
||||
pixel shader. These entry points are not yet wired to guest imports.
|
||||
@@ -14,12 +14,39 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| Form | Operands | Size or word | Recognized | Decoded | LLVM | Lowering | Reference | CPU | GPU |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `buffer_load_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL load | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values (semantic registry) | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
|
||||
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
|
||||
| `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified |
|
||||
| `v_mul_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_hi_i32_i24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_i32_i24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_hi_u32_u24_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_mul_hi_u32_u24_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_min_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_max_i32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_i32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_min_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_min_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_max_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_max_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_xnor_b32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_xnor_b32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_sub_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_sub_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_subrev_nc_u32_e64` | VOP3A, Wave32; VGPR destination and two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; inactive lanes keep VDST; the operation of `v_subrev_nc_u32_e32` | 8 B | yes | yes | three-way passed | per-thread typed integer template of the VOP2 form | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_t_i32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_i32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_lt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_eq_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_le_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_gt_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ne_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_ge_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_f_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_t_u32_e64` | VOP3A, Wave32; SGPR destination s0-s105 or vcc_lo, D[n] = EXEC_LO[n] & test, fully written; two VGPR inputs, modifier fields clear, SRC2 encoded as inline zero; the relation of `v_cmp_t_u32_e32`; reading a lane-derived mask from an SGPR other than vcc_lo is a translation error | 8 B | yes | yes | three-way passed | per-thread Wave32 mask, as the VOPC form; runtime s_cbranch_vccz through vcc_lo | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate (semantic registry) | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
|
||||
| `s_not_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0 | `BE890708` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_brev_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged | `BE8A0B08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -33,6 +60,22 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
|
||||
| `s_movk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); D = sext(SIMM16); SCC unchanged | `B0088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmovk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); if SCC then D = sext(SIMM16), SCC known during translation; SCC unchanged | `B1088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_eq_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S == sext(SIMM16) (signed) | `B1888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lg_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S != sext(SIMM16) (signed) | `B2088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_gt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S > sext(SIMM16) (signed) | `B2888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_ge_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= sext(SIMM16) (signed) | `B3088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S < sext(SIMM16) (signed) | `B3888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_le_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= sext(SIMM16) (signed) | `B4088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_eq_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S == zext(SIMM16) (unsigned) | `B4888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lg_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S != zext(SIMM16) (unsigned) | `B5088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_gt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S > zext(SIMM16) (unsigned) | `B5888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_ge_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= zext(SIMM16) (unsigned) | `B6088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_lt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S < zext(SIMM16) (unsigned) | `B6888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmpk_le_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= zext(SIMM16) (unsigned) | `B7088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_addk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = D + sext(SIMM16); SCC = signed overflow | `B7888000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mulk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = low 32 bits of D * sext(SIMM16); SCC unchanged | `B8088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -93,8 +136,36 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_cmp_t_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D0E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D800501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_t_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D8E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified |
|
||||
| `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified |
|
||||
| `v_cmp_lt_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written | `7D120702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written | `7D140702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written | `7D160702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written | `7D180702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written | `7D1A0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written | `7D1C0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written | `7D520702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written | `7D540702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written | `7D560702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written | `7D580702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written | `7D5A0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written | `7D5C0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (false), fully written | `7D400902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written | `7D420902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written | `7D440902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written | `7D460902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written | `7D480902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written | `7D4A0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written | `7D4C0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_t_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (true), fully written | `7D4E0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (false), fully written | `7DC00902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written | `7DC20902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written | `7DC40902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written | `7DC60902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written | `7DC80902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written | `7DCA0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written | `7DCC0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_t_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (true), fully written | `7DCE0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_scc0` | Nonnegative signed dword displacement (semantic registry) | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified |
|
||||
| `s_branch` | Nonnegative signed dword displacement (semantic registry) | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified |
|
||||
| `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified |
|
||||
| `v_xor_b32_e32` | Two VGPR sources and one VGPR destination | `3A020702` | yes | yes | three-way passed | MSL bitwise XOR | implemented | fixture verified | fixture verified |
|
||||
| `v_add_f32_e32` | Two VGPR sources and one VGPR destination | `06020702` | yes | yes | three-way passed | MSL FP32 add | implemented | fixture verified | fixture verified |
|
||||
@@ -103,8 +174,14 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_lshlrev_b32_e32` | Two VGPR sources and one VGPR destination | `34020501` | yes | yes | three-way passed | MSL logical left shift with a five-bit count | implemented | fixture verified | fixture verified on Apple M5 |
|
||||
| `v_lshrrev_b32_e32` | Two VGPR sources and one VGPR destination | `2DFFFF01` | yes | yes | three-way passed | MSL logical right shift with a five-bit count | implemented | fixture verified | fixture verified on Apple M5 |
|
||||
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_execz` | Nonnegative signed dword displacement (semantic registry) | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement (semantic registry) | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_not_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement | `7E046F01` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_bfrev_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order | `7E067101` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_ffbh_u32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero | `7E087302` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_ffbl_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero | `7E0A7501` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_ffbh_i32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match | `7E0C7702` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_swap_b32` | VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0 | `7E02CB02` | yes | yes | three-way passed | per-thread exchange of both register values with lane merges under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -117,16 +194,20 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_add_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry | `4A160F06` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_sub_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry | `4C181308` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_subrev_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry | `4E1A170A` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cndmask_b32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; select S1 when the VCC_LO lane bit is set, otherwise S0 | `020402C1` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_add_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned addition with carry input and output | `50040481` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_sub_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S0 minus S1 with borrow input and output | `52060480` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_subrev_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S1 minus S0 with borrow input and output | `540606C2` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
<!-- status:instructions:end -->
|
||||
|
||||
## Automated three-way comparison
|
||||
|
||||
LLVM 23.1.6, the production decoder and the independent reference decoder
|
||||
matched 650 instructions across ten streams: the eight synthetic fixtures,
|
||||
matched 1,088 instructions across 18 streams: 16 synthetic fixtures,
|
||||
a high-register sequence and an operand matrix assembled by LLVM.
|
||||
The harness checks byte offsets, widths, encoded bytes from LLVM, mnemonic
|
||||
and operands, and the typed reference operation against the production
|
||||
operation. It covers all 42 compute forms in this document.
|
||||
operation. It covers 124 instruction forms.
|
||||
|
||||
The matrix checks the 81 inline integer selectors in VOP1, SOP1, SOPC and
|
||||
SOP2, forced literals that could otherwise be inline, literal selection in
|
||||
@@ -136,7 +217,7 @@ operands, and zero and nonzero forward branch displacements. The decoder
|
||||
trace exposes MUBUF operands independently of the synthetic execution ABI,
|
||||
which still requires the original index and resource bindings.
|
||||
|
||||
Five malformed LLVM probes produced diagnostics, and 25 valid encodings
|
||||
Five malformed LLVM probes produced diagnostics, and 27 valid encodings
|
||||
or disassemblable branch sequences were deliberately rejected by both Xenora
|
||||
decoders. Both Xenora decoders also reject all 37 interior truncation offsets
|
||||
in the add fixture and every case in the unsupported-encoding list.
|
||||
|
||||
@@ -189,8 +189,9 @@ Eleven 32-bit SOP1 forms are declared in the registry (operand rule
|
||||
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
|
||||
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
|
||||
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
|
||||
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
|
||||
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
|
||||
`s_mov_b32` is the twelfth registry SOP1 form, under its own operand rule
|
||||
`sop1_move`, because it also accepts EXEC and VCC halves as destinations (the
|
||||
domain the hand-written decoder accepted before #215 moved it). As for SOP2, destinations s0-s7 are refused when a fixture runs
|
||||
(they hold its buffer descriptors), and float inline constants are rejected.
|
||||
|
||||
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# SOPK scalar immediate forms
|
||||
|
||||
Xenora decodes and translates sixteen gfx1030 SOPK integer forms through the
|
||||
semantic registry (`crates/isa/semantics/rdna2/sopk.toml`, operand rules
|
||||
`sopk_sgpr` and `sopk_compare`). Each is one 32-bit word: SIMM16 in bits 0-15,
|
||||
SDST in bits 16-22, OP in bits 23-27, ENCODING `0b1011` in bits 28-31
|
||||
(guide 13.1.2). The word never takes a literal dword (guide 12.2), so a SIMM16
|
||||
whose low byte is `0xff` is an immediate, not a literal marker.
|
||||
|
||||
| Form | Opcode | Operation | SCC |
|
||||
| --- | ---: | --- | --- |
|
||||
| `s_movk_i32` | 0 | D = signext(SIMM16) | unchanged |
|
||||
| `s_cmovk_i32` | 2 | if SCC, D = signext(SIMM16); otherwise D keeps its value | read, unchanged |
|
||||
| `s_cmpk_{eq,lg,gt,ge,lt,le}_i32` | 3-8 | SCC = (D relation signext(SIMM16)), signed | the relation |
|
||||
| `s_cmpk_{eq,lg,gt,ge,lt,le}_u32` | 9-14 | SCC = (D relation SIMM16), SIMM16 zero-extended, unsigned | the relation |
|
||||
| `s_addk_i32` | 15 | D = D + signext(SIMM16) | signed overflow of the sum |
|
||||
| `s_mulk_i32` | 16 | D = low 32 bits of D * signext(SIMM16) | unchanged |
|
||||
|
||||
## Operands
|
||||
|
||||
SDST is `s0`-`s105`. `s0`-`s7` hold the resource descriptors of the fixture
|
||||
ABI, so they may be read (the compares) but are never written: the translator
|
||||
refuses a write there even when `s_cmovk_i32` would not take it. SDST 106-127
|
||||
(`vcc`, `ttmp`, `m0`, `null`, `exec`) is rejected at decode. The other SOPK
|
||||
opcodes stay unsupported, except the fixed store fence `s_waitcnt_vscnt null,
|
||||
0` (`0xbbfd0000`), which keeps its own decoding.
|
||||
|
||||
## How it runs
|
||||
|
||||
SGPR values are known while translating, so a SOPK instruction folds into the
|
||||
translator's scalar state exactly like the SOP2 and SOPC forms: no IR node is
|
||||
emitted. `s_cmpk_*` sets SCC; `s_addk_i32` writes D and SCC; `s_mulk_i32` writes
|
||||
D; `s_movk_i32` and a taken `s_cmovk_i32` write D. `s_addk_i32`, `s_mulk_i32`
|
||||
and the compares read D, so an SDST nothing has written is rejected.
|
||||
`s_cmovk_i32` reads SCC and is rejected when SCC is uninitialized; with SCC clear
|
||||
it neither reads nor writes D, so an unwritten SDST stays unwritten.
|
||||
|
||||
## Verification
|
||||
|
||||
`tests/validation/tests/sopk.rs` derives its expected values from the guide
|
||||
alone and runs 4,184 cases on both CPU interpreters and, through the translator,
|
||||
on native Metal (that test is `#[ignore]`d and runs under `scripts/test-gpu.sh`),
|
||||
plus 398 rejected programs. `fixtures/rdna2/scalar-immediate.s` (LLVM-assembled,
|
||||
expected input ^ 0x40008275) uses all sixteen forms, recording each compare's SCC
|
||||
through an `s_cbranch_scc0`; its IR and MSL are pinned under
|
||||
`fixtures/golden/scalar-immediate.*`. Agreement with a spec-derived reference is
|
||||
not agreement with hardware.
|
||||
@@ -24,19 +24,19 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
|
||||
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
|
||||
| SOP1 | 65 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 11 |
|
||||
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
|
||||
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| SOPK | 27 | 17 | 16 | 17 | 17 | 17 | 1 | 1 | 5 |
|
||||
| SOPP | 36 | 6 | 6 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 |
|
||||
| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 |
|
||||
| VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 |
|
||||
| VOP2 | 47 | 24 | 22 | 24 | 24 | 24 | 7 | 7 | 11 |
|
||||
| VOP3 | 416 | 28 | 28 | 28 | 28 | 28 | 1 | 1 | 17 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 |
|
||||
| **Total** | 1465 | 104 | 91 | 108 | 104 | 104 | 18 | 18 | 60 |
|
||||
| VOPC | 190 | 28 | 44 | 44 | 44 | 44 | 0 | 0 | 9 |
|
||||
| **Total** | 1465 | 169 | 179 | 189 | 185 | 185 | 18 | 18 | 83 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -44,10 +44,22 @@ The table counts distinct variant names per family across registry operand rules
|
||||
|
||||
| Family | Operand rule | Unsupported variants |
|
||||
| --- | --- | --- |
|
||||
| SOP1 | `sop1_move` | `dst_m0`, `dst_null`, `dst_ttmp`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPK | `sopk_compare` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
|
||||
| SOPK | `sopk_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
|
||||
| SOPP | `sopp_branch` | None listed |
|
||||
| SOPP | `sopp_end` | None listed |
|
||||
| SOPP | `sopp_wait` | None listed |
|
||||
| VOP1 | `vop1_swap` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOP1 | `vop1_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOP2 | `vop2_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOP3 | `vop3_cmp_vgpr2` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc_hi`, `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOPC | `vopc_vcc_half` | `src_exec`, `src_float_inline`, `src_literal`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOPC | `vopc_vcc_pair` | `src_exec`, `src_float_inline`, `src_literal`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
@@ -13,7 +13,7 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `crates/isa/semantics/rdna2.toml` | The registry root: schema, architecture, the snapshot hash, the cited documents and the ordered `include` list of family files. |
|
||||
| `crates/isa/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. |
|
||||
| `crates/isa/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sopk.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. |
|
||||
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
|
||||
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
|
||||
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
|
||||
@@ -48,20 +48,19 @@ file of its encoding (`rdna2/vop3.toml`) and has exactly these fields:
|
||||
| `of` | The `name` of the declared base form |
|
||||
| `family` | The encoding family of this variant; must differ from the form's |
|
||||
| `opcode` | The XML opcode in that family |
|
||||
| `operands` | An operand rule of that family whose kind can encode the base form (today `vop3_vgpr2` for VOP2 vector forms) |
|
||||
| `operands` | An operand rule of that family that can encode the base form (`vop3_vgpr2` for VOP2 vector forms, `vop3_cmp_vgpr2` for VOPC integer compares) |
|
||||
| `spec`, `verify` | As for a form |
|
||||
|
||||
Everything else (operation, signedness, effects, source order) is inherited
|
||||
from the base form, and the XML check runs on that inherited declaration with
|
||||
the variant's family, opcode and operand rule, so the VOP3 operand widths and
|
||||
formats must agree with it. The generator emits one enum per variant rule (`VectorAluVop3Op` for
|
||||
`vop3_vgpr2`) holding exactly the declared variants, with `from_word` (encoding
|
||||
The variant inherits the operation, signedness, source order and SCC and EXEC
|
||||
effects. Its operand rule determines where the result is written. The XML
|
||||
check uses the variant's family, opcode and operand rule to validate the
|
||||
inherited declaration. The generator emits one enum per variant rule
|
||||
(`VectorAluVop3Op` or `VectorCompareVop3Op`) with `from_word` (encoding
|
||||
bits, then an explicit match on the OP field), `base()` (the inherited form),
|
||||
`assembly_name()` and `semantics()`, and one `FORMS` row per variant after the
|
||||
forms. Because the enum has no undeclared members, an instruction cannot name a
|
||||
VOP3 encoding that does not exist. Every explicit XML operand of the variant,
|
||||
destination included, must have the data format of the base operand in the same
|
||||
role (destination, then the sources in rule order). A variant-only rule says so
|
||||
VOP3 encoding that does not exist. Corresponding explicit XML operands must
|
||||
have the same data format by role. A variant-only rule says so
|
||||
in the data (`variant_only = true`), so the RDNA2 planner does not count it as a
|
||||
rule that can host new forms. A
|
||||
variant-only rule (one marked `variant_of` in the generator) cannot be used by a
|
||||
@@ -75,7 +74,15 @@ the registry: VGPR destination, two VGPR sources, ABS, OP_SEL, CLAMP, OMOD and
|
||||
NEG clear, and SRC2 the assembler's unused inline zero. `v_add_nc_u32_e64` is its
|
||||
first variant; adding the VOP3 encoding of another VOP2 form under this rule is
|
||||
one `[[encoding_variant]]` entry. Wider VOP3 operand rules (scalar and inline
|
||||
sources, legal modifiers) come with the VOP3 batch.
|
||||
sources, legal modifiers) need separate rules.
|
||||
|
||||
`vop3_cmp_vgpr2` uses the same VGPR source and modifier restrictions and
|
||||
specifies a scalar destination. It requires a base form with a `lane_mask`
|
||||
write to implicit VCC, and generates an `sdst_lane_mask` effect on the
|
||||
variant row. The generator checks the base VCC output and the variant's
|
||||
explicit scalar mask destination against the XML. An SDST of 106 selects
|
||||
`vcc_lo`. See [the compare contract](vector-compare.md#11-vop3a-encoding-_e64)
|
||||
for Wave32 lowering and allowed consumers.
|
||||
|
||||
## Fields
|
||||
|
||||
@@ -109,18 +116,18 @@ error.
|
||||
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
|
||||
| `opcode` | Opcode; must match the XML | non-negative integer |
|
||||
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `compare` and the SOP1 unaries |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` (SOP1 and SOPK), `cmov` (SOPK only), `compare` and the SOP1 unaries |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
|
||||
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
|
||||
| `width` | Operand and result width in bits | `32` |
|
||||
| `carry_in` | Implicit carry, borrow or select input | `none`, `scc` for unsigned scalar `add` and `sub` and required for scalar `cselect`, `vcc` for the Wave32 VOP2 select and carry forms |
|
||||
| `width` | Operand and result width in bits (operand width for compares) | `32`, `16` with `vopc_vcc_half`, or `64` with `vopc_vcc_pair` |
|
||||
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
|
||||
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
|
||||
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
|
||||
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
|
||||
| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (no EXEC-writing contract yet) |
|
||||
| `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC and SOPK compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Implicit effect on VCC and EXEC | `vcc` is `lane_mask` for [VOPC compares](vector-compare.md) and the three [VOP2 carry forms](vector-vcc.md). These write all of VCC_LO, zero inactive lane bits and leave VCC_HI unknown. Other forms declare `vcc` as `unchanged`. All forms declare `exec` as `unchanged`. Operand rules cover explicit destinations. |
|
||||
| `wave` | Wave sizes the form is valid in | `wave32` for SOPP controls, VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms in the Wave32 compute fixture ABI, `any` for other registry forms |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
|
||||
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
|
||||
@@ -150,13 +157,23 @@ fixes the `scc` value:
|
||||
| `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no |
|
||||
| `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no |
|
||||
| `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no |
|
||||
| `mov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | no |
|
||||
| `cmov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | required |
|
||||
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
|
||||
|
||||
Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
|
||||
SOP1 unary forms share `ScalarUnaryOp`. The `sop1_sgpr` rule accepts
|
||||
destination encodings 0–105. The `sop1_move` rule for `s_mov_b32` also accepts
|
||||
106–107 (VCC halves) and 126–127 (EXEC halves) as explicit destinations.
|
||||
Both rules accept source registers s0–s105, inline integers −16 through 64,
|
||||
and one literal dword. The move copies the source and leaves SCC unchanged.
|
||||
The destination vocabulary preserves the original decoder subset of the
|
||||
RDNA 2 guide sections 5.3 and 12.3.
|
||||
|
||||
Binary vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
|
||||
generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder
|
||||
which rule a form uses) use a separate table:
|
||||
the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc`
|
||||
must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
|
||||
must be `unchanged` (these binary forms write no SCC, VCC or EXEC):
|
||||
|
||||
| `operation` / `signedness` | `VectorBinary` |
|
||||
| --- | --- |
|
||||
@@ -167,6 +184,12 @@ must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
|
||||
| `and`, `or`, `xor` / `bitwise` | `And`, `Or`, `Xor` |
|
||||
| `lshl`, `lshr` / `bitwise`, `ashr` / `signed` (with `shift_count_bits = 5`) | `ShiftLeft`, `ShiftRight`, `ArithmeticShiftRight` |
|
||||
|
||||
The [Wave32 VOP2 select and carry forms](vector-vcc.md) use `vop2_vcc` with
|
||||
the general SRC0 domain and an implicit VCC input. The generator checks the
|
||||
direction of each fieldless VCC operand in the pinned XML. The three arithmetic
|
||||
forms also declare a lane-mask output and use the same reverse-source mechanism
|
||||
as the no-carry subtraction.
|
||||
|
||||
`vop2_vgpr2` is the VGPR-only subset (SRC0 256-511) that the hand-written decoder
|
||||
accepted for `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`
|
||||
and `v_ashrrev_i32` before they moved into the registry (#215 M27); widening them
|
||||
@@ -174,19 +197,47 @@ to `vop2_vgpr` would be a behaviour change and needs its own oracle. The three
|
||||
shifts declare `source_order = "reversed"` (D = S1 shifted by S0[4:0]), so the
|
||||
generator checks the XML's unsigned count format on SRC0, not VSRC1.
|
||||
|
||||
VOPC compares (operand rule `vopc_vcc`, kind `vector_compare`: SRC0 a
|
||||
`vector_source` as for VOP2, VSRC1 a VGPR, destination implicitly `vcc_lo`)
|
||||
take the same `relation` and primitive as SOPC compares, but declare
|
||||
VOPC compares (kind `vector_compare`) write `vcc_lo`. The 32-bit rule
|
||||
`vopc_vcc` accepts a `vector_source` as for VOP2 and a VGPR. The 16-bit rule
|
||||
`vopc_vcc_half` reads the low half of the same source types and rejects
|
||||
literals (guide sections 6.2, 6.2.5 and 6.8). The 64-bit rule
|
||||
`vopc_vcc_pair` accepts a VGPR pair, an even normal SGPR pair or an inline
|
||||
integer as SRC0 and a VGPR pair as VSRC1. All three declare a `relation`,
|
||||
`scc = "unchanged"`, `vcc = "lane_mask"` and `wave = "wave32"`. The XML's implicit
|
||||
64-bit VCC output must be present and is accounted for by `lane_mask`. Signedness
|
||||
still matters for `eq` and `lg`, because the MSL lowering casts signed operands.
|
||||
`v_cmpx_*` (EXEC writes), the VOP3 encoding and Wave64 stay unsupported.
|
||||
The VOP3A variants redirect the same Wave32 mask to SDST. EXEC-writing
|
||||
compares (`v_cmpx_*`) and Wave64 stay unsupported.
|
||||
|
||||
A SOPC compare must use an operand rule of the compare kind (`sopc_scalar`: two
|
||||
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
|
||||
one source and an SGPR destination), and a two-source ALU operation
|
||||
`sop2_sgpr`.
|
||||
|
||||
SOPK forms (guide 12.2) use two rules. `sopk_sgpr` (kind `immediate`, enum
|
||||
`ScalarImmediateOp`) has SDST `s0`-`s105` as the destination and SIMM16 as the one
|
||||
source; it takes `mov`, `cmov` (reads SCC, so `carry_in = "scc"`), `add` (`D = D +
|
||||
signext(SIMM16)`, `scc = "signed_overflow"`) and `mul` (`scc = "unchanged"`), all
|
||||
`signed`, and the `add` and `mul` forms read the old SDST. `sopk_compare` (kind
|
||||
`immediate_compare`, enum `ScalarImmediateCompareOp`) takes `compare` with SDST as
|
||||
the left operand and the SIMM16 as the right one: sign-extended for `signed`,
|
||||
zero-extended for `unsigned`. A SOPK compare's opcode must be 3 (`signed`) or 9
|
||||
(`unsigned`) plus the relation's index in `eq, lg, gt, ge, lt, le` (guide 13.1.2).
|
||||
The XML must give SIMM16 as 16-bit `FMT_NUM_I16` (`FMT_NUM_U16` for `unsigned`).
|
||||
The word never takes a literal dword. The details are in
|
||||
[scalar-immediate.md](scalar-immediate.md).
|
||||
|
||||
The SOPP control rules (AMD RDNA 2 ISA guide §§12.5 and 13.1.5) generate
|
||||
`SoppControlOp` for the existing Wave32 compute subset. `sopp_end` accepts
|
||||
`s_endpgm` with zero in SIMM16. `sopp_wait` accepts only `s_waitcnt vmcnt(0)`
|
||||
(`0x3f70`), completing a pending vector load. `sopp_branch` accepts
|
||||
`s_branch`, `s_cbranch_scc0`, `s_cbranch_vccz` and `s_cbranch_execz` with a
|
||||
nonnegative signed SIMM16 displacement in dwords from the next instruction.
|
||||
The decoder and compiler require a valid target boundary. The conditional
|
||||
branches read SCC, VCC_LO or EXEC_LO without writing those registers.
|
||||
Other SOPP forms, including `s_nop`, the nonzero branches, `s_sendmsg`,
|
||||
`s_trap`, `s_sethalt` and `s_setprio`, remain unsupported.
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
## What the validator checks
|
||||
@@ -196,8 +247,9 @@ vocabularies above, it rejects:
|
||||
|
||||
- contradictions: a declared `scc` or `carry_in` that the primitive does not
|
||||
have, `bitwise` on an arithmetic operation or the reverse;
|
||||
- VOPC compares whose opcode is not the group base (128 for `signed`, 192
|
||||
for `unsigned`) plus the relation's offset in guide Table 59 (F 0, LT 1,
|
||||
- VOPC compares whose opcode is not the group base (128 and 192 for signed and
|
||||
unsigned 32-bit forms, 136 and 168 for 16-bit forms, 160 and 224 for 64-bit
|
||||
forms) plus the relation's offset in guide Table 59 (F 0, LT 1,
|
||||
EQ 2, LE 3, GT 4, LG/NE 5, GE 6, T 7), and a `lane_mask` form whose XML
|
||||
does not have exactly one implicit VCC operand that is written and not read;
|
||||
- duplicates: the same `name`, the same `(family, opcode)`, or the same
|
||||
|
||||
@@ -75,18 +75,18 @@ stream carries no wave-size declaration (the VOPC word has no wave-size field),
|
||||
so every caller of the translator and the reference establishes Wave32 by
|
||||
using this ABI; there is no Wave64 entry point to reject.
|
||||
|
||||
### 2a. 16-bit and 64-bit compares (reference interpreters only)
|
||||
### 2a. 16-bit and 64-bit compares
|
||||
|
||||
The reference (`crates/ref`) and the second interpreter
|
||||
(`tests/validation/independent_ref.rs`) also accept the `_e32` forms
|
||||
`v_cmp_{lt,eq,le,gt,ne,ge}_{i16,u16}` (opcodes 137-142, 169-174) and
|
||||
`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i64,u64}` (160-167, 224-231). The decoder and
|
||||
the translator still reject them (section 4); these forms have an oracle
|
||||
but no translation yet.
|
||||
The decoder, translator and both reference interpreters accept the `_e32`
|
||||
forms `v_cmp_{lt,eq,le,gt,ne,ge}_{i16,u16}` (opcodes 137–142, 169–174) and
|
||||
`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i64,u64}` (160–167, 224–231). The registry
|
||||
uses `vopc_vcc_half` for the 16-bit forms and `vopc_vcc_pair` for the 64-bit
|
||||
forms.
|
||||
|
||||
- 16-bit forms read bits 15:0 of each 32-bit source and ignore bits 31:16
|
||||
(an inference from guide 6.2, 6.2.5 and 6.8: only SDWA selects a half).
|
||||
There is no literal source.
|
||||
SRC0 accepts a VGPR, a known SGPR, `vcc_lo` or an inline integer
|
||||
(for example, −1 supplies `0xffff`). VSRC1 is a VGPR. Literals are rejected.
|
||||
- 64-bit forms read a pair: v[n:n+1] with n <= 254, an even-aligned
|
||||
s[2k:2k+1] with k <= 52 (3.6.3), or an inline integer, which is
|
||||
sign-extended to 64 bits (-1 is all ones, also for `_u64`; a reading of
|
||||
@@ -122,10 +122,10 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned
|
||||
## 4. Rejected (controlled translation/reference error, never a silent no-op)
|
||||
|
||||
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
|
||||
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
|
||||
- VOP3A compares outside the integer subset in section 11.
|
||||
- SDWA and DPP forms; float compares; v_cmp_class.
|
||||
- 16-bit and 64-bit compares in the decoder and translator (the reference
|
||||
interpreters accept the subset in 2a).
|
||||
- 16-bit compares in the decoder and translator (the reference interpreters
|
||||
accept the subset in 2a).
|
||||
- SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs,
|
||||
M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct.
|
||||
- A normal-SGPR SRC0 without a known value, when EXEC_LO != 0.
|
||||
@@ -148,14 +148,15 @@ Acceptance rules for one compare:
|
||||
or VCC state), and VCC_LO becomes known 0.
|
||||
- EXEC_LO != 0: VSRC1 and a VGPR SRC0 must be initialized and not pending a
|
||||
load; a normal-SGPR SRC0 must be known; a `vcc_lo` SRC0 must be known or
|
||||
lane-derived (uninitialized is rejected). VCC_LO becomes lane-derived.
|
||||
lane-derived (uninitialized is rejected). The 64-bit forms check both words
|
||||
of each register pair. VCC_LO becomes lane-derived.
|
||||
|
||||
While VCC_LO is lane-derived it may be read only by:
|
||||
|
||||
1. `s_cbranch_vccz` (6);
|
||||
2. `v_mov_b32_e32 vD, vcc_lo`, which writes the 32-bit mask into vD of active
|
||||
lanes (inactive lanes keep vD, as for any partial-EXEC move);
|
||||
3. SRC0 of a supported compare (`v_cmp_* vcc_lo, vcc_lo, vN`), which reads the
|
||||
3. SRC0 of a supported 32-bit compare (`v_cmp_* vcc_lo, vcc_lo, vN`), which reads the
|
||||
old VCC_LO in every active lane before the new value is written.
|
||||
4. SRC0 of a registry VOP2 integer form (for example
|
||||
`v_add_nc_u32_e32 vD, vcc_lo, vN`), which reads the 32-bit mask in every
|
||||
@@ -252,10 +253,15 @@ programs, plus 2 mask-chain programs (252 in all), and the F/T fixture (253) mat
|
||||
run in `vopc_f_t_match_the_guide_on_native_metal`.
|
||||
|
||||
The 16-bit and 64-bit oracle (`tests/validation/tests/vopc_wide.rs`) checks
|
||||
6,212 lane cases on both reference interpreters, plus 1,208 rejections and the
|
||||
13 neighbouring opcodes, and that the production compiler still rejects all 28
|
||||
forms. Its native Metal test stays ignored (and skipped by `scripts/test-gpu.sh`)
|
||||
until the translator implements these forms. Deliberately broken copies of both
|
||||
6,212 cases on both reference interpreters, plus 1,208 rejections and 13
|
||||
neighbouring opcodes. CPU tests check compilation of 1,572 16-bit and 4,640
|
||||
64-bit cases, plus compiler rejection of out-of-contract programs. LLVM
|
||||
assembled `vector-compare-16.s` and `vector-compare-64.s` cover all 28 opcodes
|
||||
in the decoder's fixture inventory. The native Metal gate runs both
|
||||
`vopc16_match_the_guide_on_native_metal` and
|
||||
`vopc64_match_the_guide_on_native_metal`. On a local Apple M5 with API and
|
||||
shader validation, all 4,640 64-bit cases (3,818 programs) agree with the
|
||||
oracle. On a local Apple M5 under API and shader validation, all 1,572 16-bit cases (1,420 programs) agree; independent acceptance is pending. Deliberately broken copies of both
|
||||
interpreters (16-bit reads of 32 bits, swapped pair halves, zero-extended
|
||||
inline integers, flipped signedness, reads under empty EXEC and others) each
|
||||
fail it.
|
||||
@@ -268,14 +274,12 @@ the translator with a stale VCC under empty EXEC (CPU), and, on Metal, with
|
||||
swapped signedness, without the EXEC mask, without the absent-lane bound
|
||||
(shader validation aborts on the out-of-range read) or with an inverted join.
|
||||
|
||||
Evidence class: agreement with a specification-derived reference, run
|
||||
locally on Apple M5 Pro. It is not agreement with RDNA 2 or Xbox hardware.
|
||||
The 32-bit readback evidence is local agreement with a specification-derived
|
||||
reference on Apple M5 Pro. There is no RDNA 2 or Xbox hardware evidence.
|
||||
|
||||
## 10. Limitations
|
||||
|
||||
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares. 16-bit and
|
||||
64-bit compares exist only in the reference interpreters (2a); native Metal
|
||||
agreement for them is not shown.
|
||||
- Wave32 only. No `v_cmpx`, SDWA, DPP or float compares. VOP3 encodings cover the 32-bit compares only.
|
||||
- A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there
|
||||
is no divergent execution. That needs its own contract.
|
||||
- The skipped region of a runtime `s_cbranch_vccz` holds only integer vector
|
||||
@@ -284,3 +288,38 @@ locally on Apple M5 Pro. It is not agreement with RDNA 2 or Xbox hardware.
|
||||
- Each thread recomputes up to 32 lanes per compare. The cost grows with the
|
||||
compare's dependency chain. That is fine for fixtures, and no performance is
|
||||
claimed.
|
||||
|
||||
## 11. VOP3A encoding (`_e64`)
|
||||
|
||||
All sixteen 32-bit signed and unsigned compares in section 2 also have a 64-bit
|
||||
VOP3A encoding. The pinned AMD XML supplies each opcode. Bits 7:0 of the first
|
||||
word are the scalar destination selector (SDST), in the field named VDST.
|
||||
Selectors 0–105 name scalar general-purpose registers (SGPRs), and 106 names
|
||||
`vcc_lo`. All other destinations are rejected. Both SRC0 and SRC1 must name
|
||||
vector general-purpose registers (VGPRs), and the unused SRC2 must be the
|
||||
assembler's inline-zero selector (128). ABS, OP_SEL, CLAMP, OMOD and NEG must
|
||||
be clear. The guide describes CLAMP on compares as enabling floating-point
|
||||
exception signaling (§6.5, p. 48 and §12.9.1, p. 162).
|
||||
|
||||
The AMD guide's compare-specific text (§3.9, pp. 19–20 and §13.3.3, p. 252)
|
||||
specifies an SGPR destination for this encoding. The generic VDST label in
|
||||
§12.9.1 (p. 162) and §13.3.4 Table 82 (pp. 257–258) describes the VOP3A field
|
||||
as a VGPR destination. The pinned XML identifies VDST for these compares as
|
||||
`OPR_SREG`, with the Wave64 pair described by `FMT_NUM_M64`. The Wave32 write
|
||||
occupies one 32-bit SGPR. The guide defines 32 work-items in §2.1 (pp. 7–8),
|
||||
32-bit SGPRs in §3.1 Table 2 (p. 12) and one compare result bit per lane in
|
||||
§12.9 (p. 150). Wave64 stays unsupported.
|
||||
|
||||
LLVM 23 `llvm-mc` for gfx1030 with `+wavefrontsize32` assembles
|
||||
`v_cmp_eq_u32_e64 s4, v1, v2` as bytes `04 00 c2 d4 01 05 02 02`.
|
||||
Selecting `vcc_lo` changes the first byte to `6a`. The decoder tests cover
|
||||
the assembler's words for all sixteen forms. This is encoding evidence.
|
||||
|
||||
The compare replaces all 32 bits of SDST with the lane mask from section 3,
|
||||
including zero bits for inactive and absent lanes. It leaves SCC and EXEC
|
||||
unchanged. VCC is written only when SDST selects `vcc_lo`, which uses the
|
||||
same lowering and consumers as the VOPC form, including `s_cbranch_vccz`.
|
||||
Every other SDST is tracked as a runtime-only SGPR result, including under
|
||||
empty EXEC. Translation rejects later reads of that result, including reads
|
||||
through resource descriptors. The runtime branch region rules in section 6
|
||||
also apply here.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Wave32 vector unary integer operations and swap
|
||||
|
||||
Xenora translates six gfx1030 VOP1 integer forms for the synthetic Wave32 compute
|
||||
ABI. The AMD RDNA 2 ISA Reference Guide defines the operations in section 12.8,
|
||||
the encoding in section 13.3.2, and the execution mask (EXEC) in section 3.3.
|
||||
|
||||
| Form | Result in each active lane |
|
||||
| --- | --- |
|
||||
| `v_not_b32_e32` | Complement all 32 bits. |
|
||||
| `v_bfrev_b32_e32` | Reverse the order of the 32 bits. |
|
||||
| `v_ffbh_u32_e32` | Count leading zeros. Return all ones if the source is zero. |
|
||||
| `v_ffbl_b32_e32` | Count trailing zeros. Return all ones if the source is zero. |
|
||||
| `v_ffbh_i32_e32` | Count leading bits equal to the sign bit. Return all ones if all bits match. |
|
||||
| `v_swap_b32` | Exchange the old values of two vector general-purpose registers (VGPRs). A register swapped with itself keeps its value. |
|
||||
|
||||
The unary forms accept a VGPR, scalar register `s0`–`s105`, `vcc_lo` (the low
|
||||
half of the vector condition code), inline integer `-16`–`64`, or a literal
|
||||
word as SRC0. Swap requires a VGPR as SRC0 because it writes both operands.
|
||||
Both operands of swap must be initialized when EXEC is nonzero. The compute
|
||||
ABI reserves `v0` for indexing and requires waiting for buffer loads before
|
||||
using or overwriting their destination. Inactive lanes retain their old
|
||||
values. The six forms leave EXEC, VCC and the scalar condition code (SCC)
|
||||
unchanged.
|
||||
|
||||
The compiler emits per-thread Metal Shading Language for unary operations.
|
||||
For swap it captures both old values in the intermediate representation before
|
||||
updating either register binding. Under partial EXEC, each register receives
|
||||
its own lane merge.
|
||||
|
||||
The [guide-derived oracle](../../tests/validation/tests/vop1_integer.rs) checks
|
||||
the 752 accepted cases' outputs against its expected values on each CPU
|
||||
interpreter and, through the translator, on native Metal (Apple M5, API and
|
||||
shader validation on: 752 cases in 613 programs). A CPU test checks that the
|
||||
compiler accepts every case and refuses each of the 610 rejected programs at
|
||||
the same instruction offset as the interpreters. The
|
||||
[LLVM-assembled fixture](../../fixtures/rdna2/vector-unary.s) exercises all
|
||||
six forms with a partial EXEC swap. Independent acceptance of the
|
||||
translator is pending. Xbox hardware agreement is unknown.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Wave32 vector select, carry and borrow
|
||||
|
||||
The gfx1030 compute fixture ABI supports four 32-bit vector two-operand
|
||||
instruction (VOP2) forms that read the vector condition code (VCC).
|
||||
In Wave32, bit `n` of `VCC_LO` supplies lane `n`'s input `c`.
|
||||
The AMD RDNA 2 guide describes the operations in section 12.7, the VOP2 word
|
||||
in section 13.3.1, and the execution and condition masks in sections 3.3 and 3.9.
|
||||
|
||||
| Instruction | Active lane destination | Active lane VCC output |
|
||||
| --- | --- | --- |
|
||||
| `v_cndmask_b32_e32` | S1 if c is set, S0 otherwise | Preserved |
|
||||
| `v_add_co_ci_u32_e32` | Low 32 bits of S0 + S1 + c | Exact sum reaches 2³² |
|
||||
| `v_sub_co_ci_u32_e32` | Low 32 bits of S0 − S1 − c | S1 + c exceeds S0 |
|
||||
| `v_subrev_co_ci_u32_e32` | Low 32 bits of S1 − S0 − c | S0 + c exceeds S1 |
|
||||
|
||||
Section 12.7 prints a reverse-subtract flag expression that conflicts with its
|
||||
prose and destination equation. Xenora uses unsigned borrow from the stated
|
||||
reverse subtraction, consistent with section 12.12's `v_subrev_co_u32` when
|
||||
the incoming borrow is zero.
|
||||
|
||||
Inactive lanes retain the old vector destination (VDST). Section 3.9
|
||||
describes a fully written VCC mask and defines carry-out in terms of executing
|
||||
lanes. Under that reading, inactive lanes contribute zero to a carry or borrow
|
||||
output. Section 3.3 says scalar-register-writing vector ALU instructions
|
||||
still execute under empty EXEC, so the carry output is a zero mask.
|
||||
The synthetic ABI also zeros
|
||||
absent lanes in a final short wave when it constructs a new mask.
|
||||
The scalar condition code (SCC) and EXEC are preserved by these forms.
|
||||
|
||||
The general SRC0 subset includes vector general-purpose registers (VGPRs),
|
||||
scalar registers s0–s105, `vcc_lo`, inline integers and one literal word.
|
||||
VSRC1 and VDST are VGPRs. Translated scalar sources must be known or supplied
|
||||
by a translated VCC result. The pinned XML lists the VCC input on all four
|
||||
forms and an additional VCC output on the three arithmetic forms. VOP3
|
||||
encodings with explicit scalar conditions and VOP3B carry-out-only forms
|
||||
are outside this subset.
|
||||
|
||||
The Metal lowering reuses the compare mask's replay of the current wave's
|
||||
input lanes to form carry and borrow masks. The original `vector-vcc.s`
|
||||
fixture chains all four operations. LLVM checks encoding, and the guide-derived
|
||||
oracle checks both CPU interpreters. `vop2_vcc_matches_guide_on_native_metal` passes on a local
|
||||
Apple M5 under API and shader validation; independent acceptance is pending. The expectations are derived from the public AMD specification (class B).
|
||||
+978
-6
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
||||
# Testing and acceptance
|
||||
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
|
||||
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
|
||||
- [Baseline acceptance](phase-02-baseline.md) and [Phase 01 assurance](phase01-assurance.md) — Candidate-specific evidence.
|
||||
- [Independent reviews](review-log.md) — Review findings and acceptance records.
|
||||
- [Mutation testing](mutation.md) and [benchmark protocol](benchmarks.md) — Sensitivity and timing requirements.
|
||||
- [Infrastructure QA tooling](infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
|
||||
@@ -1,5 +1,12 @@
|
||||
# Independent review
|
||||
|
||||
## gfx1030 form acceptance
|
||||
|
||||
Use the [AMD RDNA2 desktop GPU (gfx1030) form acceptance rule](shader-form-acceptance.md) for entries that
|
||||
promote instruction forms to `fixture verified`. Record only completed runs with
|
||||
a named commit, independent runner, host, exact commands and real counts. Raw
|
||||
logs stay under ignored `artifacts/acceptance/<commit>/`.
|
||||
|
||||
## R1. First synthetic compute checkpoint, 2026-11-22
|
||||
|
||||
Reviewed the integrated working tree before a candidate commit. The findings below cover the first checkpoint.
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
# AMD RDNA2 desktop GPU (gfx1030) form acceptance
|
||||
|
||||
This is the promotion rule for AMD RDNA2 desktop GPU (`gfx1030`) instruction
|
||||
forms in [`docs/status.toml`](../status.toml). It implements the documentation
|
||||
step of [#302](https://github.com/ranveersoni98/Xenora/issues/302). It does not
|
||||
claim Xbox-hardware verification or commercial-game compatibility.
|
||||
|
||||
The **LLVM three-way decoder check** is the ignored `llvm-mc` comparison in
|
||||
[`crates/decoder/tests/gfx1030.rs`](../../crates/decoder/tests/gfx1030.rs). It
|
||||
compares Xenora's decoder with LLVM's gfx1030 decoder over the fixture and
|
||||
probe encodings; it is encoding evidence, not GPU-semantics evidence.
|
||||
|
||||
## Status meanings
|
||||
|
||||
| Status | Meaning |
|
||||
| --- | --- |
|
||||
| `local known-answer test passed` | The implementation's CPU known-answer test passed locally. This is not independent acceptance. |
|
||||
| `local Apple M5 readback passed; acceptance pending` | A local native Metal readback passed with validation, but the independence and evidence rules below are incomplete. |
|
||||
| `fixture verified on Apple M5` | The host-qualified spelling used by three existing rows. `scripts/audit/status.py` treats it as equivalent to `fixture verified`; existing rows do not need re-acceptance solely for this wording. New entries should normally use `fixture verified` and record the host in the review log. |
|
||||
| `fixture verified` | The form or documented family batch passed independent acceptance at a named commit, with CPU, LLVM and native Metal evidence recorded. |
|
||||
|
||||
A skipped test is not a pass. A shader compile without readback is not GPU
|
||||
verification. Agreement with a spec-derived reference is not agreement with
|
||||
Xbox hardware.
|
||||
|
||||
## Independence
|
||||
|
||||
> **Proposed policy, pending maintainer confirmation.** The independence rule in
|
||||
> this section is the proposal from #302. Do not use it to promote forms until
|
||||
> the maintainer confirms or revises it.
|
||||
|
||||
The person running the acceptance pass must not be the author of the pull
|
||||
request that added the form being accepted. The runner may use the existing
|
||||
tests and commands, but must record their own results and review the evidence.
|
||||
If the maintainer runs the pass for forms they authored, the review-log entry
|
||||
must say so explicitly; that exception is not silent self-certification.
|
||||
|
||||
The expected values used by the test must remain independent of the production
|
||||
decoder, translator or Metal backend. Do not change fixtures, thresholds or test
|
||||
filters to make a form pass.
|
||||
|
||||
## Acceptance procedure
|
||||
|
||||
1. **Use a clean named commit.** Start from a clean checkout of `main` at the
|
||||
commit being accepted. Record the full commit hash. Do not accept a working
|
||||
tree with uncommitted changes.
|
||||
2. **Name the scope.** List each form, or a family batch with an explicit list of
|
||||
forms, covered by the pass. A family name alone is not enough.
|
||||
3. **Run the standard gates.** Format, Clippy, workspace tests, fixture checks,
|
||||
the LLVM three-way decoder check and the native GPU suite must pass. Record
|
||||
exact commands, environment variables and pass/fail/skip counts.
|
||||
4. **Run the form's CPU and Metal tests.** The CPU known-answer/reference tests
|
||||
and the native Metal readback must both pass. Metal API and shader validation
|
||||
must be enabled. Use a targeted test filter where useful, but keep the full
|
||||
standard-gate result for the same commit.
|
||||
5. **Check negative cases.** Unsupported encodings, malformed inputs and any
|
||||
documented rejection cases for the form must still pass.
|
||||
6. **Save raw logs.** Put raw output under ignored
|
||||
`artifacts/acceptance/<commit>/`. Do not commit raw logs.
|
||||
7. **Write the review-log summary.** Add an entry to
|
||||
[`review-log.md`](review-log.md) with the commit, runner's GitHub login, host,
|
||||
scope, exact commands or log path, and CPU/LLVM/Metal results. A reviewer
|
||||
confirms the entry if the runner is not the maintainer.
|
||||
8. **Promote only passed forms.** Change `cpu` and `gpu` in `docs/status.toml`
|
||||
only for forms covered by a passing entry. Regenerate the status tables and
|
||||
progress graphic, then run `python3 scripts/audit/status.py --check`.
|
||||
|
||||
## Standard gate set
|
||||
|
||||
Run on native Apple Silicon. The exact host and tool versions belong in the
|
||||
review-log entry.
|
||||
|
||||
```sh
|
||||
export CARGO_BUILD_JOBS=2
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
scripts/assemble-fixture.sh --check
|
||||
LLVM_BIN="$(brew --prefix llvm)/bin" \
|
||||
cargo test --locked -p xenora-decoder --test gfx1030 -- --include-ignored --nocapture
|
||||
cargo test --locked -p xenora-semantic-review
|
||||
scripts/test-gpu.sh
|
||||
python3 scripts/audit/status.py --check
|
||||
```
|
||||
|
||||
For a targeted semantic-review pass, record the filter and use the same Metal
|
||||
validation environment as `scripts/test-gpu.sh`:
|
||||
|
||||
```sh
|
||||
cargo test --locked -p xenora-semantic-review <cpu-test-filter>
|
||||
MTL_DEBUG_LAYER=1 \
|
||||
MTL_SHADER_VALIDATION=1 \
|
||||
MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 \
|
||||
MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1 \
|
||||
cargo test --locked -p xenora-semantic-review <native-metal-test-filter> \
|
||||
-- --ignored --exact --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
A targeted filter does not replace the standard gate set; it attributes the
|
||||
result to a form or family batch.
|
||||
|
||||
## Review-log entry
|
||||
|
||||
Use one row per commit and scope. Add rows to
|
||||
[`review-log.md`](review-log.md); keep raw output only in `artifacts/`.
|
||||
|
||||
| Date | Commit | Runner (GitHub login) | Host and tools | Forms or batch | Commands / raw log | CPU | LLVM | Metal | Review |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| YYYY-MM-DD | full SHA | @login | Mac, macOS, Xcode, Rust, LLVM | explicit form list | exact commands and `artifacts/acceptance/<commit>/` path | pass/fail/skip counts | pass/fail counts | pass/fail/skip counts; validation on | reviewer GitHub login or maintainer exception |
|
||||
|
||||
Do not write `pass` without counts. Do not count a skipped native test as Metal
|
||||
evidence.
|
||||
|
||||
## Promotion and failures
|
||||
|
||||
After a passing entry, set the accepted rows to `fixture verified` and regenerate:
|
||||
|
||||
```sh
|
||||
python3 scripts/audit/status.py
|
||||
python3 scripts/audit/status.py --check
|
||||
```
|
||||
|
||||
If any required check fails or skips, leave the form pending. Record the commit,
|
||||
host, command and failure in the review log, and open a separate issue for the
|
||||
failure. Do not weaken the test or change the expected result in the acceptance
|
||||
pass.
|
||||
|
||||
The automated status-check enforcement proposed in #302 is a separate change.
|
||||
Until it lands, reviewers must enforce the review-log requirement manually.
|
||||
@@ -0,0 +1,26 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0018: branch.uniform 0x0020 taken=false
|
||||
0024: branch.uniform 0x002c taken=true
|
||||
0030: branch.uniform 0x0038 taken=false
|
||||
003c: branch.uniform 0x0044 taken=true
|
||||
0048: branch.uniform 0x0050 taken=false
|
||||
0054: branch.uniform 0x005c taken=false
|
||||
0060: branch.uniform 0x0068 taken=false
|
||||
006c: branch.uniform 0x0078 taken=true
|
||||
007c: branch.uniform 0x0088 taken=false
|
||||
008c: branch.uniform 0x0098 taken=true
|
||||
009c: branch.uniform 0x00a8 taken=false
|
||||
00ac: branch.uniform 0x00b8 taken=false
|
||||
00c8: branch.uniform 0x00d4 taken=false
|
||||
00d8: branch.uniform 0x00e4 taken=false
|
||||
00e8: branch.uniform 0x00f4 taken=false
|
||||
00f8: branch.uniform 0x0104 taken=true
|
||||
0118: t17 = const.u32 0x00007d75
|
||||
011c: t18 = const.u32 0xc000ffff
|
||||
0120: t19 = xor.b32 t18, t17
|
||||
0124: t20 = const.u32 0x7fffffff
|
||||
0128: t21 = xor.b32 t20, t19
|
||||
012c: t22 = const.u32 0xffffff00
|
||||
0130: t23 = xor.b32 t22, t21
|
||||
0134: t24 = xor.b32 t0, t23
|
||||
0138: store.u32 output[index], t24
|
||||
@@ -0,0 +1,17 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t17 = 0x00007d75u;
|
||||
uint t18 = 0xc000ffffu;
|
||||
uint t19 = t18 ^ t17;
|
||||
uint t20 = 0x7fffffffu;
|
||||
uint t21 = t20 ^ t19;
|
||||
uint t22 = 0xffffff00u;
|
||||
uint t23 = t22 ^ t21;
|
||||
uint t24 = t0 ^ t23;
|
||||
output[index] = t24;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = not.b32 t0
|
||||
0018: t2 = merge.lanes mask=0xaaaaaaaa, t1, t0
|
||||
0018: t3 = merge.lanes mask=0xaaaaaaaa, t0, t1
|
||||
0020: t4 = brev.b32 t2
|
||||
0024: t5 = ffbh.u32 t3
|
||||
0028: t6 = ffbl.b32 t2
|
||||
002c: t7 = ffbh.i32 t3
|
||||
0030: t8 = xor.b32 t4, t5
|
||||
0034: t9 = xor.b32 t6, t8
|
||||
0038: t10 = xor.b32 t7, t9
|
||||
003c: store.u32 output[index], t10
|
||||
@@ -0,0 +1,19 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = ~t0;
|
||||
uint t2 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t1 : t0;
|
||||
uint t3 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t0 : t1;
|
||||
uint t4 = reverse_bits(t2);
|
||||
uint t5 = t3 == 0u ? 0xffffffffu : clz(t3);
|
||||
uint t6 = t2 == 0u ? 0xffffffffu : ctz(t2);
|
||||
uint t7 = (t3 == 0u || t3 == 0xffffffffu) ? 0xffffffffu : clz(t3 ^ (0u - (t3 >> 31u)));
|
||||
uint t8 = t4 ^ t5;
|
||||
uint t9 = t6 ^ t8;
|
||||
uint t10 = t7 ^ t9;
|
||||
output[index] = t10;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000000
|
||||
000c: t2 = wave.mask v_cmp_eq_u32_e32 t1, t0 exec=0xffffffff
|
||||
0010: t3 = const.u32 0xffffffff
|
||||
0010: t4 = vcc.Select t3, t0, t2
|
||||
0014: t5 = const.u32 0x00000001
|
||||
0014: t6 = vcc.AddCarry.flag t5, t4, t2
|
||||
0014: t7 = wave.carry t6 exec=0xffffffff
|
||||
0014: t8 = vcc.AddCarry t5, t4, t2
|
||||
0018: t9 = const.u32 0x00000000
|
||||
0018: t10 = vcc.SubtractBorrow.flag t9, t8, t7
|
||||
0018: t11 = wave.carry t10 exec=0xffffffff
|
||||
0018: t12 = vcc.SubtractBorrow t9, t8, t7
|
||||
001c: t13 = const.u32 0xfffffffe
|
||||
001c: t14 = vcc.SubtractBorrow.flag t12, t13, t11
|
||||
001c: t15 = wave.carry t14 exec=0xffffffff
|
||||
001c: t16 = vcc.SubtractBorrow t12, t13, t11
|
||||
0024: store.u32 output[index], t15
|
||||
@@ -0,0 +1,63 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]],
|
||||
uint grid [[threads_per_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = 0x00000000u;
|
||||
uint t2 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (t1 == l0) ? 1u : 0u;
|
||||
t2 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t3 = 0xffffffffu;
|
||||
uint t4 = ((t2 >> (index & 31u)) & 1u) != 0u ? t0 : t3;
|
||||
uint t5 = 0x00000001u;
|
||||
uint t6 = uint((ulong(t5) + ulong(t4) + ((t2 >> (index & 31u)) & 1u)) >> 32u);
|
||||
uint t7 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
|
||||
uint l6 = uint((ulong(t5) + ulong(l4) + ((t2 >> lane) & 1u)) >> 32u);
|
||||
uint pass = l6;
|
||||
t7 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t8 = t5 + t4 + ((t2 >> (index & 31u)) & 1u);
|
||||
uint t9 = 0x00000000u;
|
||||
uint t10 = uint(ulong(t8) + ((t7 >> (index & 31u)) & 1u) > ulong(t9));
|
||||
uint t11 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
|
||||
uint l8 = t5 + l4 + ((t2 >> lane) & 1u);
|
||||
uint l10 = uint(ulong(l8) + ((t7 >> lane) & 1u) > ulong(t9));
|
||||
uint pass = l10;
|
||||
t11 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t12 = t9 - t8 - ((t7 >> (index & 31u)) & 1u);
|
||||
uint t13 = 0xfffffffeu;
|
||||
uint t14 = uint(ulong(t13) + ((t11 >> (index & 31u)) & 1u) > ulong(t12));
|
||||
uint t15 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
|
||||
uint l8 = t5 + l4 + ((t2 >> lane) & 1u);
|
||||
uint l12 = t9 - l8 - ((t7 >> lane) & 1u);
|
||||
uint l14 = uint(ulong(t13) + ((t11 >> lane) & 1u) > ulong(l12));
|
||||
uint pass = l14;
|
||||
t15 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t16 = t12 - t13 - ((t11 >> (index & 31u)) & 1u);
|
||||
output[index] = t15;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000000
|
||||
0010: t2 = const.u32 0x00000001
|
||||
0014: t3 = const.u32 0x40000001
|
||||
001c: t4 = const.u32 0x00000001
|
||||
0020: t5 = wave.mask v_cmp_f_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
002c: t6 = lshl.b32 t1, t2
|
||||
0030: t7 = xor.b32 t6, t5
|
||||
0034: t8 = wave.mask v_cmp_lt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0040: t9 = lshl.b32 t7, t2
|
||||
0044: t10 = xor.b32 t9, t8
|
||||
0048: t11 = wave.mask v_cmp_eq_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0054: t12 = lshl.b32 t10, t2
|
||||
0058: t13 = xor.b32 t12, t11
|
||||
005c: t14 = wave.mask v_cmp_le_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0068: t15 = lshl.b32 t13, t2
|
||||
006c: t16 = xor.b32 t15, t14
|
||||
0070: t17 = wave.mask v_cmp_gt_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
007c: t18 = lshl.b32 t16, t2
|
||||
0080: t19 = xor.b32 t18, t17
|
||||
0084: t20 = wave.mask v_cmp_ne_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0090: t21 = lshl.b32 t19, t2
|
||||
0094: t22 = xor.b32 t21, t20
|
||||
0098: t23 = wave.mask v_cmp_ge_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
00a4: t24 = lshl.b32 t22, t2
|
||||
00a8: t25 = xor.b32 t24, t23
|
||||
00ac: t26 = wave.mask v_cmp_t_i32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
00b8: t27 = lshl.b32 t25, t2
|
||||
00bc: t28 = xor.b32 t27, t26
|
||||
00c0: t29 = wave.mask v_cmp_f_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
00cc: t30 = lshl.b32 t28, t2
|
||||
00d0: t31 = xor.b32 t30, t29
|
||||
00d4: t32 = wave.mask v_cmp_lt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
00e0: t33 = lshl.b32 t31, t2
|
||||
00e4: t34 = xor.b32 t33, t32
|
||||
00e8: t35 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
00f4: t36 = lshl.b32 t34, t2
|
||||
00f8: t37 = xor.b32 t36, t35
|
||||
00fc: t38 = wave.mask v_cmp_le_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0108: t39 = lshl.b32 t37, t2
|
||||
010c: t40 = xor.b32 t39, t38
|
||||
0110: t41 = wave.mask v_cmp_gt_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
011c: t42 = lshl.b32 t40, t2
|
||||
0120: t43 = xor.b32 t42, t41
|
||||
0124: t44 = wave.mask v_cmp_ne_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0130: t45 = lshl.b32 t43, t2
|
||||
0134: t46 = xor.b32 t45, t44
|
||||
0138: t47 = wave.mask v_cmp_ge_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0144: t48 = lshl.b32 t46, t2
|
||||
0148: t49 = xor.b32 t48, t47
|
||||
014c: t50 = wave.mask v_cmp_t_u32_e64 t0, t3 -> vcc_lo exec=0xffffffff
|
||||
0158: t51 = lshl.b32 t49, t2
|
||||
015c: t52 = xor.b32 t51, t50
|
||||
0160: t53 = wave.mask v_cmp_eq_u32_e64 t0, t3 -> s8 exec=0xffffffff
|
||||
0168: t54 = wave.mask v_cmp_gt_u32_e64 t3, t0 -> vcc_lo exec=0xffffffff
|
||||
0170: branch.vccz t54 -> 0x0178
|
||||
0174: t56 = xor.b32 t4, t52
|
||||
0178: t57 = join.vccz t54, t56, t52
|
||||
0178: store.u32 output[index], t57
|
||||
@@ -0,0 +1,188 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]],
|
||||
uint grid [[threads_per_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = 0x00000000u;
|
||||
uint t2 = 0x00000001u;
|
||||
uint t3 = 0x40000001u;
|
||||
uint t4 = 0x00000001u;
|
||||
uint t5 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (false) ? 1u : 0u;
|
||||
t5 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t6 = t1 << (t2 & 31u);
|
||||
uint t7 = t6 ^ t5;
|
||||
uint t8 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) < as_type<int>(t3)) ? 1u : 0u;
|
||||
t8 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t9 = t7 << (t2 & 31u);
|
||||
uint t10 = t9 ^ t8;
|
||||
uint t11 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) == as_type<int>(t3)) ? 1u : 0u;
|
||||
t11 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t12 = t10 << (t2 & 31u);
|
||||
uint t13 = t12 ^ t11;
|
||||
uint t14 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) <= as_type<int>(t3)) ? 1u : 0u;
|
||||
t14 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t15 = t13 << (t2 & 31u);
|
||||
uint t16 = t15 ^ t14;
|
||||
uint t17 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) > as_type<int>(t3)) ? 1u : 0u;
|
||||
t17 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t18 = t16 << (t2 & 31u);
|
||||
uint t19 = t18 ^ t17;
|
||||
uint t20 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) != as_type<int>(t3)) ? 1u : 0u;
|
||||
t20 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t21 = t19 << (t2 & 31u);
|
||||
uint t22 = t21 ^ t20;
|
||||
uint t23 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (as_type<int>(l0) >= as_type<int>(t3)) ? 1u : 0u;
|
||||
t23 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t24 = t22 << (t2 & 31u);
|
||||
uint t25 = t24 ^ t23;
|
||||
uint t26 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (true) ? 1u : 0u;
|
||||
t26 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t27 = t25 << (t2 & 31u);
|
||||
uint t28 = t27 ^ t26;
|
||||
uint t29 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (false) ? 1u : 0u;
|
||||
t29 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t30 = t28 << (t2 & 31u);
|
||||
uint t31 = t30 ^ t29;
|
||||
uint t32 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 < t3) ? 1u : 0u;
|
||||
t32 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t33 = t31 << (t2 & 31u);
|
||||
uint t34 = t33 ^ t32;
|
||||
uint t35 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 == t3) ? 1u : 0u;
|
||||
t35 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t36 = t34 << (t2 & 31u);
|
||||
uint t37 = t36 ^ t35;
|
||||
uint t38 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 <= t3) ? 1u : 0u;
|
||||
t38 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t39 = t37 << (t2 & 31u);
|
||||
uint t40 = t39 ^ t38;
|
||||
uint t41 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 > t3) ? 1u : 0u;
|
||||
t41 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t42 = t40 << (t2 & 31u);
|
||||
uint t43 = t42 ^ t41;
|
||||
uint t44 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 != t3) ? 1u : 0u;
|
||||
t44 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t45 = t43 << (t2 & 31u);
|
||||
uint t46 = t45 ^ t44;
|
||||
uint t47 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 >= t3) ? 1u : 0u;
|
||||
t47 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t48 = t46 << (t2 & 31u);
|
||||
uint t49 = t48 ^ t47;
|
||||
uint t50 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (true) ? 1u : 0u;
|
||||
t50 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t51 = t49 << (t2 & 31u);
|
||||
uint t52 = t51 ^ t50;
|
||||
uint t53 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (l0 == t3) ? 1u : 0u;
|
||||
t53 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t54 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (t3 > l0) ? 1u : 0u;
|
||||
t54 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t56 = t4 ^ t52;
|
||||
uint t57 = t54 != 0u ? t56 : t52;
|
||||
output[index] = t57;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = mul24.i32 t0, t0
|
||||
0014: t2 = mulhi24.i32 t1, t0
|
||||
001c: t3 = mul24.u32 t1, t0
|
||||
0024: t4 = mulhi24.u32 t3, t0
|
||||
002c: t5 = min.i32 t0, t1
|
||||
0034: t6 = max.i32 t0, t3
|
||||
003c: t7 = min.u32 t2, t0
|
||||
0044: t8 = max.u32 t4, t1
|
||||
004c: t9 = xnor.b32 t0, t4
|
||||
0054: t10 = sub.u32 t5, t9
|
||||
005c: t11 = sub.u32 t8, t0
|
||||
0064: t12 = xor.b32 t1, t2
|
||||
0068: t13 = xor.b32 t3, t12
|
||||
006c: t14 = xor.b32 t4, t13
|
||||
0070: t15 = xor.b32 t5, t14
|
||||
0074: t16 = xor.b32 t6, t15
|
||||
0078: t17 = xor.b32 t7, t16
|
||||
007c: t18 = xor.b32 t8, t17
|
||||
0080: t19 = xor.b32 t9, t18
|
||||
0084: t20 = xor.b32 t10, t19
|
||||
0088: t21 = xor.b32 t11, t20
|
||||
008c: store.u32 output[index], t21
|
||||
@@ -0,0 +1,30 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = as_type<uint>((as_type<int>(t0 << 8u) >> 8)) * as_type<uint>((as_type<int>(t0 << 8u) >> 8));
|
||||
uint t2 = as_type<uint>(mulhi((as_type<int>(t1 << 8u) >> 8), (as_type<int>(t0 << 8u) >> 8)));
|
||||
uint t3 = (t1 & 0x00ffffffu) * (t0 & 0x00ffffffu);
|
||||
uint t4 = mulhi((t3 & 0x00ffffffu), (t0 & 0x00ffffffu));
|
||||
uint t5 = as_type<uint>(min(as_type<int>(t0), as_type<int>(t1)));
|
||||
uint t6 = as_type<uint>(max(as_type<int>(t0), as_type<int>(t3)));
|
||||
uint t7 = min(t2, t0);
|
||||
uint t8 = max(t4, t1);
|
||||
uint t9 = ~(t0 ^ t4);
|
||||
uint t10 = t5 - t9;
|
||||
uint t11 = t8 - t0;
|
||||
uint t12 = t1 ^ t2;
|
||||
uint t13 = t3 ^ t12;
|
||||
uint t14 = t4 ^ t13;
|
||||
uint t15 = t5 ^ t14;
|
||||
uint t16 = t6 ^ t15;
|
||||
uint t17 = t7 ^ t16;
|
||||
uint t18 = t8 ^ t17;
|
||||
uint t19 = t9 ^ t18;
|
||||
uint t20 = t10 ^ t19;
|
||||
uint t21 = t11 ^ t20;
|
||||
output[index] = t21;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Generate the original PE32+ delay-load import fixture without an x86 toolchain.
|
||||
|
||||
The image has one ordinary import DLL and two delay-loaded DLLs, each with a
|
||||
named import and one of them with an import by ordinal. It follows Microsoft's
|
||||
PE format specification ("The .idata Section" and "Delay-Load Import Tables
|
||||
(Image Only)"). It is for static inspection: the entry point returns at once and
|
||||
nothing calls an import.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from struct import pack_into
|
||||
|
||||
BASE = 0x140000000
|
||||
TEXT, RDATA, DATA = 0x1000, 0x2000, 0x3000
|
||||
# File offset of each section's data, after the 0x400-byte headers.
|
||||
RAW = {TEXT: 0x400, RDATA: 0x600, DATA: 0xA00}
|
||||
ORDINAL = 1 << 63
|
||||
|
||||
# Ordinary imports, in .rdata.
|
||||
IMPORT_DIRECTORY = RDATA
|
||||
LOOKUP, IAT = RDATA + 0x30, RDATA + 0x50
|
||||
ORDINARY_DLL, ORDINARY_NAME = RDATA + 0x70, RDATA + 0x90
|
||||
|
||||
# Delay-load names and name tables, in .rdata before their directory so that a
|
||||
# file cut inside the directory still holds everything the first entry names.
|
||||
NAMES_A, NAMES_B = RDATA + 0x100, RDATA + 0x118
|
||||
DELAY_DLL_A, DELAY_DLL_B = RDATA + 0x130, RDATA + 0x150
|
||||
DELAY_NAME_A, DELAY_NAME_B = RDATA + 0x170, RDATA + 0x190
|
||||
DELAY_DIRECTORY = RDATA + 0x200
|
||||
|
||||
# Delay-load address tables and module handles, in writable .data.
|
||||
DELAY_IAT_A, DELAY_IAT_B = DATA, DATA + 0x20
|
||||
HANDLE_A, HANDLE_B = DATA + 0x40, DATA + 0x48
|
||||
|
||||
# Each delay-load address slot starts out pointing at its own stub.
|
||||
STUBS = (TEXT + 0x10, TEXT + 0x18, TEXT + 0x20)
|
||||
|
||||
|
||||
def fixture():
|
||||
data = bytearray(0xC00)
|
||||
|
||||
def offset(rva):
|
||||
section = rva & ~0xFFF
|
||||
return RAW[section] + rva - section
|
||||
|
||||
def put(rva, layout, *values):
|
||||
pack_into(layout, data, offset(rva), *values)
|
||||
|
||||
def text(rva, value):
|
||||
data[offset(rva):offset(rva) + len(value) + 1] = value + b"\0"
|
||||
|
||||
data[:2] = b"MZ"
|
||||
pack_into("<I", data, 0x3C, 0x80)
|
||||
data[0x80:0x84] = b"PE\0\0"
|
||||
# AMD64, three sections, 240-byte optional header; relocations stripped,
|
||||
# executable, large-address-aware.
|
||||
pack_into("<HHIIIHH", data, 0x84, 0x8664, 3, 0, 0, 0, 240, 0x23)
|
||||
opt = 0x98
|
||||
pack_into("<H", data, opt, 0x20B)
|
||||
pack_into("<III", data, opt + 4, 0x200, 0x600, 0)
|
||||
pack_into("<IIQII", data, opt + 16, TEXT, TEXT, BASE, 0x1000, 0x200)
|
||||
pack_into("<HHHHHH", data, opt + 40, 6, 0, 0, 0, 6, 0)
|
||||
pack_into("<II", data, opt + 56, 0x4000, 0x400)
|
||||
# Console subsystem; NX compatible at a fixed base.
|
||||
pack_into("<HH", data, opt + 68, 3, 0x100)
|
||||
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
|
||||
# Import table, import address table and delay import descriptor.
|
||||
for index, rva, size in (
|
||||
(1, IMPORT_DIRECTORY, 40),
|
||||
(12, IAT, 24),
|
||||
(13, DELAY_DIRECTORY, 96),
|
||||
):
|
||||
pack_into("<II", data, opt + 112 + index * 8, rva, size)
|
||||
|
||||
sections = (
|
||||
(b".text", TEXT, 0x200, 0x60000020),
|
||||
(b".rdata", RDATA, 0x400, 0x40000040),
|
||||
(b".data", DATA, 0x200, 0xC0000040),
|
||||
)
|
||||
for index, (name, rva, size, characteristics) in enumerate(sections):
|
||||
pack_into(
|
||||
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, size, rva,
|
||||
size, offset(rva), 0, 0, 0, 0, characteristics,
|
||||
)
|
||||
|
||||
# Entry returns. The stubs are INT3 because the fixture is never run.
|
||||
data[offset(TEXT)] = 0xC3
|
||||
for stub in STUBS:
|
||||
data[offset(stub)] = 0xCC
|
||||
|
||||
# One ordinary DLL: a named import and ordinal 3.
|
||||
put(IMPORT_DIRECTORY, "<IIIII", LOOKUP, 0, 0, ORDINARY_DLL, IAT)
|
||||
for table in (LOOKUP, IAT):
|
||||
put(table, "<QQQ", ORDINARY_NAME, ORDINAL | 3, 0)
|
||||
text(ORDINARY_DLL, b"fixture-ordinary.dll")
|
||||
text(ORDINARY_NAME + 2, b"OrdinaryByName")
|
||||
|
||||
# Two delay-loaded DLLs. Attributes bit 0 marks the fields as RVAs.
|
||||
put(DELAY_DIRECTORY, "<IIIIIIII",
|
||||
1, DELAY_DLL_A, HANDLE_A, DELAY_IAT_A, NAMES_A, 0, 0, 0)
|
||||
put(DELAY_DIRECTORY + 32, "<IIIIIIII",
|
||||
1, DELAY_DLL_B, HANDLE_B, DELAY_IAT_B, NAMES_B, 0, 0, 0)
|
||||
put(NAMES_A, "<QQQ", DELAY_NAME_A, ORDINAL | 7, 0)
|
||||
put(NAMES_B, "<QQ", DELAY_NAME_B, 0)
|
||||
text(DELAY_DLL_A, b"fixture-delay-a.dll")
|
||||
text(DELAY_DLL_B, b"fixture-delay-b.dll")
|
||||
text(DELAY_NAME_A + 2, b"DelayedAlpha")
|
||||
text(DELAY_NAME_B + 2, b"DelayedBeta")
|
||||
put(DELAY_IAT_A, "<QQQ", BASE + STUBS[0], BASE + STUBS[1], 0)
|
||||
put(DELAY_IAT_B, "<QQ", BASE + STUBS[2], 0)
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
path = Path(__file__).with_suffix(".exe")
|
||||
if args.check:
|
||||
if path.read_bytes() != fixture():
|
||||
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
|
||||
else:
|
||||
path.write_bytes(fixture())
|
||||
Binary file not shown.
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOPK vectors: the sixteen 16-bit-immediate integer forms. s8 =
|
||||
// 0xffff8000 (s_movk_i32 sign-extends 0x8000), so the twelve s_cmpk compares
|
||||
// split signed (sign-extended SIMM16) from unsigned (zero-extended); an
|
||||
// s_cbranch_scc0 skips setting that compare's bit in s20. s_addk_i32 sets SCC
|
||||
// on signed overflow, s_mulk_i32 leaves SCC alone, and s_cmovk_i32 moves only
|
||||
// while SCC is set. Bits worked out by hand below.
|
||||
// Expected: input ^ 0x40008275 (s20 ^ s9 ^ s10 ^ s11).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_movk_i32 s8, 0x8000 // s8 = 0xffff8000
|
||||
s_mov_b32 s20, 0
|
||||
s_cmpk_eq_i32 s8, 0x8000 // SCC = 1 (-32768 == -32768)
|
||||
s_cbranch_scc0 .Lskip0
|
||||
s_or_b32 s20, s20, 0x1
|
||||
.Lskip0:
|
||||
s_cmpk_eq_u32 s8, 0x8000 // 0xffff8000 == 0x00008000: SCC = 0
|
||||
s_cbranch_scc0 .Lskip1
|
||||
s_or_b32 s20, s20, 0x2
|
||||
.Lskip1:
|
||||
s_cmpk_lg_i32 s8, 0x7fff // -32768 != 32767: SCC = 1
|
||||
s_cbranch_scc0 .Lskip2
|
||||
s_or_b32 s20, s20, 0x4
|
||||
.Lskip2:
|
||||
s_cmpk_gt_i32 s8, 0xffff // -32768 > -1 (0xffff sign-extends): SCC = 0
|
||||
s_cbranch_scc0 .Lskip3
|
||||
s_or_b32 s20, s20, 0x8
|
||||
.Lskip3:
|
||||
s_cmpk_gt_u32 s8, 0xffff // 0xffff8000 > 0x0000ffff (zero-extends): SCC = 1
|
||||
s_cbranch_scc0 .Lskip4
|
||||
s_or_b32 s20, s20, 0x10
|
||||
.Lskip4:
|
||||
s_cmpk_ge_i32 s8, 0x8000 // -32768 >= -32768: SCC = 1
|
||||
s_cbranch_scc0 .Lskip5
|
||||
s_or_b32 s20, s20, 0x20
|
||||
.Lskip5:
|
||||
s_cmpk_lt_i32 s8, 0x1 // -32768 < 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip6
|
||||
s_or_b32 s20, s20, 0x40
|
||||
.Lskip6:
|
||||
s_cmpk_lt_u32 s8, 0x1 // 0xffff8000 < 1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip7
|
||||
s_or_b32 s20, s20, 0x80
|
||||
.Lskip7:
|
||||
s_cmpk_le_i32 s8, 0x8000 // -32768 <= -32768: SCC = 1
|
||||
s_cbranch_scc0 .Lskip8
|
||||
s_or_b32 s20, s20, 0x100
|
||||
.Lskip8:
|
||||
s_cmpk_le_u32 s8, 0x8000 // 0xffff8000 <= 0x8000: SCC = 0
|
||||
s_cbranch_scc0 .Lskip9
|
||||
s_or_b32 s20, s20, 0x200
|
||||
.Lskip9:
|
||||
s_cmpk_ge_u32 s8, 0x8000 // 0xffff8000 >= 0x8000: SCC = 1
|
||||
s_cbranch_scc0 .Lskip10
|
||||
s_or_b32 s20, s20, 0x400
|
||||
.Lskip10:
|
||||
s_cmpk_lg_u32 s8, 0x8000 // 0xffff8000 != 0x8000: SCC = 1
|
||||
s_cbranch_scc0 .Lskip11
|
||||
s_or_b32 s20, s20, 0x800
|
||||
.Lskip11:
|
||||
s_movk_i32 s9, 0x7fff // s9 = 32767
|
||||
s_mov_b32 s10, 0x7fffffff
|
||||
s_addk_i32 s10, 1 // 0x7fffffff + 1 overflows: s10 = 0x80000000, SCC = 1
|
||||
s_cbranch_scc0 .Lskip12
|
||||
s_or_b32 s20, s20, 0x1000
|
||||
.Lskip12:
|
||||
s_mulk_i32 s9, 0x8000 // 32767 * -32768: s9 = 0xc0008000, SCC stays 1
|
||||
s_cbranch_scc0 .Lskip13
|
||||
s_or_b32 s20, s20, 0x2000
|
||||
.Lskip13:
|
||||
s_addk_i32 s10, 0xffff // 0x80000000 + -1 overflows: s10 = 0x7fffffff, SCC = 1
|
||||
s_cbranch_scc0 .Lskip14
|
||||
s_or_b32 s20, s20, 0x4000
|
||||
.Lskip14:
|
||||
s_addk_i32 s9, 0x7fff // 0xc0008000 + 32767 = 0xc000ffff, no overflow: SCC = 0
|
||||
s_cbranch_scc0 .Lskip15
|
||||
s_or_b32 s20, s20, 0x8000
|
||||
.Lskip15:
|
||||
s_mov_b32 s11, 0x1111
|
||||
s_cmovk_i32 s11, 0xff00 // SCC = 0: s11 stays 0x1111
|
||||
s_cmpk_eq_u32 s11, 0x1111 // SCC = 1
|
||||
s_cmovk_i32 s11, 0xff00 // SCC = 1: s11 = 0xffffff00
|
||||
v_mov_b32_e32 v2, s20 // s20 = 0x00007d75
|
||||
v_mov_b32_e32 v3, s9 // s9 = 0xc000ffff
|
||||
v_xor_b32_e32 v2, v3, v2
|
||||
v_mov_b32_e32 v3, s10 // s10 = 0x7fffffff
|
||||
v_xor_b32_e32 v2, v3, v2
|
||||
v_mov_b32_e32 v3, s11 // s11 = 0xffffff00
|
||||
v_xor_b32_e32 v2, v3, v2
|
||||
v_xor_b32_e32 v2, v1, v2
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Encoding inventory for Wave32 16-bit VOPC compares (guide Table 61).
|
||||
// Operand and execution cases are in tests/validation/tests/vopc_wide.rs.
|
||||
.text
|
||||
buffer_load_dword v2, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
v_mov_b32_e32 v3, 7
|
||||
v_cmp_lt_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_eq_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_le_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_gt_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ne_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ge_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_lt_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_eq_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_le_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_gt_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ne_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ge_u16_e32 vcc_lo, v2, v3
|
||||
v_mov_b32_e32 v2, vcc_lo
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,29 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Encoding inventory for Wave32 64-bit VOPC compares (guide Table 61).
|
||||
// Operand and execution cases are in tests/validation/tests/vopc_wide.rs.
|
||||
.text
|
||||
buffer_load_dword v2, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
v_mov_b32_e32 v3, 0
|
||||
v_mov_b32_e32 v4, 7
|
||||
v_mov_b32_e32 v5, 0
|
||||
v_cmp_f_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_lt_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_eq_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_le_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_gt_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_ne_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_ge_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_t_i64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_f_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_lt_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_eq_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_le_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_gt_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_ne_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_ge_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_cmp_t_u64_e32 vcc_lo, v[2:3], v[4:5]
|
||||
v_mov_b32_e32 v2, vcc_lo
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Wave32 VOP1 integer forms (AMD RDNA 2 ISA guide 12.8).
|
||||
// Exchange the input and its complement in odd lanes, then use both values
|
||||
// and all three bit scans to form the output.
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
v_not_b32_e32 v2, v1
|
||||
s_mov_b32 exec_lo, 0xaaaaaaaa
|
||||
v_swap_b32 v1, v2
|
||||
s_mov_b32 exec_lo, -1
|
||||
v_bfrev_b32_e32 v3, v1
|
||||
v_ffbh_u32_e32 v4, v2
|
||||
v_ffbl_b32_e32 v5, v1
|
||||
v_ffbh_i32_e32 v6, v2
|
||||
v_xor_b32_e32 v7, v3, v4
|
||||
v_xor_b32_e32 v7, v5, v7
|
||||
v_xor_b32_e32 v7, v6, v7
|
||||
buffer_store_dword v7, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original Wave32 example. The compare derives VCC from the input, then each
|
||||
// carry/borrow feeds the next operation. Before reverse subtract, v3 is
|
||||
// 0xfffffffe for a zero input and 0xffffffff otherwise, with borrow-in 1.
|
||||
// Subtracting 0xfffffffe and the borrow-in sets the final VCC bit for zero inputs.
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
v_cmp_eq_u32_e32 vcc_lo, 0, v1
|
||||
v_cndmask_b32_e32 v2, -1, v1, vcc_lo
|
||||
v_add_co_ci_u32_e32 v2, vcc_lo, 1, v2, vcc_lo
|
||||
v_sub_co_ci_u32_e32 v3, vcc_lo, 0, v2, vcc_lo
|
||||
v_subrev_co_ci_u32_e32 v3, vcc_lo, -2, v3, vcc_lo
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
buffer_store_dword v4, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,85 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original Wave32 VOP3A vectors for the sixteen integer compare encoding variants.
|
||||
// Each compare writes vcc_lo through the explicit 64-bit destination field
|
||||
// (one writes s8), and each wave folds the masks into v2 as
|
||||
// v2 = (v2 << 1) ^ mask. Sources are VGPRs. This fixture is checked through
|
||||
// its IR and MSL goldens; the per-lane expected values for these forms are in
|
||||
// tests/validation/tests/vop3_compare.rs.
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word.
|
||||
s_waitcnt vmcnt(0) // Wait for the load.
|
||||
v_mov_b32_e32 v2, 0 // Clear the accumulator.
|
||||
v_mov_b32_e32 v5, 1 // Shift count for the fold.
|
||||
v_mov_b32_e32 v3, 0x40000001 // Second source: inputs fall below, on and above it.
|
||||
v_mov_b32_e32 v6, 1 // Low bit for the branch fold.
|
||||
v_cmp_f_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_lt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_eq_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_le_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_gt_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_ne_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_ge_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_t_i32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_f_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_lt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_eq_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_le_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_gt_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_ne_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_ge_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_t_u32_e64 vcc_lo, v1, v3 // Compare the input with 0x40000001.
|
||||
v_mov_b32_e32 v4, vcc_lo // Move the mask into a VGPR.
|
||||
v_lshlrev_b32_e32 v2, v5, v2 // Shift the accumulator.
|
||||
v_xor_b32_e32 v2, v2, v4 // Fold the mask.
|
||||
v_cmp_eq_u32_e64 s8, v1, v3 // A mask into a plain SGPR, never read.
|
||||
v_cmp_gt_u32_e64 vcc_lo, v3, v1 // Unsigned 0x40000001 > input.
|
||||
s_cbranch_vccz 1 // Skip the next fold when no lane passed.
|
||||
v_xor_b32_e32 v2, v6, v2 // Flip the low bit when some lane passed.
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen // Store the folded word.
|
||||
s_waitcnt_vscnt null, 0 // Wait for the store.
|
||||
s_endpgm // End the program.
|
||||
Binary file not shown.
@@ -0,0 +1,31 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original VOP3A vectors for the eleven per-lane integer encoding variants.
|
||||
// All arithmetic operands are vector general-purpose registers (VGPRs) and every result
|
||||
// depends on the lane's own input word. XOR folds the results into one word.
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen // Load the lane's input word.
|
||||
s_waitcnt vmcnt(0) // Wait for the load.
|
||||
v_mul_i32_i24_e64 v2, v1, v1 // Multiply signed 24-bit inputs and keep the low word.
|
||||
v_mul_hi_i32_i24_e64 v3, v2, v1 // Multiply signed 24-bit inputs and keep the high word.
|
||||
v_mul_u32_u24_e64 v4, v2, v1 // Multiply unsigned 24-bit inputs and keep the low word.
|
||||
v_mul_hi_u32_u24_e64 v255, v4, v1 // Multiply unsigned 24-bit inputs and keep the high word.
|
||||
v_min_i32_e64 v6, v1, v2 // Select the signed minimum.
|
||||
v_max_i32_e64 v7, v1, v4 // Select the signed maximum.
|
||||
v_min_u32_e64 v8, v3, v1 // Select the unsigned minimum.
|
||||
v_max_u32_e64 v9, v255, v2 // Select the unsigned maximum.
|
||||
v_xnor_b32_e64 v10, v1, v255 // Complement the XOR.
|
||||
v_sub_nc_u32_e64 v11, v6, v10 // Subtract the second source from the first.
|
||||
v_subrev_nc_u32_e64 v1, v1, v9 // Subtract the first source from the second, overwriting the first.
|
||||
v_xor_b32_e32 v13, v2, v3 // Start the XOR fold.
|
||||
v_xor_b32_e32 v13, v4, v13 // Fold the unsigned product low word.
|
||||
v_xor_b32_e32 v13, v255, v13 // Fold the unsigned product high word.
|
||||
v_xor_b32_e32 v13, v6, v13 // Fold the signed minimum.
|
||||
v_xor_b32_e32 v13, v7, v13 // Fold the signed maximum.
|
||||
v_xor_b32_e32 v13, v8, v13 // Fold the unsigned minimum.
|
||||
v_xor_b32_e32 v13, v9, v13 // Fold the unsigned maximum.
|
||||
v_xor_b32_e32 v13, v10, v13 // Fold the XNOR result.
|
||||
v_xor_b32_e32 v13, v11, v13 // Fold the subtraction result.
|
||||
v_xor_b32_e32 v13, v1, v13 // Fold the reverse subtraction result.
|
||||
buffer_store_dword v13, v0, s[4:7], 0 idxen // Store the folded word.
|
||||
s_waitcnt_vscnt null, 0 // Wait for the store.
|
||||
s_endpgm // End the program.
|
||||
@@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
esac
|
||||
|
||||
for name in add bitwise-branch float-exact or shifts ashr \
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith vector-integer vector-compare-ft; do
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-vcc vop3-integer vop3-compare vector-unary vector-compare-64 vector-compare-16; do
|
||||
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
|
||||
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
|
||||
|
||||
@@ -10,7 +10,7 @@ import sys
|
||||
import tomllib
|
||||
|
||||
registry = Path("docs/claims.toml")
|
||||
claims = tomllib.loads(registry.read_text())["claim"]
|
||||
claims = tomllib.loads(registry.read_text(encoding="utf-8"))["claim"]
|
||||
classes = {}
|
||||
errors = []
|
||||
claim_id = re.compile(r"\bCLAIM-[A-Z0-9]+(?:-[A-Z0-9]+)*\b")
|
||||
@@ -37,10 +37,10 @@ files = [Path("README.md"), Path("AGENTS.md"), *Path("docs").rglob("*"),
|
||||
for source in files:
|
||||
if source == registry or source.suffix not in {".md", ".toml", ".rs"}:
|
||||
continue
|
||||
for reference in set(claim_id.findall(source.read_text())) - classes.keys():
|
||||
for reference in set(claim_id.findall(source.read_text(encoding="utf-8"))) - classes.keys():
|
||||
errors.append(f"{source}: unregistered {reference}")
|
||||
|
||||
status = tomllib.loads(Path("docs/status.toml").read_text())
|
||||
status = tomllib.loads(Path("docs/status.toml").read_text(encoding="utf-8"))
|
||||
for feature in status["feature"]:
|
||||
verification = feature.get("hardware_verification", "")
|
||||
if verification.casefold() != "verified":
|
||||
|
||||
@@ -18,7 +18,7 @@ def table(headers, rows):
|
||||
|
||||
|
||||
def replace_block(path, name, body, check):
|
||||
original = path.read_text()
|
||||
original = path.read_text(encoding="utf-8")
|
||||
start = f"<!-- status:{name}:start -->\n"
|
||||
stop = f"\n<!-- status:{name}:end -->"
|
||||
head, _, tail = original.partition(start)
|
||||
@@ -30,7 +30,7 @@ def replace_block(path, name, body, check):
|
||||
if check:
|
||||
print(f"{path}: status table differs from docs/status.toml", file=sys.stderr)
|
||||
return False
|
||||
path.write_text(updated)
|
||||
path.write_text(updated, encoding="utf-8", newline="\n")
|
||||
return True
|
||||
|
||||
|
||||
@@ -90,12 +90,12 @@ def render_progress(status):
|
||||
|
||||
|
||||
def check_asset(path, svg, check):
|
||||
if path.exists() and path.read_text() == svg:
|
||||
if path.exists() and path.read_text(encoding="utf-8") == svg:
|
||||
return True
|
||||
if check:
|
||||
print(f"{path}: progress graphic differs from docs/status.toml", file=sys.stderr)
|
||||
return False
|
||||
path.write_text(svg)
|
||||
path.write_text(svg, encoding="utf-8", newline="\n")
|
||||
return True
|
||||
|
||||
|
||||
@@ -105,8 +105,8 @@ def main():
|
||||
check = parser.parse_args().check
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
docs = root / "docs"
|
||||
status = tomllib.loads((docs / "status.toml").read_text())
|
||||
claims = tomllib.loads((docs / "claims.toml").read_text())
|
||||
status = tomllib.loads((docs / "status.toml").read_text(encoding="utf-8"))
|
||||
claims = tomllib.loads((docs / "claims.toml").read_text(encoding="utf-8"))
|
||||
classes = {claim["id"]: claim["class"] for claim in claims["claim"]}
|
||||
|
||||
features = table(
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user