mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 22:51:11 +00:00
Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3392c226ce | ||
|
|
133c9df448 | ||
|
|
00f79c10d2 | ||
|
|
ee2d29a65c | ||
|
|
83ef49c258 | ||
|
|
84b6fb4d50 | ||
|
|
7fa240f7ba | ||
|
|
0e9211cd42 | ||
|
|
c41e034fa1 | ||
|
|
7977dd4bf2 | ||
|
|
cd948d4a14 | ||
|
|
a2c696b551 | ||
|
|
d6189ae3ea | ||
|
|
e6eece6983 | ||
|
|
1a78265ede | ||
|
|
2e0e5a36f6 | ||
|
|
ece0fc27eb | ||
|
|
82f2d9e9e6 | ||
|
|
391367a531 | ||
|
|
e71a3da525 | ||
|
|
b96511bfc5 | ||
|
|
84bb80d910 | ||
|
|
9edf644d77 | ||
|
|
b5d0382e89 | ||
|
|
b705104403 | ||
|
|
f148b51a48 | ||
|
|
c979870b3a | ||
|
|
cd59e081d9 | ||
|
|
0bfb12fd17 | ||
|
|
c6d0986da2 | ||
|
|
9a9422c7da | ||
|
|
da41b6420d | ||
|
|
3f710928af | ||
|
|
2fdf01fbb3 | ||
|
|
de00cb2bfd | ||
|
|
d8f9669280 | ||
|
|
19b2e9b5d5 | ||
|
|
bb6bc52c95 | ||
|
|
ba6bbb2e4a | ||
|
|
705b074a08 | ||
|
|
d3c1150854 | ||
|
|
a81d62ffe3 | ||
|
|
bb1372cd70 | ||
|
|
8d53d82981 | ||
|
|
ba2cfc2a00 | ||
|
|
b13ab327f2 | ||
|
|
e7cb8db14f | ||
|
|
e7795d0e5a | ||
|
|
3ff9ddde24 | ||
|
|
ff191d89bd | ||
|
|
4039be8ee2 | ||
|
|
898b79dc84 | ||
|
|
30d20c8f33 | ||
|
|
0687a8add6 | ||
|
|
791b736b0e | ||
|
|
fcda9c09bd | ||
|
|
ad5a6f9c53 | ||
|
|
f856671b6d | ||
|
|
e1317322e1 | ||
|
|
0609012903 | ||
|
|
dffa50cd9c | ||
|
|
b541dce0cc | ||
|
|
52ecece126 | ||
|
|
440856a997 | ||
|
|
1eeb614ea2 | ||
|
|
afd936b20b | ||
|
|
1680e6b19c | ||
|
|
3eef0ecfa8 | ||
|
|
e616583c3f | ||
|
|
c9e3394eb3 | ||
|
|
358ddc5eba |
No files matched your search
@@ -38,6 +38,8 @@ jobs:
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
@@ -48,6 +50,10 @@ jobs:
|
||||
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
|
||||
- name: Test pull request template check
|
||||
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
|
||||
- name: Test semantic registry generator and coverage report
|
||||
run: |
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
|
||||
- name: Check formatting and lint
|
||||
run: |
|
||||
cargo fmt --all -- --check
|
||||
|
||||
@@ -37,3 +37,6 @@ __pycache__/
|
||||
*.pyc
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
@@ -10,7 +10,15 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
|
||||
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
|
||||
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
|
||||
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
|
||||
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
|
||||
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
|
||||
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
|
||||
|
||||
Generated
+9
@@ -179,6 +179,15 @@ dependencies = [
|
||||
"xenora-ref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-import-gen"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// swift-tools-version: 6.0
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Build with scripts/build-app.sh, which builds the Rust static library first.
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Xenora",
|
||||
platforms: [.macOS(.v14)],
|
||||
targets: [
|
||||
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
|
||||
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
module CXenora [system] {
|
||||
header "../../../crates/ffi/include/xenora.h"
|
||||
link "xenora_ffi"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Native shell over the versioned C interface. "Run trusted fixture" executes the
|
||||
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
|
||||
// by native Metal) and shows the verified read-back frame. No other executable can run.
|
||||
|
||||
import AppKit
|
||||
import CXenora
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct RuntimeProbe {
|
||||
var abiVersion: UInt32 = 0
|
||||
var status: Int32 = -1
|
||||
var sections: UInt32 = 0
|
||||
var entryRVA: UInt32 = 0
|
||||
|
||||
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
|
||||
|
||||
static func run() -> RuntimeProbe {
|
||||
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
|
||||
var session: xenora_session = 0
|
||||
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard probe.status == XENORA_OK else { return probe }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
|
||||
return probe
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame produced by one run of the trusted fixture.
|
||||
struct GuestFrame {
|
||||
let status: Int32
|
||||
let width: Int
|
||||
let height: Int
|
||||
let rgba: [UInt8]
|
||||
|
||||
static func run() -> GuestFrame {
|
||||
var session: xenora_session = 0
|
||||
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
var width: UInt32 = 0
|
||||
var height: UInt32 = 0
|
||||
status = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
|
||||
}
|
||||
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
|
||||
}
|
||||
|
||||
var image: CGImage? {
|
||||
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
|
||||
return CGImage(
|
||||
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
|
||||
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
|
||||
/// which the command-line toolchain does not ship.
|
||||
@MainActor
|
||||
final class FrameModel: ObservableObject {
|
||||
@Published var frame: GuestFrame?
|
||||
@Published var running = false
|
||||
|
||||
func run() {
|
||||
running = true
|
||||
Task {
|
||||
// The fixture blocks while it executes and renders, so keep it off the main thread.
|
||||
frame = await Task.detached { GuestFrame.run() }.value
|
||||
running = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed.
|
||||
@MainActor
|
||||
final class InspectionModel: ObservableObject {
|
||||
static let shared = InspectionModel()
|
||||
@Published var fileName: String?
|
||||
@Published var report = ""
|
||||
@Published var status: Int32 = Int32(XENORA_OK)
|
||||
@Published var busy = false
|
||||
@Published var importing = false
|
||||
|
||||
func inspect(_ url: URL) {
|
||||
fileName = url.lastPathComponent
|
||||
busy = true
|
||||
Task {
|
||||
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
|
||||
status = newStatus
|
||||
report = newReport
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated static func run(_ url: URL) -> (Int32, String) {
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
// Check the size before reading so an oversized file is never loaded into memory.
|
||||
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else {
|
||||
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.")
|
||||
}
|
||||
guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else {
|
||||
return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).")
|
||||
}
|
||||
guard let data = try? Data(contentsOf: url) else {
|
||||
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.")
|
||||
}
|
||||
return data.withUnsafeBytes { raw in
|
||||
let bytes = raw.bindMemory(to: UInt8.self).baseAddress
|
||||
var required: UInt64 = 0
|
||||
var probe: CChar = 0
|
||||
var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required)
|
||||
guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") }
|
||||
var text = [CChar](repeating: 0, count: Int(required))
|
||||
status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required)
|
||||
return (status, String(cString: text))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives files opened from Finder (double-click or Open With).
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
func application(_ application: NSApplication, open urls: [URL]) {
|
||||
guard let url = urls.first else { return }
|
||||
MainActor.assumeIsolated { InspectionModel.shared.inspect(url) }
|
||||
}
|
||||
}
|
||||
|
||||
struct InspectorView: View {
|
||||
@ObservedObject var model: InspectionModel
|
||||
|
||||
var body: some View {
|
||||
Section("Executable inspection (read-only)") {
|
||||
HStack {
|
||||
Button("Open Executable…") { model.importing = true }
|
||||
Text("or drop a file on this window").foregroundStyle(.secondary)
|
||||
}
|
||||
if let name = model.fileName {
|
||||
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
|
||||
ScrollView {
|
||||
Text(model.report)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.frame(minHeight: 160, maxHeight: 320)
|
||||
}
|
||||
Text("Opened files are inspected only. Running them is not available.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
let probe = RuntimeProbe.run()
|
||||
@ObservedObject var model: FrameModel
|
||||
@ObservedObject var inspection = InspectionModel.shared
|
||||
private var frame: GuestFrame? { model.frame }
|
||||
private var running: Bool { model.running }
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
InspectorView(model: inspection)
|
||||
Section("Guest display") {
|
||||
if let image = frame?.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
|
||||
.accessibilityLabel("Guest frame, \(frame!.width) by \(frame!.height) pixels")
|
||||
Text("Guest code ran, its draw was rendered by native Metal, and all \(frame!.width * frame!.height) pixels matched the fixture shader's output.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let frame {
|
||||
Text("Run failed (status \(frame.status)). No frame is shown.")
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
|
||||
.disabled(running || !probe.connected)
|
||||
}
|
||||
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
|
||||
LabeledContent("Interface version", value: "\(probe.abiVersion)")
|
||||
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
|
||||
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
|
||||
Text("Only the bundled trusted fixture can run. Live presentation, persistent sessions and input are not available yet.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
|
||||
if case .success(let url) = result { inspection.inspect(url) }
|
||||
}
|
||||
.dropDestination(for: URL.self) { urls, _ in
|
||||
guard let url = urls.first, url.isFileURL else { return false }
|
||||
inspection.inspect(url)
|
||||
return true
|
||||
}
|
||||
.frame(minWidth: 520, minHeight: 560)
|
||||
}
|
||||
}
|
||||
|
||||
struct XenoraApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
let model = FrameModel()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup("Xenora") { ContentView(model: model) }
|
||||
}
|
||||
}
|
||||
|
||||
// `--inspect <path>` prints the read-only report for a file and exits with its status.
|
||||
if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count {
|
||||
let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1]))
|
||||
print(report.hasSuffix("\n") ? report : report + "\n", terminator: "")
|
||||
print("status=\(status)")
|
||||
exit(status == Int32(XENORA_OK) ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-frame` runs the trusted fixture on the Metal device and exits; it needs a GPU.
|
||||
if CommandLine.arguments.contains("--smoke-frame") {
|
||||
let frame = GuestFrame.run()
|
||||
print(frame.summary)
|
||||
exit(frame.status == XENORA_OK ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
|
||||
if CommandLine.arguments.contains("--smoke") {
|
||||
let probe = RuntimeProbe.run()
|
||||
print(probe.summary)
|
||||
exit(probe.connected ? 0 : 1)
|
||||
}
|
||||
XenoraApp.main()
|
||||
+49
-40
@@ -4,46 +4,56 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarSource, VectorCompareOp, VectorSource,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
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,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::FORM_IDS;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination. Operand restrictions are listed in docs/status.toml;
|
||||
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
|
||||
/// restrictions are listed in docs/status.toml; every other form in
|
||||
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
|
||||
concat_forms();
|
||||
|
||||
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
let mut forms = [("", EncodingFamily::Sop2); N];
|
||||
let mut index = 0;
|
||||
while index < N {
|
||||
forms[index] = if index < HANDWRITTEN_FORMS.len() {
|
||||
HANDWRITTEN_FORMS[index]
|
||||
} else {
|
||||
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
|
||||
};
|
||||
index += 1;
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_ADDC_U32", EncodingFamily::Sop2),
|
||||
("S_AND_B32", EncodingFamily::Sop2),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_OR_B32", EncodingFamily::Sop2),
|
||||
("S_SUB_I32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_SUBB_U32", EncodingFamily::Sop2),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("S_XOR_B32", EncodingFamily::Sop2),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
@@ -364,19 +374,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if S_CMP_EQ_U32.matches(first) {
|
||||
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"));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
}
|
||||
if let Some(op) = ScalarCompareOp::from_word(first) {
|
||||
let mnemonic = op.mnemonic();
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
"s_cmp_eq_u32",
|
||||
mnemonic,
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
return Ok((
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 },
|
||||
Instruction::ScalarCompare { op, src0, src1 },
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
@@ -384,20 +405,8 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
}
|
||||
for (opcode, op) in [
|
||||
(S_ADD_U32, ScalarAluOp::AddU32),
|
||||
(S_SUB_U32, ScalarAluOp::SubU32),
|
||||
(S_ADD_I32, ScalarAluOp::AddI32),
|
||||
(S_SUB_I32, ScalarAluOp::SubI32),
|
||||
(S_ADDC_U32, ScalarAluOp::AddcU32),
|
||||
(S_SUBB_U32, ScalarAluOp::SubbU32),
|
||||
(S_AND_B32, ScalarAluOp::AndB32),
|
||||
(S_OR_B32, ScalarAluOp::OrB32),
|
||||
(S_XOR_B32, ScalarAluOp::XorB32),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
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")?;
|
||||
|
||||
@@ -4,9 +4,12 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
@@ -340,6 +343,30 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
ScalarAluOp::AndB32 => ScalarAlu::And,
|
||||
ScalarAluOp::OrB32 => ScalarAlu::Or,
|
||||
ScalarAluOp::XorB32 => ScalarAlu::Xor,
|
||||
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
|
||||
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
|
||||
ScalarAluOp::NandB32 => ScalarAlu::Nand,
|
||||
ScalarAluOp::NorB32 => ScalarAlu::Nor,
|
||||
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
|
||||
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
|
||||
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
|
||||
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
|
||||
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
|
||||
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
|
||||
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
|
||||
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
|
||||
ScalarAluOp::CselectB32 => ScalarAlu::Select,
|
||||
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
|
||||
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
|
||||
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
|
||||
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
|
||||
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
|
||||
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
|
||||
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
|
||||
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src0),
|
||||
@@ -347,8 +374,38 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
|
||||
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
|
||||
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
|
||||
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
|
||||
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(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
|
||||
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
|
||||
match op.relation() {
|
||||
CompareRelation::Equal => Op::CompareEqual(src0, src1),
|
||||
relation => Op::ScalarCompare(
|
||||
Comparison {
|
||||
offset: relation as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
},
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
@@ -434,13 +491,17 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
SHIFT_FIXTURE,
|
||||
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
|
||||
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/vector-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 88, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
|
||||
@@ -49,3 +49,11 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_forms_do_not_duplicate_hand_written_forms() {
|
||||
// A form declared in the semantic registry and also decoded by hand-written
|
||||
// code would have two implementations; the hand-written one would win.
|
||||
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "xenora-ffi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Versioned C interface between the native macOS application and the Xenora runtime"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "rlib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
@@ -0,0 +1,89 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
/*
|
||||
* Xenora native application interface, version 1.
|
||||
*
|
||||
* Every function returns a xenora_status. Sessions are identified by opaque
|
||||
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
|
||||
* handle stays invalid even if its slot is reused. Output pointers are owned
|
||||
* by the caller and are written only when the call returns XENORA_OK.
|
||||
* All functions are thread-safe. No Rust panic crosses this boundary: one is
|
||||
* reported as XENORA_INTERNAL_ERROR.
|
||||
*/
|
||||
#ifndef XENORA_H
|
||||
#define XENORA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define XENORA_ABI_VERSION 1u
|
||||
|
||||
typedef int32_t xenora_status;
|
||||
enum {
|
||||
XENORA_OK = 0,
|
||||
XENORA_INVALID_ARGUMENT = 1,
|
||||
XENORA_INVALID_HANDLE = 2,
|
||||
XENORA_VERSION_MISMATCH = 3,
|
||||
XENORA_INTERNAL_ERROR = 4,
|
||||
XENORA_PE_ERROR = 5,
|
||||
XENORA_LIMIT_EXCEEDED = 6,
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
};
|
||||
|
||||
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
|
||||
#define XENORA_FIXTURE_FRAME_WIDTH 4u
|
||||
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
|
||||
|
||||
typedef uint64_t xenora_session;
|
||||
|
||||
/* The interface version this library implements. */
|
||||
uint32_t xenora_abi_version(void);
|
||||
|
||||
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
|
||||
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
|
||||
|
||||
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
|
||||
xenora_status xenora_session_destroy(xenora_session session);
|
||||
|
||||
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
|
||||
xenora_status xenora_session_inspect_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint32_t *out_section_count,
|
||||
uint32_t *out_entry_rva);
|
||||
|
||||
/*
|
||||
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
|
||||
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
|
||||
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
|
||||
* checked against the fixture shader's known output. `capacity` is the size of
|
||||
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
|
||||
* Only the embedded fixture can run; no caller-supplied executable is accepted.
|
||||
*/
|
||||
xenora_status xenora_session_run_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height);
|
||||
|
||||
/* Largest file xenora_inspect_executable accepts, in bytes. */
|
||||
#define XENORA_MAX_INSPECT_BYTES 268435456u
|
||||
|
||||
/*
|
||||
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
|
||||
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
|
||||
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
|
||||
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
|
||||
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
|
||||
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
|
||||
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
|
||||
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
|
||||
* XENORA_LIMIT_EXCEEDED.
|
||||
*/
|
||||
xenora_status xenora_inspect_executable(
|
||||
const uint8_t *bytes,
|
||||
uint64_t length,
|
||||
char *out_report,
|
||||
uint64_t capacity,
|
||||
uint64_t *out_required);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,658 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Versioned C interface for the native macOS application (see `include/xenora.h`).
|
||||
//!
|
||||
//! Sessions are opaque 64-bit handles: the low 32 bits index a slot and the high
|
||||
//! 32 bits hold that slot's generation, so a stale handle never reaches a reused slot.
|
||||
//! Every exported function catches panics and reports them as `XENORA_INTERNAL_ERROR`.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, ParsedPe, ProbeConfig, Register, probe_pe_bytes};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
pub const XENORA_ABI_VERSION: u32 = 1;
|
||||
|
||||
pub const XENORA_OK: i32 = 0;
|
||||
pub const XENORA_INVALID_ARGUMENT: i32 = 1;
|
||||
pub const XENORA_INVALID_HANDLE: i32 = 2;
|
||||
pub const XENORA_VERSION_MISMATCH: i32 = 3;
|
||||
pub const XENORA_INTERNAL_ERROR: i32 = 4;
|
||||
pub const XENORA_PE_ERROR: i32 = 5;
|
||||
pub const XENORA_LIMIT_EXCEEDED: i32 = 6;
|
||||
pub const XENORA_BUFFER_TOO_SMALL: i32 = 7;
|
||||
pub const XENORA_EXECUTION_FAILED: i32 = 8;
|
||||
|
||||
pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4;
|
||||
pub const XENORA_FIXTURE_FRAME_HEIGHT: u32 = 3;
|
||||
const FRAME_BYTES: usize = (XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4) as usize;
|
||||
|
||||
/// Upper bound on simultaneously live sessions.
|
||||
const MAX_SESSIONS: usize = 64;
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
|
||||
struct Slot {
|
||||
/// Odd while live, even while free; starts at 0 so the first handle is never 0.
|
||||
generation: u32,
|
||||
}
|
||||
|
||||
static SESSIONS: Mutex<Vec<Slot>> = Mutex::new(Vec::new());
|
||||
|
||||
fn guarded(f: impl FnOnce() -> i32) -> i32 {
|
||||
catch_unwind(AssertUnwindSafe(f)).unwrap_or(XENORA_INTERNAL_ERROR)
|
||||
}
|
||||
|
||||
fn split(handle: u64) -> (usize, u32) {
|
||||
((handle & 0xFFFF_FFFF) as usize, (handle >> 32) as u32)
|
||||
}
|
||||
|
||||
fn is_live(slots: &[Slot], handle: u64) -> bool {
|
||||
let (index, generation) = split(handle);
|
||||
slots
|
||||
.get(index)
|
||||
.is_some_and(|slot| slot.generation == generation && generation % 2 == 1)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_abi_version() -> u32 {
|
||||
XENORA_ABI_VERSION
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `out_session` must be null or valid for one aligned `u64` write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *mut u64) -> i32 {
|
||||
guarded(|| {
|
||||
if out_session.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
if abi_version != XENORA_ABI_VERSION {
|
||||
return XENORA_VERSION_MISMATCH;
|
||||
}
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
return XENORA_INTERNAL_ERROR;
|
||||
};
|
||||
let index = match slots.iter().position(|slot| slot.generation % 2 == 0) {
|
||||
Some(index) => index,
|
||||
None if slots.len() < MAX_SESSIONS => {
|
||||
slots.push(Slot { generation: 0 });
|
||||
slots.len() - 1
|
||||
}
|
||||
None => return XENORA_LIMIT_EXCEEDED,
|
||||
};
|
||||
let slot = &mut slots[index];
|
||||
// ponytail: a slot retires after 2^31 reuses instead of wrapping its generation.
|
||||
let Some(generation) = slot.generation.checked_add(1) else {
|
||||
return XENORA_LIMIT_EXCEEDED;
|
||||
};
|
||||
slot.generation = generation;
|
||||
// SAFETY: checked non-null above; the caller guarantees validity.
|
||||
unsafe { out_session.write((u64::from(generation) << 32) | index as u64) };
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_session_destroy(session: u64) -> i32 {
|
||||
guarded(|| {
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
return XENORA_INTERNAL_ERROR;
|
||||
};
|
||||
if !is_live(&slots, session) {
|
||||
return XENORA_INVALID_HANDLE;
|
||||
}
|
||||
slots[split(session).0].generation += 1;
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Each output pointer must be null or valid for one aligned `u32` write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_inspect_trusted_fixture(
|
||||
session: u64,
|
||||
out_section_count: *mut u32,
|
||||
out_entry_rva: *mut u32,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_section_count.is_null() || out_entry_rva.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
match SESSIONS.lock() {
|
||||
Ok(slots) if is_live(&slots, session) => {}
|
||||
Ok(_) => return XENORA_INVALID_HANDLE,
|
||||
Err(_) => return XENORA_INTERNAL_ERROR,
|
||||
}
|
||||
let Ok(pe) = ParsedPe::parse(FIXTURE) else {
|
||||
return XENORA_PE_ERROR;
|
||||
};
|
||||
// SAFETY: both checked non-null above; the caller guarantees validity.
|
||||
unsafe {
|
||||
out_section_count.write(u32::from(pe.number_of_sections));
|
||||
out_entry_rva.write(pe.entry_point_rva);
|
||||
}
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
// The trusted fixture's contract, as checked by the CLI runner (crates/cli/src/runner.rs).
|
||||
// ponytail: duplicated from the runner so the CLI stays untouched; extract a shared
|
||||
// fixture-run function into a library when a third caller appears.
|
||||
const IMAGE_BASE: u64 = 0x1_5000_0000;
|
||||
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
|
||||
const TICKET: u64 = 17;
|
||||
const DRAW_RESULT: u64 = 0x42;
|
||||
const ENTRY_STEPS: usize = 100;
|
||||
/// `x9-constant-ps.s` exports (1.0, 0, 0, 1.0) to mrt0; in an RGBA8 target that is opaque red.
|
||||
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
fn draw() -> Result<Vec<u8>, String> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
|
||||
let pixels = gpu
|
||||
.render_rgba8(
|
||||
&shader.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
[
|
||||
XENORA_FIXTURE_FRAME_WIDTH as usize,
|
||||
XENORA_FIXTURE_FRAME_HEIGHT as usize,
|
||||
],
|
||||
[19, 43, 93, 251],
|
||||
)
|
||||
.map_err(|e| format!("Metal render: {e}"))?;
|
||||
if pixels != EXPECTED_PIXEL.repeat(FRAME_BYTES / 4) {
|
||||
return Err("read-back frame differs from the fixture shader's output".into());
|
||||
}
|
||||
Ok(pixels)
|
||||
}
|
||||
|
||||
/// Run the embedded fixture and return its verified frame.
|
||||
fn run_fixture() -> Result<Vec<u8>, String> {
|
||||
let frame = Arc::new(Mutex::new(None));
|
||||
let draw_frame = Arc::clone(&frame);
|
||||
let mut imports = ImportRegistry::new();
|
||||
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
|
||||
let fault = ExitReason::IllegalInstruction(0xff);
|
||||
let ticket = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let mut slot = draw_frame.lock().map_err(|_| fault)?;
|
||||
if slot.is_some()
|
||||
|| ticket != TICKET_ADDRESS
|
||||
|| memory.read_u64(ticket).map_err(ExitReason::MemoryFault)? != TICKET
|
||||
{
|
||||
return Err(fault);
|
||||
}
|
||||
let result = draw();
|
||||
let ok = result.is_ok();
|
||||
*slot = Some(result);
|
||||
if ok { Ok(DRAW_RESULT) } else { Err(fault) }
|
||||
});
|
||||
let startup = run_synthetic_startup(
|
||||
FIXTURE,
|
||||
StartupLayout {
|
||||
image_base: IMAGE_BASE,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
},
|
||||
imports,
|
||||
ENTRY_STEPS,
|
||||
)
|
||||
.map_err(|e| format!("startup: {e}"))?;
|
||||
let drawn = frame.lock().map_err(|_| "frame lock poisoned")?.take();
|
||||
if let Some(Err(e)) = drawn {
|
||||
return Err(e);
|
||||
}
|
||||
let execution = &startup.execution;
|
||||
if execution.exit_reason != ExitReason::Halt
|
||||
|| startup.relocations.applied_dir64 != 4
|
||||
|| startup.bound_imports != 1
|
||||
|| startup.tls_callbacks != 1
|
||||
|| execution.final_state.get(Register::Rax) != DRAW_RESULT
|
||||
{
|
||||
return Err(format!(
|
||||
"unexpected guest result: {:?}",
|
||||
execution.exit_reason
|
||||
));
|
||||
}
|
||||
drawn.ok_or_else(|| String::from("guest halted without a draw"))?
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `out_rgba` must be null or valid for `capacity` byte writes; each `u32` output
|
||||
/// must be null or valid for one aligned write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_run_trusted_fixture(
|
||||
session: u64,
|
||||
out_rgba: *mut u8,
|
||||
capacity: u64,
|
||||
out_width: *mut u32,
|
||||
out_height: *mut u32,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_rgba.is_null() || out_width.is_null() || out_height.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
match SESSIONS.lock() {
|
||||
Ok(slots) if is_live(&slots, session) => {}
|
||||
Ok(_) => return XENORA_INVALID_HANDLE,
|
||||
Err(_) => return XENORA_INTERNAL_ERROR,
|
||||
}
|
||||
if capacity < FRAME_BYTES as u64 {
|
||||
return XENORA_BUFFER_TOO_SMALL;
|
||||
}
|
||||
let Ok(pixels) = run_fixture() else {
|
||||
return XENORA_EXECUTION_FAILED;
|
||||
};
|
||||
// SAFETY: non-null and at least FRAME_BYTES long, both checked above.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, FRAME_BYTES);
|
||||
out_width.write(XENORA_FIXTURE_FRAME_WIDTH);
|
||||
out_height.write(XENORA_FIXTURE_FRAME_HEIGHT);
|
||||
}
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
pub const XENORA_MAX_INSPECT_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
/// Build the read-only inspection report and its status: `XENORA_OK`, `XENORA_PE_ERROR`
|
||||
/// for a rejected file, or `XENORA_INTERNAL_ERROR` if Xenora's own probe failed.
|
||||
fn inspection_report(bytes: &[u8]) -> (i32, String) {
|
||||
let mut out = String::from("Xenora read-only inspection: nothing in this file was executed.\n");
|
||||
let _ = writeln!(out, "file_size: {} bytes", bytes.len());
|
||||
let probed = catch_unwind(AssertUnwindSafe(|| {
|
||||
probe_pe_bytes(bytes, &ProbeConfig::default())
|
||||
}));
|
||||
let report = match probed {
|
||||
Ok(Ok(report)) => report,
|
||||
Ok(Err(e)) => {
|
||||
let _ = writeln!(out, "verdict: not a supported PE32+ (x86-64) image: {e}");
|
||||
return (XENORA_PE_ERROR, out);
|
||||
}
|
||||
Err(_) => {
|
||||
out.push_str(
|
||||
"verdict: inspection failed inside Xenora's static probe. This is a Xenora \
|
||||
defect, not a finding about the file.\n",
|
||||
);
|
||||
return (XENORA_INTERNAL_ERROR, out);
|
||||
}
|
||||
};
|
||||
let pe = &report.parsed;
|
||||
let _ = writeln!(out, "sha256: {}", report.sha256);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"machine: {:#06x} image_base: {:#x} entry_rva: {:#x} size_of_image: {:#x}",
|
||||
pe.machine, pe.image_base, pe.entry_point_rva, pe.size_of_image
|
||||
);
|
||||
match ParsedPe::parse(bytes) {
|
||||
Ok(_) => out.push_str("loader_validation: accepted\n"),
|
||||
Err(e) => {
|
||||
let _ = writeln!(out, "loader_validation: rejected: {e}");
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out, "\nsections ({}):", pe.sections.len());
|
||||
for s in &pe.sections {
|
||||
let p = s.permissions;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {:<8} rva {:#010x} vsize {:#x} raw {:#x} {}{}{}",
|
||||
s.name,
|
||||
s.virtual_address,
|
||||
s.virtual_size,
|
||||
s.raw_data_size,
|
||||
if p.read { 'r' } else { '-' },
|
||||
if p.write { 'w' } else { '-' },
|
||||
if p.execute { 'x' } else { '-' },
|
||||
);
|
||||
}
|
||||
let missing: Vec<_> = report.imports.iter().filter(|i| !i.is_supported).collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nimports: {} total, {} provided by Xenora's standard runtime services, {} not provided",
|
||||
report.imports.len(),
|
||||
report.imports.len() - missing.len(),
|
||||
missing.len()
|
||||
);
|
||||
for i in &missing {
|
||||
let _ = writeln!(out, " not provided: {}!{}", i.dll, i.symbol);
|
||||
}
|
||||
let decoded = report.instruction_records.len();
|
||||
let unsupported = report
|
||||
.instruction_records
|
||||
.iter()
|
||||
.filter(|r| !r.is_supported_dbt)
|
||||
.count();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nstatic disassembly (bounded): {decoded} instructions decoded, {unsupported} not supported by the ARM64 DBT"
|
||||
);
|
||||
if let Some(first) = &report.first_unsupported_dbt_insn {
|
||||
let hex: String = first.bytes.iter().map(|b| format!("{b:02x}")).collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" first unsupported: rva {:#x} {} [{hex}]",
|
||||
first.rva, first.mnemonic
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nrelocations: {} entries\ntls callbacks: {}",
|
||||
report.relocations.total_entries,
|
||||
report.tls.callback_targets.len()
|
||||
);
|
||||
out.push_str("\nExecution of opened files is not available (see #257).\n");
|
||||
(XENORA_OK, out)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `bytes` must be valid for `length` reads; `out_report` must be null or valid
|
||||
/// for `capacity` writes; `out_required` must be null or valid for one `u64` write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_inspect_executable(
|
||||
bytes: *const u8,
|
||||
length: u64,
|
||||
out_report: *mut std::ffi::c_char,
|
||||
capacity: u64,
|
||||
out_required: *mut u64,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if bytes.is_null() || out_report.is_null() || out_required.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
if length > XENORA_MAX_INSPECT_BYTES {
|
||||
return XENORA_LIMIT_EXCEEDED;
|
||||
}
|
||||
// SAFETY: non-null, and the caller guarantees `length` readable bytes.
|
||||
let input = unsafe { std::slice::from_raw_parts(bytes, length as usize) };
|
||||
let (status, text) = inspection_report(input);
|
||||
let required = text.len() as u64 + 1;
|
||||
// SAFETY: non-null, checked above.
|
||||
unsafe { out_required.write(required) };
|
||||
if capacity < required {
|
||||
return XENORA_BUFFER_TOO_SMALL;
|
||||
}
|
||||
// SAFETY: `capacity >= required`, checked above.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(text.as_ptr(), out_report.cast::<u8>(), text.len());
|
||||
out_report.add(text.len()).write(0);
|
||||
}
|
||||
status
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::ptr::null_mut;
|
||||
|
||||
/// The session table is process-global, so tests that fill or count it run one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn serial() -> std::sync::MutexGuard<'static, ()> {
|
||||
SERIAL
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn create() -> u64 {
|
||||
let mut handle = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
fn inspect(handle: u64) -> (i32, u32, u32) {
|
||||
let (mut sections, mut entry) = (u32::MAX, u32::MAX);
|
||||
let status =
|
||||
unsafe { xenora_session_inspect_trusted_fixture(handle, &mut sections, &mut entry) };
|
||||
(status, sections, entry)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_and_rust_constants_agree() {
|
||||
let header = include_str!("../include/xenora.h");
|
||||
assert!(header.contains(&format!("#define XENORA_ABI_VERSION {XENORA_ABI_VERSION}u")));
|
||||
for (name, value) in [
|
||||
("XENORA_OK", XENORA_OK),
|
||||
("XENORA_INVALID_ARGUMENT", XENORA_INVALID_ARGUMENT),
|
||||
("XENORA_INVALID_HANDLE", XENORA_INVALID_HANDLE),
|
||||
("XENORA_VERSION_MISMATCH", XENORA_VERSION_MISMATCH),
|
||||
("XENORA_INTERNAL_ERROR", XENORA_INTERNAL_ERROR),
|
||||
("XENORA_PE_ERROR", XENORA_PE_ERROR),
|
||||
("XENORA_LIMIT_EXCEEDED", XENORA_LIMIT_EXCEEDED),
|
||||
("XENORA_BUFFER_TOO_SMALL", XENORA_BUFFER_TOO_SMALL),
|
||||
("XENORA_EXECUTION_FAILED", XENORA_EXECUTION_FAILED),
|
||||
] {
|
||||
assert!(header.contains(&format!("{name} = {value},")), "{name}");
|
||||
}
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FIXTURE_FRAME_WIDTH {XENORA_FIXTURE_FRAME_WIDTH}u"
|
||||
)));
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FIXTURE_FRAME_HEIGHT {XENORA_FIXTURE_FRAME_HEIGHT}u"
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_inspects_the_trusted_fixture() {
|
||||
let _serial = serial();
|
||||
let handle = create();
|
||||
// Independent expectation: read straight from the fixture's COFF and optional headers.
|
||||
let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap());
|
||||
let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap());
|
||||
assert_eq!(inspect(handle), (XENORA_OK, u32::from(sections), entry));
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_mismatch_and_null_outputs_are_rejected() {
|
||||
let _serial = serial();
|
||||
let mut handle = 7;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(2, &mut handle) },
|
||||
XENORA_VERSION_MISMATCH
|
||||
);
|
||||
assert_eq!(handle, 7, "output untouched on failure");
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(1, null_mut()) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
let live = create();
|
||||
let mut x = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_inspect_trusted_fixture(live, null_mut(), &mut x) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
xenora_session_destroy(live);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_stale_and_double_destroyed_handles_are_rejected() {
|
||||
let _serial = serial();
|
||||
for bogus in [0, u64::MAX, 0xFFFF_FFFF, 1 << 32] {
|
||||
assert_eq!(
|
||||
xenora_session_destroy(bogus),
|
||||
XENORA_INVALID_HANDLE,
|
||||
"{bogus:#x}"
|
||||
);
|
||||
assert_eq!(inspect(bogus), (XENORA_INVALID_HANDLE, u32::MAX, u32::MAX));
|
||||
}
|
||||
let handle = create();
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_INVALID_HANDLE);
|
||||
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
|
||||
// Reusing the slot must not revive the old handle.
|
||||
let reused: Vec<u64> = (0..MAX_SESSIONS).map(|_| create()).collect();
|
||||
assert!(!reused.contains(&handle));
|
||||
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
|
||||
for h in reused {
|
||||
xenora_session_destroy(h);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_and_concurrent_lifecycles_do_not_leak_slots() {
|
||||
let _serial = serial();
|
||||
let threads: Vec<_> = (0..8)
|
||||
.map(|_| {
|
||||
std::thread::spawn(|| {
|
||||
for _ in 0..500 {
|
||||
let mut handle = 0;
|
||||
let status = unsafe { xenora_session_create(1, &mut handle) };
|
||||
assert_eq!(status, XENORA_OK);
|
||||
assert_eq!(inspect(handle).0, XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for t in threads {
|
||||
t.join().unwrap();
|
||||
}
|
||||
assert!(SESSIONS.lock().unwrap().len() <= MAX_SESSIONS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panics_do_not_cross_the_boundary() {
|
||||
assert_eq!(guarded(|| panic!("injected")), XENORA_INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixture_run_rejects_bad_arguments_before_executing() {
|
||||
let _serial = serial();
|
||||
let handle = create();
|
||||
let (mut buf, mut w, mut h) = ([0u8; 48], 0u32, 0u32);
|
||||
let run = |session, buf: *mut u8, cap, w: *mut u32, h: *mut u32| unsafe {
|
||||
xenora_session_run_trusted_fixture(session, buf, cap, w, h)
|
||||
};
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 47, &mut w, &mut h),
|
||||
XENORA_BUFFER_TOO_SMALL
|
||||
);
|
||||
assert_eq!(
|
||||
run(handle, null_mut(), 48, &mut w, &mut h),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 48, null_mut(), &mut h),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
xenora_session_destroy(handle);
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 48, &mut w, &mut h),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
assert_eq!((w, h), (0, 0), "outputs untouched on failure");
|
||||
assert!(buf.iter().all(|&b| b == 0));
|
||||
}
|
||||
|
||||
fn inspect_bytes(bytes: &[u8]) -> (i32, String) {
|
||||
let mut required = 0;
|
||||
let mut buf = vec![0 as std::ffi::c_char; 1];
|
||||
let status = unsafe {
|
||||
xenora_inspect_executable(
|
||||
bytes.as_ptr(),
|
||||
bytes.len() as u64,
|
||||
buf.as_mut_ptr(),
|
||||
1,
|
||||
&mut required,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, XENORA_BUFFER_TOO_SMALL);
|
||||
assert_eq!(buf[0], 0, "nothing written when the buffer is too small");
|
||||
buf.resize(required as usize, 0);
|
||||
let status = unsafe {
|
||||
xenora_inspect_executable(
|
||||
bytes.as_ptr(),
|
||||
bytes.len() as u64,
|
||||
buf.as_mut_ptr(),
|
||||
required,
|
||||
&mut required,
|
||||
)
|
||||
};
|
||||
let text = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) }
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_eq!(text.len() as u64 + 1, required);
|
||||
(status, text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_reports_independently_read_facts_of_a_fixture() {
|
||||
let (status, text) = inspect_bytes(FIXTURE);
|
||||
assert_eq!(status, XENORA_OK);
|
||||
let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap());
|
||||
let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap());
|
||||
assert!(text.contains(&format!("file_size: {} bytes", FIXTURE.len())));
|
||||
assert!(text.contains(&format!("entry_rva: {entry:#x}")));
|
||||
assert!(text.contains(&format!("sections ({sections}):")));
|
||||
assert!(text.contains("loader_validation: accepted"));
|
||||
assert!(
|
||||
text.contains("xenora.dll") || text.contains("1 provided by Xenora"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains("nothing in this file was executed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_rejects_malformed_and_oversized_input() {
|
||||
for bad in [&b""[..], b"not a pe file", &[0u8; 0x100]] {
|
||||
let (status, text) = inspect_bytes(bad);
|
||||
assert_eq!(status, XENORA_PE_ERROR, "{text}");
|
||||
assert!(text.contains("not a supported PE32+"), "{text}");
|
||||
}
|
||||
// Every truncation of a valid file yields a report and a deterministic status.
|
||||
// Some truncations currently hit a panic inside the loader's static probe
|
||||
// (probe.rs, #270); the boundary must turn it into a report.
|
||||
for len in (0..FIXTURE.len()).step_by(7) {
|
||||
let (status, text) = inspect_bytes(&FIXTURE[..len]);
|
||||
assert!(
|
||||
matches!(status, XENORA_OK | XENORA_PE_ERROR | XENORA_INTERNAL_ERROR),
|
||||
"len {len}"
|
||||
);
|
||||
assert_eq!(
|
||||
inspect_bytes(&FIXTURE[..len]),
|
||||
(status, text),
|
||||
"len {len} is deterministic"
|
||||
);
|
||||
}
|
||||
let (mut req, mut c) = (0u64, 0 as std::ffi::c_char);
|
||||
let one = [0u8];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_inspect_executable(
|
||||
one.as_ptr(),
|
||||
XENORA_MAX_INSPECT_BYTES + 1,
|
||||
&mut c,
|
||||
1,
|
||||
&mut req,
|
||||
)
|
||||
},
|
||||
XENORA_LIMIT_EXCEEDED
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { xenora_inspect_executable(std::ptr::null(), 0, &mut c, 1, &mut req) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Runs the trusted fixture through the C interface on a native Metal device.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
|
||||
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
|
||||
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
#[test]
|
||||
fn guest_fixture_frame_reaches_the_caller_through_metal() {
|
||||
for run in 0..3 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
|
||||
let status = unsafe {
|
||||
xenora_session_run_trusted_fixture(
|
||||
session,
|
||||
rgba.as_mut_ptr(),
|
||||
64,
|
||||
&mut width,
|
||||
&mut height,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, XENORA_OK, "run {run}");
|
||||
assert_eq!((width, height), (4, 3));
|
||||
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
|
||||
assert!(
|
||||
rgba[48..].iter().all(|&b| b == 0),
|
||||
"no write past the frame"
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
}
|
||||
@@ -17,16 +17,6 @@ VARIANTS = (
|
||||
("V_ADD_NC_U32", "ENC_VOP3"),
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_ADD_U32", "ENC_SOP2"),
|
||||
("S_SUB_U32", "ENC_SOP2"),
|
||||
("S_ADD_I32", "ENC_SOP2"),
|
||||
("S_SUB_I32", "ENC_SOP2"),
|
||||
("S_ADDC_U32", "ENC_SOP2"),
|
||||
("S_SUBB_U32", "ENC_SOP2"),
|
||||
("S_AND_B32", "ENC_SOP2"),
|
||||
("S_OR_B32", "ENC_SOP2"),
|
||||
("S_XOR_B32", "ENC_SOP2"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
|
||||
Executable
+838
@@ -0,0 +1,838 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the declarative gfx1030 semantic registry and generate its Rust tables.
|
||||
|
||||
validate check crates/isa/semantics/rdna2.toml against its closed vocabulary
|
||||
and the pinned AMD XML snapshot (crates/isa/data/rdna2.jsonl)
|
||||
generate validate, then write crates/isa/src/semantics_gen.rs
|
||||
--check validate and regenerate in memory; exit 1 if the committed file
|
||||
differs. Never writes.
|
||||
|
||||
The registry is data only. Behaviour is chosen from a closed set of primitives
|
||||
(crates/isa/src/primitive.rs) by the declared operation, signedness and SCC
|
||||
effect, never from a mnemonic. Only the Python standard library is used
|
||||
(tomllib needs Python 3.11 or newer). See docs/shaders/semantic-registry.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
|
||||
sys.exit("generate_semantics.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REGISTRY = ROOT / "crates/isa/semantics/rdna2.toml"
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/semantics_gen.rs"
|
||||
|
||||
SCHEMA = 1
|
||||
ARCHITECTURE = "gfx1030"
|
||||
|
||||
FORM_KEYS = {
|
||||
"name", "family", "opcode", "variant", "operation", "signedness", "carry_in",
|
||||
"width", "scc", "vcc", "exec", "wave", "operands", "spec", "verify",
|
||||
}
|
||||
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
|
||||
|
||||
OPERATIONS = {
|
||||
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
|
||||
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
|
||||
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
|
||||
"compare": "Compare",
|
||||
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
|
||||
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
|
||||
"sext": "SignExtend", "abs": "Absolute",
|
||||
"min": "Minimum", "max": "Maximum", "cselect": "Select", "bfm": "BitfieldMask",
|
||||
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
|
||||
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
# Sign extension reads only the low source_bits of S0 (required for sext only).
|
||||
SOURCE_BITS_KEY = "source_bits"
|
||||
SOURCE_BITS = {8, 16}
|
||||
# Compares take a relation (S0 on the left) and set SCC to whether it holds.
|
||||
RELATION_KEY = "relation"
|
||||
RELATIONS = {
|
||||
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
|
||||
"lt": "Less", "le": "LessOrEqual",
|
||||
}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
COMPARE_PRIMITIVES = {
|
||||
("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32",
|
||||
("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32",
|
||||
("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32",
|
||||
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
|
||||
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
|
||||
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
|
||||
}
|
||||
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
|
||||
# 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",
|
||||
}
|
||||
ARITHMETIC = {"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add"}
|
||||
SHIFTS = {"lshl", "lshr", "ashr"}
|
||||
# Operations whose S1 is an unsigned control word (a shift count or a bit-field
|
||||
# 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"}
|
||||
# XML number formats a source may have for each declared signedness.
|
||||
SOURCE_FORMATS = {
|
||||
"signed": {"FMT_NUM_I32"},
|
||||
"unsigned": {"FMT_NUM_U32"},
|
||||
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
|
||||
}
|
||||
# Optional keys: required exactly when the condition holds.
|
||||
SHIFT_KEY = "shift_count_bits"
|
||||
# Shift-and-add declares its fixed S0 shift (required for lshl_add only).
|
||||
SHIFT_AMOUNT_KEY = "shift_amount"
|
||||
SHIFT_AMOUNTS = {1, 2, 3, 4}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
SCC = {
|
||||
"unchanged": "Unchanged",
|
||||
"carry_out": "CarryOut",
|
||||
"borrow": "Borrow",
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
"relation": "Relation",
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# The decoder has no wave-size input at the registry dispatch yet, so a Wave32
|
||||
# restriction could be declared but not enforced. Reject it until it can be.
|
||||
ENFORCED_WAVES = {"any"}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
"metal": "Metal",
|
||||
"llvm_encoding": "LlvmEncoding",
|
||||
}
|
||||
DOCUMENTS = {"guide": "Guide", "xml": "Xml"}
|
||||
# The public documents spec references may cite, pinned so a citation cannot
|
||||
# silently point at another file.
|
||||
PINNED_DOCUMENTS = {
|
||||
"guide": {
|
||||
"title": "AMD RDNA 2 Instruction Set Architecture Reference Guide",
|
||||
"file": "rdna2-shader-instruction-set-architecture.pdf",
|
||||
"pages": 291,
|
||||
},
|
||||
"xml": {
|
||||
"title": "AMD RDNA 2 machine-readable ISA (pinned XML)",
|
||||
"file": "amdgpu_isa_rdna2.xml",
|
||||
},
|
||||
}
|
||||
WIDTHS = {32}
|
||||
|
||||
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
|
||||
# A form whose declaration is not a row here has no primitive and is rejected.
|
||||
PRIMITIVES = {
|
||||
("add", "unsigned"): ("carry_out", "add_carry_u32", True),
|
||||
("sub", "unsigned"): ("borrow", "sub_borrow_u32", True),
|
||||
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
|
||||
("sub", "signed"): ("signed_overflow", "sub_overflow_i32", False),
|
||||
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
|
||||
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
|
||||
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
|
||||
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
|
||||
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
|
||||
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
|
||||
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
|
||||
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
|
||||
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
|
||||
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
|
||||
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
|
||||
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
|
||||
("brev", "bitwise"): ("unchanged", "brev_b32", False),
|
||||
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
|
||||
("bcnt1", "bitwise"): ("nonzero", "bcnt1_nonzero_b32", False),
|
||||
("ff0", "bitwise"): ("unchanged", "ff0_b32", False),
|
||||
("ff1", "bitwise"): ("unchanged", "ff1_b32", False),
|
||||
("flbit", "bitwise"): ("unchanged", "flbit_b32", False),
|
||||
("flbit", "signed"): ("unchanged", "flbit_i32", False),
|
||||
("sext", "signed"): ("unchanged", "sext_i32", False),
|
||||
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
|
||||
("min", "signed"): ("selected_src0", "min_i32", False),
|
||||
("min", "unsigned"): ("selected_src0", "min_u32", False),
|
||||
("max", "signed"): ("selected_src0", "max_i32", False),
|
||||
("max", "unsigned"): ("selected_src0", "max_u32", False),
|
||||
("cselect", "bitwise"): ("unchanged", "cselect_b32", True),
|
||||
("bfm", "bitwise"): ("unchanged", "bfm_b32", False),
|
||||
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
|
||||
("mul_hi", "unsigned"): ("unchanged", "mul_hi_u32", False),
|
||||
("mul_hi", "signed"): ("unchanged", "mul_hi_i32", False),
|
||||
("bfe", "unsigned"): ("nonzero", "bfe_nonzero_u32", False),
|
||||
("bfe", "signed"): ("nonzero", "bfe_nonzero_i32", False),
|
||||
("absdiff", "signed"): ("nonzero", "absdiff_nonzero_i32", False),
|
||||
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
# match one of these shapes; anything else is an unimplemented rule.
|
||||
UNSUPPORTED_COMBOS = {
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
|
||||
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
|
||||
}
|
||||
OPERAND_RULES = {
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
"enum": "ScalarAluOp",
|
||||
"shape": {
|
||||
"family": "SOP2",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# Every one of these is rejected by the decoder's SOP2 operand checks.
|
||||
"unsupported": UNSUPPORTED_COMBOS,
|
||||
"kind": "alu",
|
||||
},
|
||||
"sopc_scalar": {
|
||||
"rust": "SopcScalar",
|
||||
"enum": "ScalarCompareOp",
|
||||
"shape": {
|
||||
"family": "SOPC",
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# SOPC has no destination field; the decoder rejects these sources.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")},
|
||||
"kind": "compare",
|
||||
},
|
||||
"sop1_sgpr": {
|
||||
"rust": "Sop1Sgpr",
|
||||
"enum": "ScalarUnaryOp",
|
||||
"shape": {
|
||||
"family": "SOP1",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [{"field": "SSRC0", "class": "scalar_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# One source, so two literals cannot occur; the rest are rejected.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
}
|
||||
|
||||
VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$")
|
||||
RESERVED_VARIANTS = {"Self", "ALL"}
|
||||
U16_MAX = 0xFFFF
|
||||
NAME = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
||||
SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$")
|
||||
|
||||
|
||||
def load_registry(path=REGISTRY):
|
||||
"""Parse the TOML registry into a dict."""
|
||||
with open(path, "rb") as handle:
|
||||
return tomllib.load(handle)
|
||||
|
||||
|
||||
def load_snapshot(path=SNAPSHOT):
|
||||
"""Index the normalised XML snapshot: source line, encodings, default variants."""
|
||||
source = None
|
||||
encodings = {}
|
||||
variants = {}
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
record = json.loads(line)
|
||||
kind = record.get("kind")
|
||||
if kind == "source":
|
||||
source = record
|
||||
elif kind == "encoding":
|
||||
encodings[record["name"]] = record
|
||||
elif kind == "variant" and record.get("condition") == "default":
|
||||
variants[(record["instruction"], record["encoding"])] = record
|
||||
return {"source": source or {}, "encodings": encodings, "variants": variants}
|
||||
|
||||
|
||||
def _family_encoding(family):
|
||||
return "ENC_" + family
|
||||
|
||||
|
||||
def _rust_family(family):
|
||||
return family[0] + family[1:].lower()
|
||||
|
||||
|
||||
def _check_rule(name, rule, errors):
|
||||
implemented = OPERAND_RULES.get(name)
|
||||
if implemented is None:
|
||||
errors.append(f"operand rule {name}: not implemented by the decoder")
|
||||
return
|
||||
unsupported = rule.get("unsupported", [])
|
||||
unknown = sorted(set(unsupported) - UNSUPPORTED_COMBOS)
|
||||
if unknown:
|
||||
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
|
||||
if len(set(unsupported)) != len(unsupported):
|
||||
errors.append(f"operand rule {name}: duplicate unsupported combos")
|
||||
if set(unsupported) != implemented["unsupported"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: unsupported combos differ from those the decoder rejects"
|
||||
)
|
||||
declared = {key: value for key, value in rule.items() if key != "unsupported"}
|
||||
if declared != implemented["shape"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: declaration differs from the decoder's implemented rule"
|
||||
)
|
||||
|
||||
|
||||
def _check_xml(form, rule, snapshot, errors):
|
||||
label = form["name"]
|
||||
encoding_name = _family_encoding(form["family"])
|
||||
encoding = snapshot["encodings"].get(encoding_name)
|
||||
if encoding is None:
|
||||
errors.append(f"{label}: family {form['family']} has no XML encoding {encoding_name}")
|
||||
return
|
||||
variant = snapshot["variants"].get((form["name"], encoding_name))
|
||||
if variant is None:
|
||||
errors.append(f"{label}: no default {encoding_name} variant in the XML snapshot")
|
||||
return
|
||||
if variant["opcode"] != form["opcode"]:
|
||||
errors.append(
|
||||
f"{label}: opcode {form['opcode']} disagrees with the XML opcode {variant['opcode']}"
|
||||
)
|
||||
if _identifier(encoding, form["opcode"]) not in encoding["identifiers"]:
|
||||
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
|
||||
if scc_out != (form["scc"] != "unchanged"):
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
|
||||
if rule is None:
|
||||
return
|
||||
if not isinstance(rule.get("src"), list) or not all(
|
||||
isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]
|
||||
) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])):
|
||||
return # the rule check already reported the malformed shape
|
||||
fields = [(rule["dst"]["field"], False)] if "dst" in rule else []
|
||||
fields += [(src["field"], True) for src in rule["src"]]
|
||||
shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1
|
||||
count_field = rule["src"][1]["field"] if shift else None
|
||||
for field, is_source in fields:
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
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):
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
if field == count_field:
|
||||
if data_format != "FMT_NUM_U32":
|
||||
errors.append(
|
||||
f"{label}: control operand {field} has XML format {data_format}, not FMT_NUM_U32"
|
||||
)
|
||||
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"], ()):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
extra = sorted(set(operands) - {field for field, _ in fields})
|
||||
if extra:
|
||||
errors.append(f"{label}: XML operands {extra} are not covered by rule {form['operands']}")
|
||||
|
||||
|
||||
def _identifier(encoding, opcode):
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
(offset, size), = fields["OP"]
|
||||
base = encoding["identifiers"][0] & ~(((1 << size) - 1) << offset)
|
||||
return base | (opcode << offset)
|
||||
|
||||
|
||||
def validate(registry, snapshot):
|
||||
"""Return every error in the registry; an empty list means it is valid."""
|
||||
errors = []
|
||||
unknown = sorted(set(registry) - TOP_KEYS)
|
||||
if unknown:
|
||||
errors.append(f"unknown top-level keys {unknown}")
|
||||
if type(registry.get("schema")) is not int or registry["schema"] != SCHEMA:
|
||||
errors.append(f"schema {registry.get('schema')!r} is not {SCHEMA}")
|
||||
if registry.get("architecture") != ARCHITECTURE:
|
||||
errors.append(f"architecture {registry.get('architecture')!r} is not {ARCHITECTURE}")
|
||||
if registry.get("source_sha256") != snapshot["source"].get("sha256"):
|
||||
errors.append("source_sha256 does not match the XML snapshot")
|
||||
documents = registry.get("documents", {})
|
||||
for name, document in documents.items():
|
||||
if name not in DOCUMENTS:
|
||||
errors.append(f"unknown document {name}")
|
||||
elif document != PINNED_DOCUMENTS[name]:
|
||||
errors.append(f"document {name}: differs from the pinned public document")
|
||||
if "guide" not in documents:
|
||||
errors.append("the guide document is not declared")
|
||||
rules = registry.get("operand_rules", {})
|
||||
for name, rule in rules.items():
|
||||
_check_rule(name, rule, errors)
|
||||
forms = registry.get("form", [])
|
||||
if not forms:
|
||||
errors.append("the registry declares no forms")
|
||||
seen = {"name": set(), "opcode": set(), "variant": set()}
|
||||
for index, form in enumerate(forms):
|
||||
label = form.get("name", f"form #{index}")
|
||||
missing = sorted(FORM_KEYS - set(form))
|
||||
extra = sorted(
|
||||
set(form) - FORM_KEYS - {SHIFT_KEY, SHIFT_AMOUNT_KEY, RELATION_KEY, SOURCE_BITS_KEY}
|
||||
)
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
errors.append(f"{label}: unknown keys {extra}")
|
||||
if missing:
|
||||
continue
|
||||
for key, vocabulary in (
|
||||
("operation", OPERATIONS), ("signedness", SIGNEDNESS), ("carry_in", CARRY_IN),
|
||||
("scc", SCC), ("vcc", MASK), ("exec", MASK), ("wave", WAVE),
|
||||
):
|
||||
if form[key] not in vocabulary:
|
||||
errors.append(f"{label}: unknown {key} {form[key]!r}")
|
||||
if not isinstance(form["name"], str) or not NAME.match(form["name"]):
|
||||
errors.append(f"{label}: invalid name")
|
||||
if not isinstance(form["variant"], str) or not VARIANT.match(form["variant"]):
|
||||
errors.append(f"{label}: invalid variant {form['variant']!r}")
|
||||
if form["variant"] in RESERVED_VARIANTS:
|
||||
errors.append(f"{label}: variant {form['variant']!r} is reserved")
|
||||
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid opcode")
|
||||
if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES:
|
||||
errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet")
|
||||
if type(form["width"]) is not int or form["width"] not in WIDTHS:
|
||||
errors.append(f"{label}: width {form['width']} is not supported")
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
("opcode", (form["family"], form["opcode"])),
|
||||
("variant", form["variant"]),
|
||||
):
|
||||
if value in seen[key]:
|
||||
errors.append(f"{label}: duplicate {key} {value}")
|
||||
seen[key].add(value)
|
||||
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
|
||||
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
|
||||
):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
|
||||
)
|
||||
if form["operation"] in SHIFTS:
|
||||
bits = form.get(SHIFT_KEY)
|
||||
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
|
||||
)
|
||||
elif SHIFT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
|
||||
if form["operation"] == "lshl_add":
|
||||
amount = form.get(SHIFT_AMOUNT_KEY)
|
||||
if type(amount) is not int or amount not in SHIFT_AMOUNTS:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_AMOUNT_KEY} must be one of {sorted(SHIFT_AMOUNTS)}, got {amount!r}"
|
||||
)
|
||||
elif SHIFT_AMOUNT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_AMOUNT_KEY} on a non-lshl_add operation")
|
||||
if 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)
|
||||
if type(bits) is not int or bits not in SOURCE_BITS:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} must be one of {sorted(SOURCE_BITS)}, got {bits!r}")
|
||||
elif SOURCE_BITS_KEY in form:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} on a non-sext operation")
|
||||
if form["operation"] == "compare":
|
||||
relation = form.get(RELATION_KEY)
|
||||
if not isinstance(relation, str) or relation not in RELATIONS:
|
||||
errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}")
|
||||
elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES:
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
if form["scc"] != "relation":
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)")
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = ("relation", None, 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"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
scc, _, takes_carry = primitive
|
||||
if form["scc"] != scc:
|
||||
errors.append(
|
||||
f"{label}: scc {form['scc']} contradicts {form['operation']}/"
|
||||
f"{form['signedness']} (requires {scc})"
|
||||
)
|
||||
if form["carry_in"] == "scc" and not takes_carry:
|
||||
errors.append(f"{label}: carry_in scc contradicts {form['operation']}/{form['signedness']}")
|
||||
rule = rules.get(form["operands"])
|
||||
if rule is None:
|
||||
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
"compare" if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
verify = form["verify"]
|
||||
if not verify:
|
||||
errors.append(f"{label}: no verification requirement")
|
||||
if any(item not in EVIDENCE for item in verify):
|
||||
errors.append(f"{label}: unknown verification requirement in {verify}")
|
||||
if len(set(verify)) != len(verify):
|
||||
errors.append(f"{label}: duplicate verification requirement")
|
||||
_check_xml(form, rule, snapshot, errors)
|
||||
return errors
|
||||
|
||||
|
||||
def _check_spec(label, spec, documents, errors):
|
||||
has_guide = False
|
||||
for ref in spec:
|
||||
if set(ref) != {"document", "section", "page"}:
|
||||
errors.append(f"{label}: spec reference needs exactly document, section, page")
|
||||
continue
|
||||
if ref["document"] not in documents:
|
||||
errors.append(f"{label}: spec cites undeclared document {ref['document']!r}")
|
||||
if not SECTION.match(str(ref["section"])):
|
||||
errors.append(f"{label}: invalid spec section {ref['section']!r}")
|
||||
if type(ref["page"]) is not int or not 0 <= ref["page"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid spec page")
|
||||
if ref["document"] == "guide" and type(ref["page"]) is int and ref["page"] > 0:
|
||||
has_guide = True
|
||||
if not has_guide:
|
||||
errors.append(f"{label}: missing a guide section and page reference")
|
||||
|
||||
|
||||
def render(registry, snapshot):
|
||||
"""Return the complete generated Rust source. Requires a valid registry."""
|
||||
forms = registry["form"]
|
||||
rule_names = sorted({form["operands"] for form in forms})
|
||||
positions = {form["name"]: position for position, form in enumerate(forms)}
|
||||
out = [
|
||||
"// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.",
|
||||
"// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate",
|
||||
"",
|
||||
"use crate::meta::EncodingFamily;",
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
"/// Registry schema of the generated tables.",
|
||||
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
|
||||
]
|
||||
for rule_name in rule_names:
|
||||
selected = [form for form in forms if form["operands"] == rule_name]
|
||||
out += _render_enum(rule_name, selected, snapshot, positions)
|
||||
out += [
|
||||
"",
|
||||
"/// Identity of every registry form, in registry order.",
|
||||
f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
out.append(f" (\"{form['name']}\", EncodingFamily::{_rust_family(form['family'])}),")
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
"/// One validated row per registry form, in registry order.",
|
||||
f"pub static FORMS: [FormSemantics; {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
spec = ", ".join(
|
||||
f"SpecRef {{ document: Document::{DOCUMENTS[ref['document']]}, "
|
||||
f"section: \"{ref['section']}\", page: {ref['page']} }}"
|
||||
for ref in form["spec"]
|
||||
)
|
||||
verify = ", ".join(f"Evidence::{EVIDENCE[item]}" for item in form["verify"])
|
||||
out += [
|
||||
" FormSemantics {",
|
||||
f" name: \"{form['name']}\",",
|
||||
f" family: EncodingFamily::{_rust_family(form['family'])},",
|
||||
f" opcode: {form['opcode']},",
|
||||
f" operation: Operation::{OPERATIONS[form['operation']]},",
|
||||
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
|
||||
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
|
||||
f" width: {form['width']},",
|
||||
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
|
||||
f" shift_amount: {form.get(SHIFT_AMOUNT_KEY, 0)},",
|
||||
f" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},",
|
||||
" relation: "
|
||||
+ (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"),
|
||||
f" scc: SccEffect::{SCC[form['scc']]},",
|
||||
f" vcc: MaskEffect::{MASK[form['vcc']]},",
|
||||
f" exec: MaskEffect::{MASK[form['exec']]},",
|
||||
f" wave: Wave::{WAVE[form['wave']]},",
|
||||
f" operands: OperandRule::{OPERAND_RULES[form['operands']]['rust']},",
|
||||
f" spec: &[{spec}],",
|
||||
f" verify: &[{verify}],",
|
||||
" },",
|
||||
]
|
||||
out += ["];", ""]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _render_enum(rule_name, forms, snapshot, positions):
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
kind = OPERAND_RULES[rule_name]["kind"]
|
||||
table = re.sub(r"(?<!^)(?=[A-Z])", "_", enum).upper() + "_BY_OPCODE"
|
||||
family = forms[0]["family"]
|
||||
encoding = snapshot["encodings"][_family_encoding(family)]
|
||||
mask = encoding["identifier_mask"]
|
||||
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
|
||||
op_mask = ((1 << size) - 1) << offset
|
||||
fixed_mask = mask & ~op_mask
|
||||
fixed_bits = encoding["identifiers"][0] & fixed_mask
|
||||
# Every identifier of the family must share the fixed bits, or the split
|
||||
# into an encoding test plus an OP match would change which words match.
|
||||
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
|
||||
mask & op_mask != op_mask
|
||||
):
|
||||
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
|
||||
out = [
|
||||
"",
|
||||
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq)]",
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"]
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.",
|
||||
f" {form['variant']},",
|
||||
]
|
||||
by_opcode = {form["opcode"]: form["variant"] for form in forms}
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
|
||||
f"const {table}: [Option<{enum}>; {1 << size}] = [",
|
||||
]
|
||||
out += [
|
||||
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
|
||||
for opcode in range(1 << size)
|
||||
]
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
f"impl {enum} {{",
|
||||
" /// Every operation, in registry order.",
|
||||
f" pub const ALL: [Self; {len(forms)}] = [",
|
||||
]
|
||||
out += [f" Self::{form['variant']}," for form in forms]
|
||||
out += [
|
||||
" ];",
|
||||
"",
|
||||
f" /// Selects the operation from a first instruction word: the {family} encoding",
|
||||
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
|
||||
" pub const fn from_word(word: u32) -> Option<Self> {",
|
||||
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
|
||||
" return None;",
|
||||
" }",
|
||||
f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
|
||||
" }",
|
||||
"",
|
||||
" /// Lower-case mnemonic.",
|
||||
" pub const fn mnemonic(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "unary":
|
||||
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 += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged).",
|
||||
" pub const fn evaluate(self, src: u32) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, _ = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if form["operation"] == "sext":
|
||||
value = f"primitive::{function}(src, {form[SOURCE_BITS_KEY]})"
|
||||
else:
|
||||
value = f"primitive::{function}(src)"
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({value}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {value};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with 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 new SCC: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation reads SCC (carry-in, borrow-in or select 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 += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged). `scc_in` is the SCC read by forms that consume it (ignored by",
|
||||
" /// the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, scc_in: bool) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if takes_carry:
|
||||
argument = "scc_in" if form["carry_in"] == "scc" else "false"
|
||||
call = f"primitive::{function}(src0, src1, {argument})"
|
||||
elif form["operation"] in SHIFTS:
|
||||
mask = (1 << form[SHIFT_KEY]) - 1
|
||||
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
|
||||
elif form["operation"] == "lshl_add":
|
||||
call = f"primitive::{function}(src0, src1, {form[SHIFT_AMOUNT_KEY]})"
|
||||
else:
|
||||
call = f"primitive::{function}(src0, src1)"
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({call}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {call};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
|
||||
|
||||
def _display(path):
|
||||
try:
|
||||
return path.resolve().relative_to(ROOT)
|
||||
except ValueError:
|
||||
return path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("mode", nargs="?", choices=("generate", "validate"))
|
||||
parser.add_argument("--check", action="store_true", help="fail if the committed file is stale")
|
||||
parser.add_argument("--registry", type=Path, default=REGISTRY)
|
||||
parser.add_argument("--snapshot", type=Path, default=SNAPSHOT)
|
||||
parser.add_argument("--output", type=Path, default=RUST)
|
||||
arguments = parser.parse_args()
|
||||
if bool(arguments.mode) == arguments.check:
|
||||
parser.error("choose exactly one of generate, validate or --check")
|
||||
registry = load_registry(arguments.registry)
|
||||
snapshot = load_snapshot(arguments.snapshot)
|
||||
errors = validate(registry, snapshot)
|
||||
if errors:
|
||||
for error in errors:
|
||||
print(f"error: {error}", file=sys.stderr)
|
||||
return 1
|
||||
count = len(registry["form"])
|
||||
if arguments.mode == "validate":
|
||||
print(f"registry valid: {count} forms")
|
||||
return 0
|
||||
text = render(registry, snapshot)
|
||||
if arguments.check:
|
||||
current = arguments.output.read_text(encoding="utf-8") if arguments.output.exists() else ""
|
||||
if current != text:
|
||||
print(f"{_display(arguments.output)} is stale; run generate", file=sys.stderr)
|
||||
return 1
|
||||
print(f"registry valid and generated code current: {count} forms")
|
||||
return 0
|
||||
arguments.output.write_text(text, encoding="utf-8")
|
||||
print(f"wrote {_display(arguments.output)}: {count} forms")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large.
Load diff
+27
-93
@@ -3,18 +3,22 @@
|
||||
use std::fmt;
|
||||
|
||||
pub mod meta;
|
||||
pub mod primitive;
|
||||
mod rdna2;
|
||||
pub mod semantics;
|
||||
#[rustfmt::skip]
|
||||
mod rdna2_meta;
|
||||
#[rustfmt::skip]
|
||||
mod semantics_gen;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
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,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -164,86 +168,6 @@ impl VectorCompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// SOP2 32-bit integer operations in the supported scalar subset.
|
||||
///
|
||||
/// SCC behaviour follows the pinned AMD RDNA 2 XML descriptions: additions
|
||||
/// store the carry-out, subtractions the borrow, ADDC and SUBB also consume
|
||||
/// SCC as carry-in or borrow-in, signed forms store signed overflow (RDNA 2 ISA
|
||||
/// guide 12.1), and bitwise operations set SCC iff the result is nonzero. See
|
||||
/// docs/shaders/scalar-alu.md for the sources.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAluOp {
|
||||
/// `s_add_u32`: D = S0 + S1, SCC = carry-out.
|
||||
AddU32,
|
||||
/// `s_sub_u32`: D = S0 - S1, SCC = borrow (S1 > S0).
|
||||
SubU32,
|
||||
/// `s_add_i32`: D = S0 + S1, SCC = signed overflow.
|
||||
AddI32,
|
||||
/// `s_sub_i32`: D = S0 - S1, SCC = signed overflow.
|
||||
SubI32,
|
||||
/// `s_addc_u32`: D = S0 + S1 + SCC, SCC = carry-out.
|
||||
AddcU32,
|
||||
/// `s_subb_u32`: D = S0 - S1 - SCC, SCC = borrow.
|
||||
SubbU32,
|
||||
/// `s_and_b32`: D = S0 & S1, SCC = D != 0.
|
||||
AndB32,
|
||||
/// `s_or_b32`: D = S0 | S1, SCC = D != 0.
|
||||
OrB32,
|
||||
/// `s_xor_b32`: D = S0 ^ S1, SCC = D != 0.
|
||||
XorB32,
|
||||
}
|
||||
|
||||
impl ScalarAluOp {
|
||||
/// Lower-case mnemonic.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::AddU32 => "s_add_u32",
|
||||
Self::SubU32 => "s_sub_u32",
|
||||
Self::AddI32 => "s_add_i32",
|
||||
Self::SubI32 => "s_sub_i32",
|
||||
Self::AddcU32 => "s_addc_u32",
|
||||
Self::SubbU32 => "s_subb_u32",
|
||||
Self::AndB32 => "s_and_b32",
|
||||
Self::OrB32 => "s_or_b32",
|
||||
Self::XorB32 => "s_xor_b32",
|
||||
}
|
||||
}
|
||||
|
||||
/// The 32-bit result and the new SCC, with `carry_in` the SCC read by
|
||||
/// ADDC and SUBB (ignored by the other operations).
|
||||
pub fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {
|
||||
let carry = u32::from(carry_in && self.reads_scc());
|
||||
match self {
|
||||
Self::AddU32 | Self::AddcU32 => {
|
||||
let (partial, first) = src0.overflowing_add(src1);
|
||||
let (value, second) = partial.overflowing_add(carry);
|
||||
(value, first || second)
|
||||
}
|
||||
Self::SubU32 | Self::SubbU32 => {
|
||||
let (partial, first) = src0.overflowing_sub(src1);
|
||||
let (value, second) = partial.overflowing_sub(carry);
|
||||
(value, first || second)
|
||||
}
|
||||
Self::AddI32 => {
|
||||
let (value, overflow) = (src0 as i32).overflowing_add(src1 as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
Self::SubI32 => {
|
||||
let (value, overflow) = (src0 as i32).overflowing_sub(src1 as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
Self::AndB32 => (src0 & src1, src0 & src1 != 0),
|
||||
Self::OrB32 => (src0 | src1, src0 | src1 != 0),
|
||||
Self::XorB32 => (src0 ^ src1, src0 ^ src1 != 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC as a carry-in or borrow-in.
|
||||
pub fn reads_scc(self) -> bool {
|
||||
matches!(self, Self::AddcU32 | Self::SubbU32)
|
||||
}
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ExportTarget {
|
||||
@@ -285,15 +209,24 @@ pub enum Instruction {
|
||||
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
|
||||
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
|
||||
/// for some operations, SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
src: ScalarSource,
|
||||
},
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
|
||||
/// most operations, SCC; `s_cselect_b32` also reads SCC.
|
||||
ScalarAlu {
|
||||
op: ScalarAluOp,
|
||||
dst: u8,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPC 32-bit equality comparison writing SCC.
|
||||
ScalarCompareEqU32 {
|
||||
/// SOPC 32-bit integer compare writing only SCC.
|
||||
ScalarCompare {
|
||||
op: ScalarCompareOp,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
@@ -382,8 +315,9 @@ impl Instruction {
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
@@ -446,13 +380,13 @@ impl fmt::Display for Instruction {
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } => {
|
||||
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
//! Reusable integer semantic primitives selected by the generated registry dispatch.
|
||||
//!
|
||||
//! Each function implements one closed [`crate::semantics::Operation`] at one
|
||||
//! signedness, with the condition-code rule the RDNA 2 guide gives for it
|
||||
//! (section 5.3, "Scalar Condition Code", and the SOP2 pseudocode in 12.1).
|
||||
//! Forms share a primitive only when their declared operation, signedness and
|
||||
//! SCC effect are identical; the generator never selects one by mnemonic.
|
||||
|
||||
/// Unsigned `a + b + carry_in` and the carry-out of bit 31.
|
||||
pub const fn add_carry_u32(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_add(b);
|
||||
let (value, second) = partial.overflowing_add(carry_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Unsigned `a - b - borrow_in` and the borrow (`b + borrow_in > a`).
|
||||
pub const fn sub_borrow_u32(a: u32, b: u32, borrow_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_sub(b);
|
||||
let (value, second) = partial.overflowing_sub(borrow_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Two's-complement `a + b` and whether the exact sum leaves the i32 range.
|
||||
pub const fn add_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_add(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Two's-complement `a - b` and whether the exact difference leaves the i32 range.
|
||||
pub const fn sub_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_sub(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Bitwise AND and whether the result is nonzero.
|
||||
pub const fn and_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise OR and whether the result is nonzero.
|
||||
pub const fn or_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise XOR and whether the result is nonzero.
|
||||
pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a ^ b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a & !b` and whether the result is nonzero.
|
||||
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a | !b` and whether the result is nonzero.
|
||||
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a & b)` and whether the result is nonzero.
|
||||
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a & b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a | b)` and whether the result is nonzero.
|
||||
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a | b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
|
||||
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a ^ b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a << count` and whether the result is nonzero. The caller masks the count
|
||||
/// to the declared count width, so `count` is below 32.
|
||||
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a << count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a >> count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = ((a as i32) >> count) as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// `a != b` on the raw bits (the guide's LG, "less or greater").
|
||||
pub const fn ne_b32(a: u32, b: u32) -> bool {
|
||||
a != b
|
||||
}
|
||||
|
||||
/// Two's-complement `a > b`.
|
||||
pub const fn gt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) > (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a >= b`.
|
||||
pub const fn ge_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) >= (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a < b`.
|
||||
pub const fn lt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) < (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a <= b`.
|
||||
pub const fn le_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) <= (b as i32)
|
||||
}
|
||||
|
||||
/// Unsigned `a > b`.
|
||||
pub const fn gt_u32(a: u32, b: u32) -> bool {
|
||||
a > b
|
||||
}
|
||||
|
||||
/// Unsigned `a >= b`.
|
||||
pub const fn ge_u32(a: u32, b: u32) -> bool {
|
||||
a >= b
|
||||
}
|
||||
|
||||
/// Unsigned `a < b`.
|
||||
pub const fn lt_u32(a: u32, b: u32) -> bool {
|
||||
a < b
|
||||
}
|
||||
|
||||
/// Unsigned `a <= b`.
|
||||
pub const fn le_u32(a: u32, b: u32) -> bool {
|
||||
a <= b
|
||||
}
|
||||
|
||||
/// `!a` and whether the result is nonzero.
|
||||
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = !a;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a` with bit `i` moved to bit `31 - i`.
|
||||
pub const fn brev_b32(a: u32) -> u32 {
|
||||
a.reverse_bits()
|
||||
}
|
||||
|
||||
/// Number of zero bits and whether that count is nonzero.
|
||||
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_zeros();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Number of one bits and whether that count is nonzero.
|
||||
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_ones();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
|
||||
pub const fn ff0_b32(a: u32) -> u32 {
|
||||
if a == u32::MAX {
|
||||
u32::MAX
|
||||
} else {
|
||||
a.trailing_ones()
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
|
||||
pub const fn ff1_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.trailing_zeros() }
|
||||
}
|
||||
|
||||
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
|
||||
pub const fn flbit_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.leading_zeros() }
|
||||
}
|
||||
|
||||
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
|
||||
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
|
||||
pub const fn flbit_i32(a: u32) -> u32 {
|
||||
let differing = if a >> 31 == 0 { a } else { !a };
|
||||
if differing == 0 {
|
||||
u32::MAX
|
||||
} else {
|
||||
differing.leading_zeros()
|
||||
}
|
||||
}
|
||||
|
||||
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
|
||||
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
let shift = 32 - bits;
|
||||
(((a << shift) as i32) >> shift) 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) {
|
||||
let value = (a as i32).wrapping_abs() as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) < (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned minimum and whether S0 was strictly smaller.
|
||||
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a < b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Two's-complement maximum and whether S0 was strictly greater (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) > (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned maximum and whether S0 was strictly greater.
|
||||
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a > b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// `a` when `condition` (SCC) is set, otherwise `b`.
|
||||
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
|
||||
if condition { a } else { b }
|
||||
}
|
||||
|
||||
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
|
||||
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
|
||||
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
|
||||
}
|
||||
|
||||
/// The low 32 bits of the product (identical for signed and unsigned operands).
|
||||
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
|
||||
a.wrapping_mul(b)
|
||||
}
|
||||
|
||||
/// The high 32 bits of the unsigned 64-bit product.
|
||||
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
|
||||
((a as u64 * b as u64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The high 32 bits of the two's-complement 64-bit product.
|
||||
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
|
||||
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
|
||||
const fn bfe_field(b: u32) -> (u32, u32) {
|
||||
(b & 0x1f, (b >> 16) & 0x7f)
|
||||
}
|
||||
|
||||
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
|
||||
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = a >> offset;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
shifted & ((1 << width) - 1)
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
|
||||
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
|
||||
/// more keeps the whole shifted word); and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = ((a as i32) >> offset) as u32;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let unused = 32 - width;
|
||||
(((shifted << unused) as i32) >> unused) as u32
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
|
||||
/// shifted out of `a`; `shift` is 1 to 4.
|
||||
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)
|
||||
}
|
||||
@@ -45,56 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
|
||||
bits: 0xbe800300,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADD_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x80000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUB_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x80800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADD_I32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x81000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUB_I32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x81800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADDC_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x82000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUBB_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x82800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_AND_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x87000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_OR_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x88000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_XOR_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x89000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Typed vocabulary of the declarative semantic registry (`crates/isa/semantics/rdna2.toml`).
|
||||
//!
|
||||
//! The registry is data. `crates/isa/generate_semantics.py` validates it against
|
||||
//! this closed vocabulary and the pinned AMD XML snapshot, then emits
|
||||
//! `semantics_gen.rs`: the typed operation enums, their opcode dispatch and one
|
||||
//! static [`FormSemantics`] row per form. Nothing here interprets metadata at run
|
||||
//! time; the decoder and translator call the generated `const fn`s and `match`es.
|
||||
//!
|
||||
//! The reference interpreter (`crates/ref`) and the independent interpreter
|
||||
//! (`tests/validation/independent_ref.rs`) must not use this module.
|
||||
|
||||
use crate::CompareRelation;
|
||||
use crate::meta::EncodingFamily;
|
||||
|
||||
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
|
||||
|
||||
/// Version of the registry schema this crate was generated against.
|
||||
pub const SCHEMA: u32 = 1;
|
||||
|
||||
/// Reusable semantic primitive selected by a form. Closed: the generator rejects
|
||||
/// any other name, and each primitive has one implementation in `primitive.rs`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Operation {
|
||||
/// Integer addition.
|
||||
Add,
|
||||
/// Integer subtraction.
|
||||
Sub,
|
||||
/// Bitwise AND.
|
||||
And,
|
||||
/// Bitwise OR.
|
||||
Or,
|
||||
/// Bitwise exclusive OR.
|
||||
Xor,
|
||||
/// Bitwise AND with the complement of S1.
|
||||
AndNot,
|
||||
/// Bitwise OR with the complement of S1.
|
||||
OrNot,
|
||||
/// Complement of bitwise AND.
|
||||
Nand,
|
||||
/// Complement of bitwise OR.
|
||||
Nor,
|
||||
/// Complement of bitwise exclusive OR.
|
||||
Xnor,
|
||||
/// Shift S0 left by the masked count in S1, filling with zeros.
|
||||
ShiftLeft,
|
||||
/// Shift S0 right by the masked count in S1, filling with zeros.
|
||||
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,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
/// S0 with its bit order reversed.
|
||||
ReverseBits,
|
||||
/// Number of zero bits in S0.
|
||||
CountZeros,
|
||||
/// Number of one bits in S0.
|
||||
CountOnes,
|
||||
/// Index of the lowest zero bit of S0, or -1 when there is none.
|
||||
FindFirstZero,
|
||||
/// Index of the lowest one bit of S0, or -1 when there is none.
|
||||
FindFirstOne,
|
||||
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
|
||||
/// above the highest bit that differs from the sign bit. -1 when none.
|
||||
FindLastBit,
|
||||
/// Sign-extend the low `source_bits` of S0 to 32 bits.
|
||||
SignExtend,
|
||||
/// Two's-complement absolute value; the most negative value maps to itself.
|
||||
Absolute,
|
||||
/// S0 when it is strictly less than S1, otherwise S1.
|
||||
Minimum,
|
||||
/// S0 when it is strictly greater than S1, otherwise S1.
|
||||
Maximum,
|
||||
/// S0 when SCC is set, otherwise S1.
|
||||
Select,
|
||||
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
|
||||
BitfieldMask,
|
||||
/// Low 32 bits of the product.
|
||||
Multiply,
|
||||
/// High 32 bits of the 64-bit product.
|
||||
MultiplyHigh,
|
||||
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
|
||||
BitfieldExtract,
|
||||
/// Absolute value of the wrapped 32-bit difference S0 - S1.
|
||||
AbsoluteDifference,
|
||||
/// `(S0 << shift_amount) + S1`.
|
||||
ShiftLeftAdd,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Signedness {
|
||||
/// Unsigned integers.
|
||||
Unsigned,
|
||||
/// Two's-complement integers.
|
||||
Signed,
|
||||
/// Untyped bits.
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// SCC is not read.
|
||||
None,
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
}
|
||||
|
||||
/// What a form writes to SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum SccEffect {
|
||||
/// SCC is not written.
|
||||
Unchanged,
|
||||
/// Unsigned carry-out of the top bit.
|
||||
CarryOut,
|
||||
/// Unsigned borrow (subtrahend plus borrow-in exceeds the minuend).
|
||||
Borrow,
|
||||
/// Two's-complement overflow of the exact result.
|
||||
SignedOverflow,
|
||||
/// The result is not zero.
|
||||
Nonzero,
|
||||
/// The compare's relation holds for S0 and S1.
|
||||
Relation,
|
||||
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
Unchanged,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Wave {
|
||||
/// Behaviour does not depend on the wave size.
|
||||
Any,
|
||||
/// Only Wave32 behaviour is declared; Wave64 stays unsupported.
|
||||
Wave32,
|
||||
}
|
||||
|
||||
/// Shared operand rule. The decoder implements each rule once.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum OperandRule {
|
||||
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
|
||||
/// or one literal word. Everything else is rejected as unsupported.
|
||||
Sop2Sgpr,
|
||||
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
|
||||
/// integers -16..64 or one literal word). Everything else is rejected.
|
||||
SopcScalar,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Evidence {
|
||||
/// `crates/ref` lockstep reference.
|
||||
Reference,
|
||||
/// `tests/validation/independent_ref.rs`.
|
||||
Independent,
|
||||
/// Native Metal known-answer runs.
|
||||
Metal,
|
||||
/// LLVM assembler/disassembler encoding agreement.
|
||||
LlvmEncoding,
|
||||
}
|
||||
|
||||
/// Public document a [`SpecRef`] points at.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Document {
|
||||
/// AMD RDNA 2 ISA reference guide (PDF).
|
||||
Guide,
|
||||
/// Pinned AMD machine-readable XML.
|
||||
Xml,
|
||||
}
|
||||
|
||||
/// One public specification reference.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SpecRef {
|
||||
/// Source document.
|
||||
pub document: Document,
|
||||
/// Section number, for example `"12.1"`.
|
||||
pub section: &'static str,
|
||||
/// Page in the document, or 0 when the page has not been recorded.
|
||||
pub page: u16,
|
||||
}
|
||||
|
||||
/// One validated registry row, emitted as a static table by the generator.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormSemantics {
|
||||
/// XML instruction name, the stable form identity.
|
||||
pub name: &'static str,
|
||||
/// Encoding family (matches [`crate::meta::FORMS`]).
|
||||
pub family: EncodingFamily,
|
||||
/// Opcode within the family.
|
||||
pub opcode: u16,
|
||||
/// Primitive.
|
||||
pub operation: Operation,
|
||||
/// Operand interpretation.
|
||||
pub signedness: Signedness,
|
||||
/// SCC input.
|
||||
pub carry_in: CarryIn,
|
||||
/// Operand and result width in bits.
|
||||
pub width: u8,
|
||||
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
|
||||
pub shift_count_bits: u8,
|
||||
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
|
||||
pub shift_amount: u8,
|
||||
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
|
||||
pub source_bits: u8,
|
||||
/// The relation tested by compares (S0 on the left); `None` otherwise.
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
pub vcc: MaskEffect,
|
||||
/// EXEC write.
|
||||
pub exec: MaskEffect,
|
||||
/// Wave-size restriction.
|
||||
pub wave: Wave,
|
||||
/// Operand rule.
|
||||
pub operands: OperandRule,
|
||||
/// Public references.
|
||||
pub spec: &'static [SpecRef],
|
||||
/// Required evidence.
|
||||
pub verify: &'static [Evidence],
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
assert_eq!(GENERATED_SCHEMA, SCHEMA);
|
||||
assert_eq!(FORM_IDS.len(), FORMS.len());
|
||||
for (row, (name, family)) in FORMS.iter().zip(FORM_IDS) {
|
||||
assert_eq!((row.name, row.family), (name, family));
|
||||
let meta = META_FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == row.name && form.family == row.family)
|
||||
.unwrap_or_else(|| panic!("{} is not an identified form", row.name));
|
||||
assert_eq!(meta.opcode, row.opcode, "{}", row.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every word of `family` that the XML metadata identifies selects an operation
|
||||
/// exactly when the registry declares that form, and no 32-bit word of another
|
||||
/// family selects one.
|
||||
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
|
||||
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
|
||||
let mut selected = 0;
|
||||
for meta in META_FORMS.iter().filter(|form| form.family == family) {
|
||||
match select(meta.bits as u32) {
|
||||
Some(name) => {
|
||||
assert_eq!(name, meta.name);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
declared.iter().all(|row| row.name != meta.name),
|
||||
"{} is declared but not dispatched",
|
||||
meta.name
|
||||
),
|
||||
}
|
||||
}
|
||||
assert_eq!(selected, declared.len());
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != family && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop2);
|
||||
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);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
|
||||
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
for op in ScalarCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
|
||||
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop1);
|
||||
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)
|
||||
});
|
||||
}
|
||||
+234
-52
@@ -53,6 +53,25 @@ impl Register {
|
||||
}
|
||||
}
|
||||
|
||||
/// Instruction prefixes decoded ahead of an opcode.
|
||||
///
|
||||
/// The interpreter decodes these once per instruction and passes them to the
|
||||
/// helpers that need them, so prefix state travels as one typed value instead
|
||||
/// of a list of independent booleans.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Prefixes {
|
||||
/// REX.W: 64-bit operand size.
|
||||
rex_w: bool,
|
||||
/// REX.R: extends the ModRM `reg` field to R8-R15.
|
||||
rex_r: bool,
|
||||
/// REX.B: extends the ModRM `rm` field to R8-R15.
|
||||
rex_b: bool,
|
||||
/// The GS segment override prefix (0x65) is present.
|
||||
seg_gs: bool,
|
||||
/// The FS segment override prefix (0x64) is present.
|
||||
seg_fs: bool,
|
||||
}
|
||||
|
||||
/// RFLAGS status bits tracked during guest execution.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RFlags {
|
||||
@@ -153,6 +172,167 @@ mod layout_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod prefix_tests {
|
||||
use super::{CpuState, ExitReason, Interpreter, Register};
|
||||
use crate::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
const CODE_BASE: u64 = 0x1000;
|
||||
const CODE_SIZE: usize = 0x1000;
|
||||
const STACK_BASE: u64 = 0x8000_0000;
|
||||
const STACK_SIZE: usize = 0x10000;
|
||||
const FS_BASE: u64 = 0x9000;
|
||||
const GS_BASE: u64 = 0xA000;
|
||||
|
||||
/// A guest memory image with executable code, a stack and distinct FS and
|
||||
/// GS bases.
|
||||
fn memory_with_code(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE_BASE,
|
||||
CODE_SIZE,
|
||||
MemoryPermissions::READ_WRITE_EXECUTE,
|
||||
code,
|
||||
)
|
||||
.expect("code region");
|
||||
memory
|
||||
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack region");
|
||||
// The segment bases are distinct so a swapped prefix is visible.
|
||||
memory
|
||||
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.expect("fs region");
|
||||
memory
|
||||
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.expect("gs region");
|
||||
memory
|
||||
}
|
||||
|
||||
/// Run `code` on the interpreter and return the final state and exit reason.
|
||||
fn run(code: &[u8]) -> (CpuState, ExitReason) {
|
||||
let mut memory = memory_with_code(code);
|
||||
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut memory, 64);
|
||||
let result = interp.run();
|
||||
(result.final_state, result.exit_reason)
|
||||
}
|
||||
|
||||
/// `mov r8, imm64`: 49 B8 <imm64>.
|
||||
fn mov_r8_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x49, 0xB8];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rbx, imm64`: 48 BB <imm64>.
|
||||
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rax, imm64`: 48 B8 <imm64>.
|
||||
fn mov_rax_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xB8];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
|
||||
///
|
||||
/// Encoding 49 89 D8 is `mov r8, rbx`.
|
||||
#[test]
|
||||
fn rex_b_extends_the_rm_field_to_r8() {
|
||||
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
// No prefix in this encoding selects r9.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
}
|
||||
|
||||
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
|
||||
///
|
||||
/// Encoding 4C 89 C3 is `mov rbx, r8`.
|
||||
#[test]
|
||||
fn rex_r_extends_the_reg_field_to_r8() {
|
||||
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
// No prefix in this encoding selects r9.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.B extend independent fields, so the destination r9 and
|
||||
/// the source r12 are chosen by different prefix bits.
|
||||
///
|
||||
/// Encoding 4D 89 E1 is `mov r9, r12`.
|
||||
#[test]
|
||||
fn rex_r_and_rex_b_extend_independent_fields() {
|
||||
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// r9 receives r12, which is zero here, and not the value in r8.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
assert_eq!(state.get(Register::R12), 0);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
}
|
||||
|
||||
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
|
||||
/// low half of the source and its upper half is cleared.
|
||||
///
|
||||
/// Encoding 89 D8 is `mov eax, ebx`.
|
||||
#[test]
|
||||
fn a_move_without_rex_w_is_32_bit_wide() {
|
||||
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
|
||||
assert_eq!(state.get(Register::Rax), 0x5566_7788);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
}
|
||||
|
||||
/// The FS segment override adds the FS base to the effective address.
|
||||
///
|
||||
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
|
||||
#[test]
|
||||
fn the_fs_prefix_adds_the_fs_base() {
|
||||
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let mut memory = memory_with_code(&code);
|
||||
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
let mut interp = Interpreter::new(cpu, &mut memory, 64);
|
||||
let result = interp.run();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
// The GS base is untouched: the GS-prefixed store did not happen.
|
||||
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Result returned after running guest execution.
|
||||
#[derive(Debug)]
|
||||
pub struct ExecutionResult {
|
||||
@@ -255,29 +435,25 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
|
||||
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mut rex_w = false;
|
||||
let mut rex_r = false;
|
||||
let mut rex_b = false;
|
||||
let mut seg_gs = false;
|
||||
let mut seg_fs = false;
|
||||
let mut prefixes = Prefixes::default();
|
||||
|
||||
let mut byte = self.fetch_u8()?;
|
||||
|
||||
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
|
||||
while byte == 0x65 || byte == 0x64 {
|
||||
if byte == 0x65 {
|
||||
seg_gs = true;
|
||||
prefixes.seg_gs = true;
|
||||
} else {
|
||||
seg_fs = true;
|
||||
prefixes.seg_fs = true;
|
||||
}
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
// Handle REX prefix (0x40 - 0x4F)
|
||||
if (byte & 0xF0) == 0x40 {
|
||||
rex_w = (byte & 0x08) != 0;
|
||||
rex_r = (byte & 0x04) != 0;
|
||||
rex_b = (byte & 0x01) != 0;
|
||||
prefixes.rex_w = (byte & 0x08) != 0;
|
||||
prefixes.rex_r = (byte & 0x04) != 0;
|
||||
prefixes.rex_b = (byte & 0x01) != 0;
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
@@ -288,9 +464,9 @@ impl<'a> Interpreter<'a> {
|
||||
0x0F => match self.fetch_u8()? {
|
||||
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
|
||||
op @ 0xC8..=0xCF => {
|
||||
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
|
||||
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
|
||||
let value = self.cpu.get(reg);
|
||||
let reversed = if rex_w {
|
||||
let reversed = if prefixes.rex_w {
|
||||
value.swap_bytes()
|
||||
} else {
|
||||
u64::from((value as u32).swap_bytes())
|
||||
@@ -303,9 +479,9 @@ impl<'a> Interpreter<'a> {
|
||||
|
||||
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
|
||||
0xB8..=0xBF => {
|
||||
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = (byte - 0xB8) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
if rex_w {
|
||||
if prefixes.rex_w {
|
||||
let imm = self.fetch_u64()?;
|
||||
self.cpu.set(reg, imm);
|
||||
} else {
|
||||
@@ -318,28 +494,28 @@ impl<'a> Interpreter<'a> {
|
||||
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
|
||||
0x31 | 0x33 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let res = if rex_w {
|
||||
let res = if prefixes.rex_w {
|
||||
val1 ^ val2
|
||||
} else {
|
||||
(val1 as u32 ^ val2 as u32) as u64
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.update_flags_logic(res, rex_w);
|
||||
self.update_flags_logic(res, prefixes.rex_w);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
|
||||
0x01 | 0x03 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
add64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = add32(val1 as u32, val2 as u32);
|
||||
@@ -353,11 +529,11 @@ impl<'a> Interpreter<'a> {
|
||||
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
|
||||
0x29 | 0x2B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
sub64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = sub32(val1 as u32, val2 as u32);
|
||||
@@ -371,13 +547,13 @@ impl<'a> Interpreter<'a> {
|
||||
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
|
||||
0x39 | 0x3B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let (v1, v2) = if byte == 0x39 {
|
||||
(self.cpu.get(rm), self.cpu.get(reg))
|
||||
} else {
|
||||
(self.cpu.get(reg), self.cpu.get(rm))
|
||||
};
|
||||
let (_, flags) = if rex_w {
|
||||
let (_, flags) = if prefixes.rex_w {
|
||||
sub64(v1, v2)
|
||||
} else {
|
||||
let (r, f) = sub32(v1 as u32, v2 as u32);
|
||||
@@ -391,7 +567,7 @@ impl<'a> Interpreter<'a> {
|
||||
0x83 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let op = (modrm >> 3) & 7;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
|
||||
let imm8 = self.fetch_i8()? as i64;
|
||||
let imm = imm8 as u64;
|
||||
|
||||
@@ -399,7 +575,7 @@ impl<'a> Interpreter<'a> {
|
||||
match op {
|
||||
0 => {
|
||||
// ADD
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
add64(val, imm)
|
||||
} else {
|
||||
let (r, f) = add32(val as u32, imm as u32);
|
||||
@@ -410,7 +586,7 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
5 => {
|
||||
// SUB
|
||||
let (res, flags) = if rex_w {
|
||||
let (res, flags) = if prefixes.rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
@@ -421,7 +597,7 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
7 => {
|
||||
// CMP
|
||||
let (_, flags) = if rex_w {
|
||||
let (_, flags) = if prefixes.rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
@@ -438,7 +614,7 @@ impl<'a> Interpreter<'a> {
|
||||
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
|
||||
0x89 | 0x8B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
|
||||
self.execute_mov_rm(modrm, &prefixes, byte == 0x8B)
|
||||
}
|
||||
|
||||
// JMP rel8 (0xEB)
|
||||
@@ -492,7 +668,7 @@ impl<'a> Interpreter<'a> {
|
||||
|
||||
// PUSH reg (0x50..=0x57)
|
||||
0x50..=0x57 => {
|
||||
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = (byte - 0x50) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.cpu.get(reg);
|
||||
self.push_u64(val)?;
|
||||
@@ -501,7 +677,7 @@ impl<'a> Interpreter<'a> {
|
||||
|
||||
// POP reg (0x58..=0x5F)
|
||||
0x58..=0x5F => {
|
||||
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = (byte - 0x58) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.pop_u64()?;
|
||||
self.cpu.set(reg, val);
|
||||
@@ -532,32 +708,26 @@ impl<'a> Interpreter<'a> {
|
||||
fn decode_modrm_reg_reg(
|
||||
&self,
|
||||
modrm: u8,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
prefixes: &Prefixes,
|
||||
) -> Result<(Register, Register), ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(modrm));
|
||||
}
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
|
||||
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn execute_mov_rm(
|
||||
&mut self,
|
||||
modrm: u8,
|
||||
rex_w: bool,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
prefixes: &Prefixes,
|
||||
is_load: bool,
|
||||
seg_gs: bool,
|
||||
seg_fs: bool,
|
||||
) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
|
||||
if mode == 3 {
|
||||
@@ -565,12 +735,24 @@ impl<'a> Interpreter<'a> {
|
||||
let rm = Register::from_index(rm_idx);
|
||||
if is_load {
|
||||
let val = self.cpu.get(rm);
|
||||
self.cpu
|
||||
.set(reg, if rex_w { val } else { val as u32 as u64 });
|
||||
self.cpu.set(
|
||||
reg,
|
||||
if prefixes.rex_w {
|
||||
val
|
||||
} else {
|
||||
val as u32 as u64
|
||||
},
|
||||
);
|
||||
} else {
|
||||
let val = self.cpu.get(reg);
|
||||
self.cpu
|
||||
.set(rm, if rex_w { val } else { val as u32 as u64 });
|
||||
self.cpu.set(
|
||||
rm,
|
||||
if prefixes.rex_w {
|
||||
val
|
||||
} else {
|
||||
val as u32 as u64
|
||||
},
|
||||
);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -580,8 +762,8 @@ impl<'a> Interpreter<'a> {
|
||||
// SIB byte follows ModR/M
|
||||
let sib = self.fetch_u8()?;
|
||||
let scale_shift = (sib >> 6) & 3;
|
||||
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
|
||||
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
|
||||
let index_raw = ((sib >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
|
||||
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
|
||||
|
||||
let base_v = if mode == 0 && (sib & 7) == 5 {
|
||||
// disp32 with no base register
|
||||
@@ -637,15 +819,15 @@ impl<'a> Interpreter<'a> {
|
||||
(base_val as i64 + disp) as u64
|
||||
};
|
||||
|
||||
if seg_gs {
|
||||
if prefixes.seg_gs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
|
||||
} else if seg_fs {
|
||||
} else if prefixes.seg_fs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
|
||||
}
|
||||
|
||||
if is_load {
|
||||
// Load from memory to reg
|
||||
if rex_w {
|
||||
if prefixes.rex_w {
|
||||
let val = self
|
||||
.memory
|
||||
.read_u64(effective_addr)
|
||||
@@ -661,7 +843,7 @@ impl<'a> Interpreter<'a> {
|
||||
} else {
|
||||
// Store from reg to memory
|
||||
let val = self.cpu.get(reg);
|
||||
if rex_w {
|
||||
if prefixes.rex_w {
|
||||
self.memory
|
||||
.write_u64(effective_addr, val)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
|
||||
+90
-66
@@ -226,57 +226,102 @@ impl GuestMemory {
|
||||
true
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, src.len()) {
|
||||
if !region.permissions.write {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "write",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + src.len()].copy_from_slice(src);
|
||||
return Ok(());
|
||||
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
|
||||
///
|
||||
/// An access may span adjacent regions, as it would span adjacent pages, but every
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
len: usize,
|
||||
required: Option<&'static str>,
|
||||
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
|
||||
let end = address
|
||||
.checked_add(len as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if len == 0 {
|
||||
return if self.regions.iter().any(|r| r.contains(address, 0)) {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
};
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
let mut cursor = address;
|
||||
for (index, region) in self.regions.iter().enumerate() {
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if region_end <= cursor {
|
||||
continue;
|
||||
}
|
||||
if region.base > cursor {
|
||||
break;
|
||||
}
|
||||
let permitted = match required {
|
||||
None => true,
|
||||
Some("read") => region.permissions.read,
|
||||
Some("write") => region.permissions.write,
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
cursor += take as u64;
|
||||
if cursor == end {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
&self,
|
||||
address: u64,
|
||||
dst: &mut [u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
|
||||
dst[done..done + take]
|
||||
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_checked(
|
||||
&mut self,
|
||||
address: u64,
|
||||
src: &[u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, src.len(), required)? {
|
||||
self.regions[index].data[offset..offset + take]
|
||||
.copy_from_slice(&src[done..done + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, dst.len()) {
|
||||
if !region.permissions.read {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "read",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
dst.copy_from_slice(®ion.data[offset..offset + dst.len()]);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 1) {
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
return Ok(region.data[offset]);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -288,14 +333,9 @@ impl GuestMemory {
|
||||
|
||||
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
|
||||
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
|
||||
return Ok(u64::from_le_bytes(buf));
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 8];
|
||||
self.read_checked(address, &mut buf, None)?;
|
||||
Ok(u64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Write a 64-bit integer (little endian) to guest memory.
|
||||
@@ -305,15 +345,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 8].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a 32-bit integer (little endian) from guest memory.
|
||||
@@ -330,15 +362,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 4) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 4].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a single byte from guest memory.
|
||||
|
||||
+18
-1
@@ -94,6 +94,9 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
|
||||
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
|
||||
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
|
||||
const SECTION_HEADER_SIZE: usize = 40;
|
||||
/// Host memory budget for all mapped sections of one image. This is a loader policy
|
||||
/// limit, not a property of the PE format.
|
||||
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
@@ -170,7 +173,10 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
|
||||
for sec_bytes in bytes[section_table_offset..table_end].chunks_exact(SECTION_HEADER_SIZE) {
|
||||
for sec_bytes in bytes[section_table_offset..table_end]
|
||||
.as_chunks::<SECTION_HEADER_SIZE>()
|
||||
.0
|
||||
{
|
||||
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
|
||||
let name_raw = &sec_bytes[0..8];
|
||||
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
|
||||
@@ -270,6 +276,17 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
|
||||
// Each section becomes a zero-filled host allocation, so bound the total before
|
||||
// allocating anything. Sections may not overlap, so the sum is the mapped size.
|
||||
let mapped: u64 = self
|
||||
.sections
|
||||
.iter()
|
||||
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
|
||||
.sum();
|
||||
if mapped > MAX_MAPPED_IMAGE_BYTES {
|
||||
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
|
||||
}
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
|
||||
for sec in &self.sections {
|
||||
|
||||
+136
-16
@@ -11,6 +11,14 @@ use crate::{
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
const TEB_TLS_POINTER: u64 = 0x58;
|
||||
|
||||
/// Guest addresses reserved by the fixture harness.
|
||||
pub struct StartupLayout {
|
||||
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// Reject an impossible layout before parsing or mapping anything.
|
||||
let (stack_base, teb_base) = layout_regions(&layout)?;
|
||||
let pe = ParsedPe::parse(bytes)?;
|
||||
observe(StartupEvent::Parsed {
|
||||
sections: pe.sections.len(),
|
||||
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)?;
|
||||
}
|
||||
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
|
||||
// Allocate and initialize Win64 TEB (Thread Environment Block)
|
||||
// Layout in TEB:
|
||||
// +0x08: StackBase (highest address)
|
||||
// +0x10: StackLimit (lowest address)
|
||||
// +0x30: Self pointer (TEB linear address)
|
||||
// +0x58: ThreadLocalStoragePointer
|
||||
let teb_base = layout.tls_base.saturating_add(0x10000);
|
||||
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
|
||||
engine.set_import_registry(imports);
|
||||
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
|
||||
dbt_metrics: engine.metrics,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate the harness layout and return `(stack_base, teb_base)`.
|
||||
///
|
||||
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
|
||||
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
|
||||
/// space and must not overlap each other.
|
||||
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_base = layout
|
||||
.tls_base
|
||||
.checked_add(TEB_OFFSET)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_end = teb_base
|
||||
.checked_add(TEB_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if teb_base < layout.stack_top && stack_base < teb_end {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base: teb_base,
|
||||
size: TEB_SIZE as u64,
|
||||
});
|
||||
}
|
||||
Ok((stack_base, teb_base))
|
||||
}
|
||||
|
||||
/// Map the Win64 TEB and write the fields the harness provides.
|
||||
fn map_teb(
|
||||
memory: &mut crate::GuestMemory,
|
||||
teb_base: u64,
|
||||
layout: &StartupLayout,
|
||||
stack_base: u64,
|
||||
) -> Result<(), MemoryError> {
|
||||
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::GuestMemory;
|
||||
|
||||
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top,
|
||||
tls_base,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_layout_places_stack_and_teb() {
|
||||
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
|
||||
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_below_zero_is_rejected() {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x8000, 0x3_0000_0000)),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_address_overflow_is_rejected_not_saturated() {
|
||||
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x2_0001_0000, tls_base)),
|
||||
Err(MemoryError::Overflow),
|
||||
"tls_base {tls_base:#x}"
|
||||
);
|
||||
}
|
||||
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
|
||||
// representable, and GuestMemory could not map that range either.
|
||||
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_overlapping_stack_is_rejected() {
|
||||
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
|
||||
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
|
||||
assert!(matches!(
|
||||
layout_regions(&collide),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
// Directly above the stack is fine.
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_layout_fails_before_parsing() {
|
||||
// Empty bytes would fail PE parsing; the layout error must come first.
|
||||
let err = run_synthetic_startup(
|
||||
&[],
|
||||
layout(0x2_0001_0000, u64::MAX),
|
||||
ImportRegistry::new(),
|
||||
1,
|
||||
)
|
||||
.err()
|
||||
.expect("startup must fail");
|
||||
assert_eq!(
|
||||
err.downcast_ref::<MemoryError>(),
|
||||
Some(&MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_fields_are_at_win64_offsets() {
|
||||
let l = layout(0x2_0001_0000, 0x3_0000_0000);
|
||||
let (stack_base, teb) = layout_regions(&l).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
map_teb(&mut memory, teb, &l, stack_base).unwrap();
|
||||
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
|
||||
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
|
||||
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest memory boundary regression tests (#82).
|
||||
//!
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
fn two_regions(first: P, second: P) -> GuestMemory {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
|
||||
.unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
|
||||
m.read_u64_bypass(at).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_are_enforced_per_access_kind() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
let violation = |address, required| MemoryError::PermissionViolation { address, required };
|
||||
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
|
||||
assert_eq!(
|
||||
m.write_u8(A + 0x1000, 1),
|
||||
Err(violation(A + 0x1000, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(A + 0x2000),
|
||||
Err(violation(A + 0x2000, "execute"))
|
||||
);
|
||||
assert!(m.read_u8(A + 0x1000).is_ok());
|
||||
assert!(m.write_u8(A + 0x2000, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_end_is_exclusive() {
|
||||
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
assert!(m.read_u32(A + 0xFFC).is_ok());
|
||||
assert!(matches!(
|
||||
m.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
let mut lone = GuestMemory::new();
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
Err(MemoryError::UnmappedAddress(A - 1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unaligned_accesses_succeed_inside_a_region() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
|
||||
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
|
||||
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_spanning_adjacent_permitted_regions_succeeds() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
|
||||
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
|
||||
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
|
||||
|
||||
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
|
||||
assert!(m.read_u64(A + 0xFFC).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
|
||||
m.write_u32_bypass(A, 7).unwrap();
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_overflow_is_reported() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(u64::MAX - 3, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.map_region(u64::MAX, 2, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion {
|
||||
base: A + 0xFFF,
|
||||
size: 0x10
|
||||
})
|
||||
);
|
||||
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
|
||||
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! PE image mapping budget tests (#80).
|
||||
//!
|
||||
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
|
||||
//! backs it with zero-filled host memory, so a small file can request a large
|
||||
//! allocation. The loader's documented budget is 256 MiB per image.
|
||||
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
|
||||
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
|
||||
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
|
||||
fn build(bss_sizes: &[u32]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x400];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
|
||||
let h = opt + 112 + i * 40;
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
};
|
||||
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
|
||||
let mut va = 0x2000u32;
|
||||
for (i, &size) in bss_sizes.iter().enumerate() {
|
||||
section(i + 1, va, size, 0, 0xC000_0080);
|
||||
va += size;
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
fn over_budget() -> PeError {
|
||||
PeError::SectionMappingError(MemoryError::AllocationFailed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_image_loads() {
|
||||
let bytes = build(&[0x1000]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_exactly_at_budget_loads() {
|
||||
let bytes = build(&[BUDGET - 0x200]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_byte_over_budget_is_rejected() {
|
||||
let bytes = build(&[BUDGET - 0x1FF]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_counts_all_sections_together() {
|
||||
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
|
||||
let bytes = build(&[128 << 20; 3]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
|
||||
let bytes = build(&[0xF000_0000]);
|
||||
assert_eq!(bytes.len(), 0x400);
|
||||
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_fixture_is_within_budget() {
|
||||
let path = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/trusted-runner.exe"
|
||||
);
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
+290
-23
@@ -51,13 +51,19 @@ pub enum Op {
|
||||
Move(u8, Source),
|
||||
Add(u8, u8, u8),
|
||||
ScalarMove(u8, Source),
|
||||
/// SOP1 unary operation writing an SGPR (s0-s105), and SCC for some.
|
||||
ScalarUnary(ScalarUnary, u8, Source),
|
||||
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
|
||||
MoveScalar(u8, u8),
|
||||
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
|
||||
Compare(Comparison, CompareSource, u8),
|
||||
/// SOP2 operation writing an SGPR and SCC.
|
||||
Scalar(ScalarAlu, u8, Source, Source),
|
||||
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
|
||||
CompareEqual(Source, Source),
|
||||
/// 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),
|
||||
Branch {
|
||||
target: usize,
|
||||
condition: BranchCondition,
|
||||
@@ -129,7 +135,7 @@ pub enum BranchCondition {
|
||||
///
|
||||
/// AMD RDNA 2 XML descriptions: additions store the carry-out in SCC,
|
||||
/// subtractions the borrow; ADDC/SUBB add or subtract SCC; bitwise
|
||||
/// operations set SCC iff the result is nonzero.
|
||||
/// operations and shifts set SCC iff the result is nonzero.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAlu {
|
||||
Add,
|
||||
@@ -142,6 +148,79 @@ pub enum ScalarAlu {
|
||||
And,
|
||||
Or,
|
||||
Xor,
|
||||
/// RDNA 2 ISA guide 12.1: D = S0 & ~S1, SCC = (D != 0).
|
||||
AndNot,
|
||||
/// D = S0 | ~S1, SCC = (D != 0).
|
||||
OrNot,
|
||||
/// D = ~(S0 & S1), SCC = (D != 0).
|
||||
Nand,
|
||||
/// D = ~(S0 | S1), SCC = (D != 0).
|
||||
Nor,
|
||||
/// D = ~(S0 ^ S1), SCC = (D != 0).
|
||||
Xnor,
|
||||
/// D = S0 << S1[4:0], SCC = (D != 0).
|
||||
ShiftLeft,
|
||||
/// D = S0 >> S1[4:0] (logical), SCC = (D != 0).
|
||||
ShiftRight,
|
||||
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
|
||||
ArithmeticShiftRight,
|
||||
/// Guide 12.1: D = (S0 < S1) ? S0 : S1, SCC = (S0 < S1); signed or not.
|
||||
Minimum {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = (S0 > S1) ? S0 : S1, SCC = (S0 > S1).
|
||||
Maximum {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = SCC ? S0 : S1; reads SCC and leaves it unchanged.
|
||||
Select,
|
||||
/// D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged.
|
||||
BitfieldMask,
|
||||
/// D = low 32 bits of S0 * S1; SCC unchanged.
|
||||
Multiply,
|
||||
/// D = (S0 >> S1[4:0]) & ((1 << S1[22:16]) - 1), sign-extended from the
|
||||
/// field's top bit when signed (S0 then shifts arithmetically);
|
||||
/// SCC = (D != 0).
|
||||
BitfieldExtract {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = |S0 - S1| with the 32-bit difference (0x80000000 stays),
|
||||
/// SCC = (D != 0).
|
||||
AbsoluteDifference,
|
||||
/// D = (S0 << N) + S1, SCC = ((S0 << N) + S1 >= 2^32) with N = 1..4.
|
||||
ShiftLeftAdd(u8),
|
||||
/// D = high 32 bits of S0 * S1; SCC unchanged.
|
||||
MultiplyHigh {
|
||||
signed: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// SOP1 unary operations decoded by the reference interpreter (RDNA 2 ISA
|
||||
/// guide 12.3; SCC per Tables 12 and 14).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarUnary {
|
||||
/// D = ~S0, SCC = (D != 0).
|
||||
Not,
|
||||
/// D[31:0] = S0[0:31].
|
||||
ReverseBits,
|
||||
/// D = number of zero bits, SCC = (D != 0).
|
||||
CountZeros,
|
||||
/// D = number of one bits, SCC = (D != 0).
|
||||
CountOnes,
|
||||
/// D = index of the lowest zero bit, or -1.
|
||||
FindFirstZero,
|
||||
/// D = index of the lowest one bit, or -1.
|
||||
FindFirstOne,
|
||||
/// D = number of zeros above the highest one bit, or -1 for 0.
|
||||
FindLastBit,
|
||||
/// D = number of leading bits equal to the sign bit, or -1 for 0 and -1.
|
||||
FindLastSignBit,
|
||||
/// D = signext(S0[7:0]).
|
||||
SignExtendByte,
|
||||
/// D = signext(S0[15:0]).
|
||||
SignExtendShort,
|
||||
/// D = |S0| (0x80000000 stays), SCC = (D != 0).
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// VOP2 operations decoded by the reference interpreter.
|
||||
@@ -277,32 +356,90 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarMove(destination & 0x7f, source), length)
|
||||
}
|
||||
[left, right, 6, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST in 16-22 (s0-s105
|
||||
// only), OP in 8-15.
|
||||
[
|
||||
source,
|
||||
op @ (7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52),
|
||||
destination @ 0x80..=0xe9,
|
||||
0xbe,
|
||||
tail @ ..,
|
||||
] => {
|
||||
let kind = match op {
|
||||
7 => ScalarUnary::Not,
|
||||
11 => ScalarUnary::ReverseBits,
|
||||
13 => ScalarUnary::CountZeros,
|
||||
15 => ScalarUnary::CountOnes,
|
||||
17 => ScalarUnary::FindFirstZero,
|
||||
19 => ScalarUnary::FindFirstOne,
|
||||
21 => ScalarUnary::FindLastBit,
|
||||
23 => ScalarUnary::FindLastSignBit,
|
||||
25 => ScalarUnary::SignExtendByte,
|
||||
26 => ScalarUnary::SignExtendShort,
|
||||
_ => ScalarUnary::Absolute,
|
||||
};
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarUnary(kind, destination & 0x7f, source), length)
|
||||
}
|
||||
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22 (guide
|
||||
// 13.1.4); 0-5 signed and 6-11 unsigned EQ, LG, GT, GE, LT, LE.
|
||||
[left, right, op @ 0..=11, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
(Op::CompareEqual(left, right), left_length.max(right_length))
|
||||
// VOPC relation offsets: LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
|
||||
let relation = [2, 5, 4, 6, 1, 3][usize::from(op % 6)];
|
||||
let comparison = Comparison {
|
||||
offset: relation,
|
||||
signed: *op < 6,
|
||||
};
|
||||
let op = if relation == 2 {
|
||||
Op::CompareEqual(left, right)
|
||||
} else {
|
||||
Op::ScalarCompare(comparison, left, right)
|
||||
};
|
||||
(op, left_length.max(right_length))
|
||||
}
|
||||
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
|
||||
[
|
||||
left,
|
||||
right,
|
||||
low,
|
||||
high @ (0x80..=0x82 | 0x87 | 0x88 | 0x89),
|
||||
tail @ ..,
|
||||
] if (*left, *right) != (255, 255)
|
||||
&& low & 0x7f <= 105
|
||||
&& (low & 0x80 == 0 || matches!(high, 0x80..=0x82)) =>
|
||||
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
|
||||
if (*left, *right) != (255, 255)
|
||||
&& low & 0x7f <= 105
|
||||
&& matches!(
|
||||
(high & 0x3f) << 1 | low >> 7,
|
||||
0..=10 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
|
||||
| 36 | 38..=40 | 44 | 46..=49 | 53 | 54
|
||||
) =>
|
||||
{
|
||||
let kind = match (high, low >> 7) {
|
||||
(0x80, 0) => ScalarAlu::Add,
|
||||
(0x80, _) => ScalarAlu::Subtract,
|
||||
(0x81, 0) => ScalarAlu::AddSigned,
|
||||
(0x81, _) => ScalarAlu::SubtractSigned,
|
||||
(0x82, 0) => ScalarAlu::AddWithCarry,
|
||||
(0x82, _) => ScalarAlu::SubtractWithBorrow,
|
||||
(0x87, _) => ScalarAlu::And,
|
||||
(0x88, _) => ScalarAlu::Or,
|
||||
_ => ScalarAlu::Xor,
|
||||
let kind = match (high & 0x3f) << 1 | low >> 7 {
|
||||
0 => ScalarAlu::Add,
|
||||
1 => ScalarAlu::Subtract,
|
||||
2 => ScalarAlu::AddSigned,
|
||||
3 => ScalarAlu::SubtractSigned,
|
||||
4 => ScalarAlu::AddWithCarry,
|
||||
5 => ScalarAlu::SubtractWithBorrow,
|
||||
6 => ScalarAlu::Minimum { signed: true },
|
||||
7 => ScalarAlu::Minimum { signed: false },
|
||||
8 => ScalarAlu::Maximum { signed: true },
|
||||
9 => ScalarAlu::Maximum { signed: false },
|
||||
10 => ScalarAlu::Select,
|
||||
14 => ScalarAlu::And,
|
||||
16 => ScalarAlu::Or,
|
||||
18 => ScalarAlu::Xor,
|
||||
20 => ScalarAlu::AndNot,
|
||||
22 => ScalarAlu::OrNot,
|
||||
24 => ScalarAlu::Nand,
|
||||
26 => ScalarAlu::Nor,
|
||||
28 => ScalarAlu::Xnor,
|
||||
30 => ScalarAlu::ShiftLeft,
|
||||
32 => ScalarAlu::ShiftRight,
|
||||
34 => ScalarAlu::ArithmeticShiftRight,
|
||||
36 => ScalarAlu::BitfieldMask,
|
||||
38 => ScalarAlu::Multiply,
|
||||
39 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
40 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
44 => ScalarAlu::AbsoluteDifference,
|
||||
op @ 46..=49 => ScalarAlu::ShiftLeftAdd(op - 45),
|
||||
53 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
_ => ScalarAlu::MultiplyHigh { signed: true },
|
||||
};
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
@@ -652,9 +789,51 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
}
|
||||
Op::ScalarUnary(kind, dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
}
|
||||
let value = read_scalar(src)?;
|
||||
// -1 (all ones) when no bit is found.
|
||||
let found = |index: u32| if index == 32 { u32::MAX } else { index };
|
||||
let result = match kind {
|
||||
ScalarUnary::Not => !value,
|
||||
ScalarUnary::ReverseBits => value.reverse_bits(),
|
||||
ScalarUnary::CountZeros => value.count_zeros(),
|
||||
ScalarUnary::CountOnes => value.count_ones(),
|
||||
ScalarUnary::FindFirstZero => found(value.trailing_ones()),
|
||||
ScalarUnary::FindFirstOne => found(value.trailing_zeros()),
|
||||
ScalarUnary::FindLastBit => found(value.leading_zeros()),
|
||||
ScalarUnary::FindLastSignBit => {
|
||||
let same = if value >> 31 == 1 {
|
||||
value.leading_ones()
|
||||
} else {
|
||||
value.leading_zeros()
|
||||
};
|
||||
found(same)
|
||||
}
|
||||
ScalarUnary::SignExtendByte => value as u8 as i8 as i32 as u32,
|
||||
ScalarUnary::SignExtendShort => value as u16 as i16 as i32 as u32,
|
||||
ScalarUnary::Absolute => (value as i32).wrapping_abs() as u32,
|
||||
};
|
||||
scalars[usize::from(dst)] = Some(result);
|
||||
if matches!(
|
||||
kind,
|
||||
ScalarUnary::Not
|
||||
| ScalarUnary::CountZeros
|
||||
| ScalarUnary::CountOnes
|
||||
| ScalarUnary::Absolute
|
||||
) {
|
||||
scc = Some(result != 0);
|
||||
}
|
||||
}
|
||||
Op::CompareEqual(lhs, rhs) => {
|
||||
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
|
||||
}
|
||||
// Guide 12.4: SCC = (S0 <relation> S1); no SGPR is written.
|
||||
Op::ScalarCompare(comparison, lhs, rhs) => {
|
||||
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
|
||||
}
|
||||
Op::Scalar(kind, dst, lhs, rhs) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -664,8 +843,13 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
ScalarAlu::AddWithCarry | ScalarAlu::SubtractWithBorrow => i64::from(
|
||||
scc.ok_or_else(|| error(offset, "carry-in from uninitialized SCC"))?,
|
||||
),
|
||||
ScalarAlu::Select => {
|
||||
i64::from(scc.ok_or_else(|| error(offset, "select on uninitialized SCC"))?)
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let (signed_lhs, signed_rhs) =
|
||||
(i64::from(lhs as u32 as i32), i64::from(rhs as u32 as i32));
|
||||
// Exact integer arithmetic, then reduction modulo 2^32.
|
||||
let (exact, flag) = match kind {
|
||||
ScalarAlu::Add | ScalarAlu::AddWithCarry => {
|
||||
@@ -694,10 +878,93 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
};
|
||||
(bits, bits != 0)
|
||||
}
|
||||
// Guide 12.1: strict comparisons, so equal operands give
|
||||
// S1 (the same value) and SCC = 0.
|
||||
ScalarAlu::Minimum { signed } | ScalarAlu::Maximum { signed } => {
|
||||
let (a, b) = if signed {
|
||||
(signed_lhs, signed_rhs)
|
||||
} else {
|
||||
(lhs, rhs)
|
||||
};
|
||||
let first = if matches!(kind, ScalarAlu::Minimum { .. }) {
|
||||
a < b
|
||||
} else {
|
||||
a > b
|
||||
};
|
||||
(if first { lhs } else { rhs }, first)
|
||||
}
|
||||
// The SCC-less forms; `flag` is unused for them below.
|
||||
ScalarAlu::Select => (if carry == 1 { lhs } else { rhs }, false),
|
||||
ScalarAlu::BitfieldMask => (((1 << (lhs & 0x1f)) - 1) << (rhs & 0x1f), false),
|
||||
ScalarAlu::Multiply => (signed_lhs * signed_rhs, false),
|
||||
ScalarAlu::MultiplyHigh { signed } => {
|
||||
// The unsigned product fits only in u64.
|
||||
let high = if signed {
|
||||
(signed_lhs * signed_rhs) >> 32
|
||||
} else {
|
||||
((lhs as u64 * rhs as u64) >> 32) as i64
|
||||
};
|
||||
(high, false)
|
||||
}
|
||||
// Offset S1[4:0], width S1[22:16] (0-127). A width of 32 or
|
||||
// more keeps every bit of the shifted word.
|
||||
ScalarAlu::BitfieldExtract { signed } => {
|
||||
let (shift, width) = (rhs & 0x1f, (rhs >> 16) & 0x7f);
|
||||
let data = if signed { signed_lhs } else { lhs };
|
||||
let shifted = data >> shift;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let field = shifted & ((1 << width) - 1);
|
||||
if signed && field >> (width - 1) == 1 {
|
||||
field - (1 << width)
|
||||
} else {
|
||||
field
|
||||
}
|
||||
};
|
||||
(value, value.rem_euclid(1 << 32) != 0)
|
||||
}
|
||||
// The 32-bit difference first (guide examples), then |D|.
|
||||
ScalarAlu::AbsoluteDifference => {
|
||||
let difference = (signed_lhs - signed_rhs) as u32 as i32;
|
||||
let value = difference.unsigned_abs();
|
||||
(i64::from(value), value != 0)
|
||||
}
|
||||
// The carry out of the exact (S0 << N) + S1.
|
||||
ScalarAlu::ShiftLeftAdd(n) => {
|
||||
let sum = (lhs << n) + rhs;
|
||||
(sum, sum >= 1 << 32)
|
||||
}
|
||||
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
|
||||
_ => {
|
||||
let (a, b) = (lhs as u32, rhs as u32);
|
||||
let bits = match kind {
|
||||
ScalarAlu::AndNot => a & !b,
|
||||
ScalarAlu::OrNot => a | !b,
|
||||
ScalarAlu::Nand => !(a & b),
|
||||
ScalarAlu::Nor => !(a | b),
|
||||
ScalarAlu::Xnor => !(a ^ b),
|
||||
ScalarAlu::ShiftLeft => a << (b & 0x1f),
|
||||
ScalarAlu::ShiftRight => a >> (b & 0x1f),
|
||||
_ => ((a as i32) >> (b & 0x1f)) as u32,
|
||||
};
|
||||
(i64::from(bits), bits != 0)
|
||||
}
|
||||
};
|
||||
let value = exact.rem_euclid(1 << 32) as u32;
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
scc = Some(flag);
|
||||
// Guide 12.1 and Tables 11, 12, 14: these forms leave SCC unchanged.
|
||||
if !matches!(
|
||||
kind,
|
||||
ScalarAlu::Select
|
||||
| ScalarAlu::BitfieldMask
|
||||
| ScalarAlu::Multiply
|
||||
| ScalarAlu::MultiplyHigh { .. }
|
||||
) {
|
||||
scc = Some(flag);
|
||||
}
|
||||
}
|
||||
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
|
||||
Op::Compare(comparison, src0, src1) => {
|
||||
|
||||
@@ -809,6 +809,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
*slot = Some(value);
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = read_scalar(src)?;
|
||||
if dst < 8 {
|
||||
return Err(error("scalar unary would modify a resource descriptor"));
|
||||
}
|
||||
let (value, flag) = op.evaluate(src);
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
@@ -816,24 +831,26 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
src1,
|
||||
} => {
|
||||
let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?);
|
||||
let carry_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("carry-in or borrow-in reads uninitialized SCC"))?
|
||||
let scc_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("SOP2 SCC input reads uninitialized SCC"))?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if dst < 8 {
|
||||
return Err(error("scalar ALU would modify a resource descriptor"));
|
||||
}
|
||||
let (value, flag) = op.evaluate(src0, src1, carry_in);
|
||||
let (value, flag) = op.evaluate(src0, src1, scc_in);
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
scc = Some(flag);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/vector-compare.md sections 3 and 5.
|
||||
|
||||
@@ -280,6 +280,62 @@ fn scalar_alu_results_reach_the_kernel_as_constants() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_logic_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-logic.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-logic.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-logic.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_results_resolve_every_branch() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-compare.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_arith_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-arith.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-arith.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-arith.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
|
||||
|
||||
@@ -22,7 +22,9 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
## RDNA 2 decoding and shader translation
|
||||
|
||||
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
|
||||
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
|
||||
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
|
||||
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
|
||||
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
|
||||
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
|
||||
|
||||
|
||||
@@ -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: 42 of 42. Accepted Metal forms · Apple M5: 18 of 42. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 88 of 88. Accepted Metal forms · Apple M5: 18 of 88. 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">42 / 42</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">88 / 88</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 / 42</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 88</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="210.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="100.23" 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 |
@@ -21,7 +21,29 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
|
||||
| `s_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 |
|
||||
| `s_bcnt0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0 | `BE8C0D08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bcnt1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0 | `BE8B0F08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged | `BE8E11FF 0000FFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged | `BE8D13FF 00400000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged | `BE8F1508` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged | `BE9017FF FFF00000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sext_i32_i8` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged | `BE911908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `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_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 |
|
||||
| `s_cmp_ge_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed) | `BF030909` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed) | `BF040908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed) | `BF050809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned) | `BF07FF0A 89ABCDEF` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned) | `BF080908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_ge_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned) | `BF090809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned) | `BF0A0809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned) | `BF0BC009` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8110C109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -31,6 +53,30 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_andn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0 | `8A09FF08 FF00FF00` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_orn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 \| ~S1; SCC = result != 0 | `8B0AC109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_nand_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0 | `8C0B0808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_nor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 \| S1); SCC = result != 0 | `8D0C090B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_xnor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0 | `8E0D080C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0 | `8F0EA40D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshr_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0 | `900FFF0E FFFFFFE1` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ashr_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0 | `91109F0E` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_min_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1 | `830A0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_min_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1 | `83988509` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_max_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1 | `84170908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_max_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1 | `848C0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cselect_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged | `850B0809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfm_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged | `920D848C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged | `930F0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfe_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0 | `9390FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfe_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0 | `9411FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_absdiff_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = \|S0 - S1\| of the 32-bit difference (0x80000000 stays); SCC = D != 0 | `96120809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl1_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum | `970E0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl2_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum | `97990909` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl3_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum | `98130808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl4_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum | `9894D009` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_hi_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged | `9A950808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_hi_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged | `9B160808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
|
||||
@@ -8,8 +8,10 @@
|
||||
| SOPP `S_WAITCNT`, SOPK `S_WAITCNT_VSCNT` | A zero vector-load or vector-store threshold completes the associated transfer. The model permits one pending operation per counter (CLAIM-RDNA2-TRANSFER-WAITS). |
|
||||
| VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. |
|
||||
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_MIN_{I32,U32}`, `S_MAX_{I32,U32}`, `S_CSELECT_B32`, `S_BFM_B32`, `S_MUL_I32`, `S_MUL_HI_{U32,I32}`, `S_BFE_{U32,I32}`, `S_ABSDIFF_I32`, `S_LSHL{1,2,3,4}_ADD_U32` | The guide's section 12.1 result, computed exactly and reduced modulo 2^32. Min and max compare strictly (a tie gives S1, SCC = 0); CSELECT reads SCC and refuses it unset; BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; BFE uses offset S1[4:0] and width S1[22:16] (32 or more keeps every shifted bit); ABSDIFF negates the wrapped difference; LSHLn_ADD sets SCC to the carry of the exact sum. Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
|
||||
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
|
||||
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
|
||||
|
||||
+120
-6
@@ -1,7 +1,9 @@
|
||||
# SOP2 scalar ALU subset
|
||||
|
||||
Xenora decodes and executes nine gfx1030 SOP2 forms. Each takes 32-bit
|
||||
operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
Xenora decodes and executes thirty-three gfx1030 SOP2 forms. Each takes 32-bit
|
||||
operands and writes a normal SGPR (s0-s105). The seventeen below set SCC; the
|
||||
sixteen in [Arithmetic, select and bit-field forms](#arithmetic-select-and-bit-field-forms)
|
||||
set it or leave it as the guide says.
|
||||
|
||||
| Form | D | SCC |
|
||||
| --- | --- | --- |
|
||||
@@ -14,8 +16,33 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
| `s_and_b32` | S0 & S1 | D != 0 |
|
||||
| `s_or_b32` | S0 \| S1 | D != 0 |
|
||||
| `s_xor_b32` | S0 ^ S1 | D != 0 |
|
||||
| `s_andn2_b32` | S0 & ~S1 | D != 0 |
|
||||
| `s_orn2_b32` | S0 \| ~S1 | D != 0 |
|
||||
| `s_nand_b32` | ~(S0 & S1) | D != 0 |
|
||||
| `s_nor_b32` | ~(S0 \| S1) | D != 0 |
|
||||
| `s_xnor_b32` | ~(S0 ^ S1) | D != 0 |
|
||||
| `s_lshl_b32` | S0 << S1[4:0] | D != 0 |
|
||||
| `s_lshr_b32` | S0 >> S1[4:0], zero fill | D != 0 |
|
||||
| `s_ashr_i32` | S0 >> S1[4:0], sign fill | D != 0 |
|
||||
|
||||
The last eight were added through the semantic registry alone: one TOML entry
|
||||
each, with no hand-written Rust per form. Shifts use only the low five bits of
|
||||
S1 as the count, as the guide's pseudocode states (section 12.1); higher bits are
|
||||
ignored.
|
||||
|
||||
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
|
||||
|
||||
These forms are declared as data in the semantic registry,
|
||||
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
|
||||
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
|
||||
checks each declaration against the pinned AMD XML snapshot and rejects
|
||||
contradictions (for example a carry-in on a bitwise form, or a signed form whose
|
||||
SCC is a carry). It then generates `crates/isa/src/semantics_gen.rs`, which holds
|
||||
the decoder's opcode dispatch and `ScalarAluOp`'s mnemonic, SCC read and
|
||||
evaluation through the shared primitives in `crates/isa/src/primitive.rs`. Run
|
||||
`python3 crates/isa/generate_semantics.py validate`, `generate` or `--check`
|
||||
(Python 3.11 or newer). The reference and independent interpreters do not use
|
||||
the registry.
|
||||
`v_mov_b32_e32` may read a normal SGPR, so the results can reach vector code.
|
||||
|
||||
## Sources
|
||||
@@ -43,17 +70,17 @@ Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
|
||||
|
||||
## Not supported
|
||||
|
||||
- Every other SOP2 form, including the 64-bit bitwise forms.
|
||||
- Every other SOP2 form, including the 64-bit bitwise forms and `s_cselect_b64`.
|
||||
- Destinations other than s0-s105 (VCC, EXEC, TTMP and M0).
|
||||
- Sources other than normal SGPRs, inline integers and one literal.
|
||||
- Both sources selecting a literal.
|
||||
- ADDC or SUBB before SCC is set.
|
||||
- ADDC, SUBB or CSELECT before SCC is set.
|
||||
- Writes to the fixture's resource descriptors s0-s7.
|
||||
|
||||
## How it runs
|
||||
|
||||
Scalar state in a compute fixture is wave-uniform and known while the code is
|
||||
translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates
|
||||
translated. As with `s_mov_b32` and the SOPC compares, the translator evaluates
|
||||
SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values
|
||||
read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the
|
||||
IR and MSL contain the results, not scalar instructions.
|
||||
@@ -73,7 +100,7 @@ literal operands, bitwise results that set and clear SCC, and an
|
||||
Its expected output, input ^ 0x0000000e,
|
||||
was derived by hand.
|
||||
|
||||
`tests/validation/known_answers.rs` runs every supported form over 10 boundary
|
||||
`tests/validation/known_answers.rs` runs the first nine forms over 10 boundary
|
||||
operands squared, with SCC clear and set. That is 1,800 programs. The same file
|
||||
covers aliasing, inline and literal operands, and rejected forms. Expected
|
||||
values come from exact integer definitions in the test. Three implementations
|
||||
@@ -82,7 +109,94 @@ must agree with them:
|
||||
- the reference interpreter (exact integers, reduced modulo 2^32);
|
||||
- the independent interpreter (a bit-serial ripple-carry adder).
|
||||
|
||||
The eight logical and shift forms added through the registry have their own
|
||||
suite, `tests/validation/tests/sop2_stage_c.rs`: 6,896 cases whose expected
|
||||
values were derived from the guide separately from the registry, checked on
|
||||
both CPU interpreters and, through the translator, on native Metal. The
|
||||
LLVM-assembled `fixtures/rdna2/scalar-logic.s` (expected input ^ 0x887f00f8)
|
||||
runs on all three and on native Metal.
|
||||
|
||||
`scalar_alu_native_metal_known_answers` runs the fixture, the 1,800 programs
|
||||
and the aliasing and immediate cases on native Metal with API and shader
|
||||
validation. `scripts/test-gpu.sh` runs it. This is local evidence from one
|
||||
Apple M5 Pro; independent acceptance is pending.
|
||||
|
||||
## Arithmetic, select and bit-field forms
|
||||
|
||||
Sixteen more 32-bit SOP2 forms are declared in the registry with the same
|
||||
operand rule (`sop2_sgpr`), each one TOML entry over a shared primitive:
|
||||
|
||||
| Form | D | SCC |
|
||||
| --- | --- | --- |
|
||||
| `s_min_i32`, `s_min_u32` | S0 if S0 < S1 (signed or unsigned), else S1 | S0 < S1 |
|
||||
| `s_max_i32`, `s_max_u32` | S0 if S0 > S1, else S1 | S0 > S1 |
|
||||
| `s_cselect_b32` | SCC ? S0 : S1 | read, not written |
|
||||
| `s_bfm_b32` | ((1 << S0[4:0]) - 1) << S1[4:0] | unchanged |
|
||||
| `s_mul_i32` | low 32 bits of S0 * S1 | unchanged |
|
||||
| `s_mul_hi_u32`, `s_mul_hi_i32` | high 32 bits of the unsigned or signed 64-bit product | unchanged |
|
||||
| `s_bfe_u32` | (S0 >> S1[4:0]) masked to S1[22:16] bits | D != 0 |
|
||||
| `s_bfe_i32` | (S0 >> S1[4:0], sign fill) masked to S1[22:16] bits, sign-extended from the field's top bit | D != 0 |
|
||||
| `s_absdiff_i32` | \|S0 - S1\| of the wrapped 32-bit difference (0x80000000 stays) | D != 0 |
|
||||
| `s_lshl1_add_u32` to `s_lshl4_add_u32` | (S0 << N) + S1, N = 1 to 4 | carry out of the exact sum, counting bits shifted out of S0 |
|
||||
|
||||
These follow the guide's 12.1 pseudocode and Tables 11, 12 and 14 (pages
|
||||
34-36). Min and max compare strictly, so equal operands give S1 and SCC = 0.
|
||||
The guide leaves two C-like operators open; Xenora reads them as exact
|
||||
arithmetic: a BFE width of 32 to 127 keeps every shifted bit, and a width of 0
|
||||
gives 0. These are guide readings, not hardware evidence. CSELECT is refused
|
||||
when SCC has not been set, as ADDC and SUBB are.
|
||||
|
||||
The registry gained the vocabulary for them: the operations above, a
|
||||
`selected_src0` SCC effect for min and max, `carry_in = "scc"` for the select
|
||||
condition, and a declared `shift_amount` (1 to 4) for the shift-and-add forms.
|
||||
The generated `ScalarAluOp::evaluate` now returns `(u32, Option<bool>)`, with
|
||||
`None` for forms that leave SCC unchanged.
|
||||
|
||||
`tests/validation/tests/sop2_arith.rs` checks 21,070 cases, with expected values
|
||||
derived from the guide (including its ABSDIFF examples) separately from the
|
||||
registry, on both CPU interpreters and, through the translator, on native
|
||||
Metal; its 597 rejected programs are checked on the CPU interpreters and the
|
||||
compiler. `fixtures/rdna2/scalar-arith.s` (LLVM-assembled, expected input ^
|
||||
0x81157dfe) chains all sixteen, including a min tie and CSELECT on both SCC
|
||||
values, and shows SCC surviving the forms that do not write it.
|
||||
|
||||
## SOPC compares
|
||||
|
||||
The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`
|
||||
are declared in the same registry (operand rule `sopc_scalar`). Each sets only
|
||||
SCC, to whether the relation holds with SSRC0 on the left; LG means not equal.
|
||||
EQ and LG give the same result for `_i32` and `_u32`; GT, GE, LT and LE compare
|
||||
two's-complement values for `_i32` and unsigned values for `_u32` (guide section
|
||||
12.4). Sources follow the SOP2 rule: normal SGPRs, inline integers or one
|
||||
literal. Both sources selecting the literal encoding (255) is rejected for SOPC
|
||||
as for SOP2; whether the guide allows one shared literal there was not settled.
|
||||
|
||||
`tests/validation/tests/sopc_stage_d.rs` checks 7,824 cases, with expected
|
||||
values derived from the guide separately from the registry, on both CPU
|
||||
interpreters and, through the translator, on native Metal (compiled per case
|
||||
and read back from nine distinct generated kernels). Its 348 rejected programs
|
||||
are checked on both CPU interpreters and against the compiler, which rejects
|
||||
them before any Metal dispatch. `fixtures/rdna2/scalar-compare.s` (LLVM-assembled, expected input ^
|
||||
0x00000d5b) records every compare's SCC through an `s_cbranch_scc0` per form.
|
||||
|
||||
## SOP1 unary forms
|
||||
|
||||
Eleven 32-bit SOP1 forms are declared in the registry (operand rule
|
||||
`sop1_sgpr`): `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
|
||||
`s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
|
||||
`s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`. Following the guide (section
|
||||
12.3): a find-first or find-last search that finds nothing returns -1
|
||||
(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
|
||||
(they hold its buffer descriptors), and float inline constants are rejected.
|
||||
|
||||
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
|
||||
derived from the guide (including its worked examples) separately from the
|
||||
registry, on both CPU interpreters and, through the translator, on native
|
||||
Metal; its 231 rejected programs are checked on the CPU interpreters and the
|
||||
compiler. `fixtures/rdna2/scalar-unary.s` (LLVM-assembled, expected input ^
|
||||
0x0f0080f5) chains all eleven and shows SCC surviving the forms that do not
|
||||
write it.
|
||||
@@ -0,0 +1,49 @@
|
||||
# gfx1030 semantic coverage
|
||||
|
||||
<!-- Generated by scripts/audit/semantic_coverage.py. -->
|
||||
|
||||
Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms
|
||||
come from the semantic registry. Decoder support is the decoder's hand-written
|
||||
list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.
|
||||
|
||||
The status inventory records LLVM three-way encoding checks, intermediate
|
||||
representation (IR) and Metal Shading Language (MSL) lowering, and fixture
|
||||
verification. IR and MSL share the inventory's lowering field. Reference
|
||||
verification requires an implemented reference and verified CPU fixture.
|
||||
Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending
|
||||
acceptance remain outside the verified count. All results concern synthetic fixtures.
|
||||
|
||||
| Family | Identified | Encoding-validated | Declared | Decoder-supported | IR | MSL | Reference-verified | Metal-verified | Unsupported operand variants |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| DS | 123 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| EXP | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
|
||||
| FLAT | 54 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| GLOBAL | 57 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MIMG | 130 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MTBUF | 16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
|
||||
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SOP1 | 65 | 12 | 11 | 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 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP2 | 47 | 8 | 0 | 8 | 8 | 8 | 7 | 7 | 0 |
|
||||
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
|
||||
| **Total** | 1465 | 88 | 56 | 92 | 88 | 88 | 18 | 18 | 30 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
The table counts distinct variant names per family across registry operand rules.
|
||||
|
||||
| Family | Operand rule | Unsupported variants |
|
||||
| --- | --- | --- |
|
||||
| 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` |
|
||||
@@ -0,0 +1,240 @@
|
||||
# Adding an instruction through the semantic registry
|
||||
|
||||
The semantic registry is a data file that declares what each supported gfx1030
|
||||
instruction form does. A generator checks it and turns it into Rust tables that
|
||||
the decoder uses. This page explains where entries live, what each field means,
|
||||
how to check and regenerate the tables, and what the generator does not do for
|
||||
you.
|
||||
|
||||
The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.md).
|
||||
|
||||
## Files
|
||||
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. |
|
||||
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
|
||||
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
|
||||
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
|
||||
| `crates/isa/src/semantics.rs` | The Rust types the generated tables use (`FormSemantics`, `Operation`, `SccEffect` and so on). |
|
||||
| `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. |
|
||||
| `tests/semantics_generator/` | Unit tests for the generator. |
|
||||
|
||||
## Fields
|
||||
|
||||
The top of the file holds:
|
||||
|
||||
- `schema`: must be `1`.
|
||||
- `architecture`: must be `"gfx1030"`.
|
||||
- `source_sha256`: must equal the `sha256` on the `source` line of
|
||||
`crates/isa/data/rdna2.jsonl`, so the registry is always checked against the
|
||||
snapshot it was written for.
|
||||
- `[documents.<name>]`: the public documents that spec references cite. Only
|
||||
`guide` (the AMD RDNA 2 ISA reference guide) and `xml` (the AMD
|
||||
machine-readable ISA) are allowed, and each must match the title and file
|
||||
pinned in the generator, so a citation cannot point at another file.
|
||||
- `[operand_rules.<name>]`: an operand rule shared by a whole family. The
|
||||
decoder implements each rule once, and the generator only accepts a rule
|
||||
whose declaration matches the decoder's implementation exactly. Today there
|
||||
is one rule, `sop2_sgpr`: an SGPR destination `s0`-`s105`, two scalar sources
|
||||
(an SGPR, an inline integer -16 to 64, or a literal word) and at most one
|
||||
literal. Its `unsupported` list names the encodings the rule rejects, which
|
||||
stay unsupported instead of being guessed. The list must name exactly the
|
||||
encodings the decoder rejects.
|
||||
|
||||
Each `[[form]]` entry has exactly these fields. A missing or unknown field is an
|
||||
error.
|
||||
|
||||
| Field | Meaning | Allowed values |
|
||||
| --- | --- | --- |
|
||||
| `name` | XML instruction name, the form's stable identity | upper-case, e.g. `S_ADD_U32` |
|
||||
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
|
||||
| `opcode` | Opcode; must match the XML | non-negative integer |
|
||||
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `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` |
|
||||
| `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 |
|
||||
| `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 S1 used as the count. The generator masks S1 with it, and the XML must list S1 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` (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` |
|
||||
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
|
||||
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
|
||||
|
||||
The `operation` and `signedness` pair picks one primitive, and that primitive
|
||||
fixes the `scc` value:
|
||||
|
||||
| `operation` / `signedness` | Required `scc` | Primitive | Reads carry-in |
|
||||
| --- | --- | --- | --- |
|
||||
| `add` / `unsigned` | `carry_out` | `add_carry_u32` | allowed |
|
||||
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
|
||||
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
|
||||
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
|
||||
| `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32`, `andn2_nonzero_b32`, `orn2_nonzero_b32`, `nand_nonzero_b32`, `nor_nonzero_b32`, `xnor_nonzero_b32` | no |
|
||||
| `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no |
|
||||
| `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no |
|
||||
| `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no |
|
||||
| `not`, `bcnt0`, `bcnt1` / `bitwise` | `nonzero` | `not_nonzero_b32`, `bcnt0_nonzero_b32`, `bcnt1_nonzero_b32` | no |
|
||||
| `brev`, `ff0`, `ff1`, `flbit` / `bitwise` | `unchanged` | `brev_b32`, `ff0_b32`, `ff1_b32`, `flbit_b32` | no |
|
||||
| `flbit`, `sext` / `signed` | `unchanged` | `flbit_i32`, `sext_i32` | no |
|
||||
| `abs` / `signed` | `nonzero` | `abs_nonzero_i32` | no |
|
||||
| `min`, `max` / `signed` or `unsigned` | `selected_src0` | `min_i32`/`min_u32`, `max_i32`/`max_u32` | no |
|
||||
| `cselect` / `bitwise` | `unchanged` | `cselect_b32` | required |
|
||||
| `bfm` / `bitwise` | `unchanged` | `bfm_b32` | no |
|
||||
| `mul` / `signed` | `unchanged` | `mul_lo_i32` | no |
|
||||
| `mul_hi` / `unsigned` or `signed` | `unchanged` | `mul_hi_u32`, `mul_hi_i32` | no |
|
||||
| `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 |
|
||||
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
|
||||
|
||||
A 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`.
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
## What the validator checks
|
||||
|
||||
`validate` reports every error it finds, not only the first (a form with a missing field is not checked further). Besides the
|
||||
vocabularies above, it rejects:
|
||||
|
||||
- contradictions: a declared `scc` or `carry_in` that the primitive does not
|
||||
have, `bitwise` on an arithmetic operation or the reverse;
|
||||
- duplicates: the same `name`, the same `(family, opcode)` or the same
|
||||
`variant` declared twice;
|
||||
- XML disagreements: a family with no XML encoding, a form with no default XML
|
||||
variant, a different opcode, an SCC input or output the XML does not show (or
|
||||
that the declaration omits), an operand width other than `width`, a signed
|
||||
declaration on unsigned XML formats or the reverse (a shift count or the `bfe`
|
||||
field descriptor in S1 must be `FMT_NUM_U32` whatever the signedness), an operand direction that
|
||||
differs, and XML operands the operand rule does not cover;
|
||||
- references: a spec citing an undeclared document, a bad section or page, or
|
||||
no guide page at all;
|
||||
- operand rules the decoder does not implement, or whose declaration differs
|
||||
from the implemented one;
|
||||
- wrong types: a float width, a boolean schema, an opcode or page outside
|
||||
0-65535, or a reserved variant name such as `Self`.
|
||||
|
||||
CI runs `generate_semantics.py --check`, `scripts/audit/semantic_coverage.py
|
||||
--check` and both Python test suites next to the existing
|
||||
`generate_rdna2_meta.py --check`. Both scripts stop with a clear message on
|
||||
Python older than 3.11.
|
||||
|
||||
## What the generator does not do
|
||||
|
||||
- **The XML gives identity and encodings only.** The snapshot confirms the
|
||||
name, family, opcode, operand fields, widths, number formats and whether SCC
|
||||
is read or written. It says nothing about the arithmetic. Behaviour comes from
|
||||
the AMD guide, cited in `spec`, through the closed primitive table.
|
||||
- **It does not invent behaviour.** A form whose operation, signedness or
|
||||
operand rule is not already implemented is rejected. Adding a new operation
|
||||
means hand-writing a primitive in `primitive.rs`, a variant in
|
||||
`semantics.rs` and a row in the generator's vocabulary tables, reviewed like
|
||||
any other code.
|
||||
- **Undeclared forms stay unsupported.** The generated `from_word` returns
|
||||
`None` for every opcode not in the registry, and the decoder reports
|
||||
`UnsupportedOpcode`. Nothing falls back to a guess or a no-op.
|
||||
- **It does not write tests or reference semantics.** The reference
|
||||
interpreter (`crates/ref`) and the independent interpreter
|
||||
(`tests/validation/independent_ref.rs`) never read the registry or the
|
||||
generated code, and their known-answer tests are written by hand from the
|
||||
guide. That independence is what lets them catch a wrong registry entry; keep
|
||||
it when you add a form. Agreement with these references is agreement with a
|
||||
reading of the public AMD guide, not with Xbox hardware.
|
||||
|
||||
## Commands
|
||||
|
||||
Run these from the repository root. `python3` must be 3.11 or newer.
|
||||
|
||||
```sh
|
||||
# Check the registry only.
|
||||
python3 crates/isa/generate_semantics.py validate
|
||||
|
||||
# Validate, then rewrite crates/isa/src/semantics_gen.rs.
|
||||
python3 crates/isa/generate_semantics.py generate
|
||||
|
||||
# Validate and regenerate in memory; exit 1 if the committed file is stale. Never writes.
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
|
||||
# Generator unit tests.
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
|
||||
# The XML metadata tables the registry is cross-checked against are still current.
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
|
||||
# Rust tests of the generated tables and the decoder that uses them.
|
||||
cargo test --locked -p xenora-isa -p xenora-decoder
|
||||
|
||||
# Independent CPU validation.
|
||||
cargo test --locked -p xenora-semantic-review
|
||||
|
||||
# Native GPU correctness on Apple silicon.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The LLVM encoding corpus check needs an LLVM build with the AMDGPU target:
|
||||
|
||||
```sh
|
||||
python3 crates/isa/tests/llvm/corpus.py --llvm-bin /path/to/llvm/bin --check
|
||||
```
|
||||
|
||||
## Worked example: `s_addc_u32`
|
||||
|
||||
`s_addc_u32` adds two 32-bit sources plus SCC and writes the carry-out of
|
||||
bit 31 to SCC (guide section 12.1, page 102; SCC rules in section 5.3, page 33).
|
||||
Its registry entry is:
|
||||
|
||||
```toml
|
||||
[[form]]
|
||||
name = "S_ADDC_U32"
|
||||
family = "SOP2"
|
||||
opcode = 4
|
||||
variant = "AddcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
```
|
||||
|
||||
How each field is checked:
|
||||
|
||||
1. The XML snapshot has a default `ENC_SOP2` variant named `S_ADDC_U32` with
|
||||
opcode 4, so `name`, `family` and `opcode` agree.
|
||||
2. That XML variant reads and writes SCC, which matches `carry_in = "scc"` and
|
||||
an `scc` other than `unchanged`.
|
||||
3. `add` / `unsigned` selects `add_carry_u32`, which requires
|
||||
`scc = "carry_out"` and accepts a carry-in.
|
||||
4. The XML `SDST`, `SSRC0` and `SSRC1` operands are 32-bit `FMT_NUM_U32`
|
||||
fields, which matches `width = 32`, `unsigned` and the `sop2_sgpr` rule.
|
||||
|
||||
From this entry the generator emits, in `semantics_gen.rs`, the `AddcU32`
|
||||
variant of `ScalarAluOp`, its `from_word` arm (`0x8200_0000`), the mnemonic
|
||||
`s_addc_u32`, `reads_scc() == true`, an `evaluate` arm that calls
|
||||
`primitive::add_carry_u32(src0, src1, carry_in)`, and a `FormSemantics` row.
|
||||
|
||||
To add a form the same way:
|
||||
|
||||
1. Confirm its behaviour in the AMD guide and note the section and page.
|
||||
2. Check that an existing primitive and operand rule cover it. If not, the
|
||||
form needs hand-written code first (see above).
|
||||
3. Add a `[[form]]` entry and run `validate` until it reports no errors.
|
||||
4. Run `generate` and commit the registry and `semantics_gen.rs` together.
|
||||
5. Add known-answer tests to the reference and independent interpreters by
|
||||
hand, then run every command in [Commands](#commands).
|
||||
@@ -135,6 +135,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_not_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0"
|
||||
representation = "`BE890708`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_brev_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged"
|
||||
representation = "`BE8A0B08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bcnt0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0"
|
||||
representation = "`BE8C0D08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bcnt1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0"
|
||||
representation = "`BE8B0F08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ff0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged"
|
||||
representation = "`BE8E11FF 0000FFFF`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ff1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8D13FF 00400000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_flbit_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8F1508`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_flbit_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged"
|
||||
representation = "`BE9017FF FFF00000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_sext_i32_i8"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE911908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_sext_i32_i16"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE921AFF 00018000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_abs_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = |S0| (0x80000000 stays); SCC = D != 0"
|
||||
representation = "`BE933412`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_u32"
|
||||
encoding = "Normal SGPR or integer operands, with at most one source selecting a literal"
|
||||
@@ -147,6 +279,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)"
|
||||
representation = "`BF00C108`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lg_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed)"
|
||||
representation = "`BF010908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_gt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed)"
|
||||
representation = "`BF020908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_ge_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed)"
|
||||
representation = "`BF030909`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed)"
|
||||
representation = "`BF040908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_le_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed)"
|
||||
representation = "`BF050809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lg_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned)"
|
||||
representation = "`BF07FF0A 89ABCDEF`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_gt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned)"
|
||||
representation = "`BF080908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_ge_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned)"
|
||||
representation = "`BF090809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned)"
|
||||
representation = "`BF0A0809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_le_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned)"
|
||||
representation = "`BF0BC009`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out"
|
||||
@@ -255,6 +519,294 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_andn2_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0"
|
||||
representation = "`8A09FF08 FF00FF00`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_orn2_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 | ~S1; SCC = result != 0"
|
||||
representation = "`8B0AC109`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_nand_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0"
|
||||
representation = "`8C0B0808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_nor_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 | S1); SCC = result != 0"
|
||||
representation = "`8D0C090B`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_xnor_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0"
|
||||
representation = "`8E0D080C`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0"
|
||||
representation = "`8F0EA40D`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshr_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0"
|
||||
representation = "`900FFF0E FFFFFFE1`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ashr_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0"
|
||||
representation = "`91109F0E`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_min_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1"
|
||||
representation = "`830A0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_min_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1"
|
||||
representation = "`83988509`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_max_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1"
|
||||
representation = "`84170908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_max_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1"
|
||||
representation = "`848C0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cselect_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged"
|
||||
representation = "`850B0809`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bfm_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged"
|
||||
representation = "`920D848C`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_mul_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged"
|
||||
representation = "`930F0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bfe_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0"
|
||||
representation = "`9390FF08 00080004`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bfe_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0"
|
||||
representation = "`9411FF08 00080004`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_absdiff_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = |S0 - S1| of the 32-bit difference (0x80000000 stays); SCC = D != 0"
|
||||
representation = "`96120809`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl1_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`970E0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl2_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`97990909`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl3_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`98130808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl4_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`9894D009`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_mul_hi_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged"
|
||||
representation = "`9A950808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_mul_hi_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged"
|
||||
representation = "`9B160808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_lt_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0068: branch.uniform 0x0074 taken=true
|
||||
0074: t2 = const.u32 0x89abcdef
|
||||
0078: t3 = const.u32 0x00000005
|
||||
007c: t4 = xor.b32 t2, t3
|
||||
0080: t5 = const.u32 0x89abcdef
|
||||
0084: t6 = xor.b32 t4, t5
|
||||
0088: t7 = const.u32 0x0000fff0
|
||||
008c: t8 = xor.b32 t6, t7
|
||||
0090: t9 = const.u32 0x13579be3
|
||||
0094: t10 = xor.b32 t8, t9
|
||||
0098: t11 = const.u32 0xb05b05ab
|
||||
009c: t12 = xor.b32 t10, t11
|
||||
00a0: t13 = const.u32 0x000000de
|
||||
00a4: t14 = xor.b32 t12, t13
|
||||
00a8: t15 = const.u32 0xffffffde
|
||||
00ac: t16 = xor.b32 t14, t15
|
||||
00b0: t17 = const.u32 0x76543216
|
||||
00b4: t18 = xor.b32 t16, t17
|
||||
00b8: t19 = const.u32 0xd70a3d67
|
||||
00bc: t20 = xor.b32 t18, t19
|
||||
00c0: t21 = const.u32 0x00000040
|
||||
00c4: t22 = xor.b32 t20, t21
|
||||
00c8: t23 = const.u32 0x4a0955b6
|
||||
00cc: t24 = xor.b32 t22, t23
|
||||
00d0: t25 = const.u32 0x36b1b9d8
|
||||
00d4: t26 = xor.b32 t24, t25
|
||||
00d8: t27 = const.u32 0x00000005
|
||||
00dc: t28 = xor.b32 t26, t27
|
||||
00e0: t29 = const.u32 0x00000005
|
||||
00e4: t30 = xor.b32 t28, t29
|
||||
00e8: t31 = const.u32 0x00000019
|
||||
00ec: t32 = xor.b32 t30, t31
|
||||
00f0: t33 = const.u32 0x00000005
|
||||
00f4: t34 = xor.b32 t32, t33
|
||||
00f8: t35 = const.u32 0x00000000
|
||||
00fc: t36 = xor.b32 t34, t35
|
||||
0100: t37 = xor.b32 t0, t36
|
||||
0104: store.u32 output[index], t37
|
||||
@@ -0,0 +1,45 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t2 = 0x89abcdefu;
|
||||
uint t3 = 0x00000005u;
|
||||
uint t4 = t2 ^ t3;
|
||||
uint t5 = 0x89abcdefu;
|
||||
uint t6 = t4 ^ t5;
|
||||
uint t7 = 0x0000fff0u;
|
||||
uint t8 = t6 ^ t7;
|
||||
uint t9 = 0x13579be3u;
|
||||
uint t10 = t8 ^ t9;
|
||||
uint t11 = 0xb05b05abu;
|
||||
uint t12 = t10 ^ t11;
|
||||
uint t13 = 0x000000deu;
|
||||
uint t14 = t12 ^ t13;
|
||||
uint t15 = 0xffffffdeu;
|
||||
uint t16 = t14 ^ t15;
|
||||
uint t17 = 0x76543216u;
|
||||
uint t18 = t16 ^ t17;
|
||||
uint t19 = 0xd70a3d67u;
|
||||
uint t20 = t18 ^ t19;
|
||||
uint t21 = 0x00000040u;
|
||||
uint t22 = t20 ^ t21;
|
||||
uint t23 = 0x4a0955b6u;
|
||||
uint t24 = t22 ^ t23;
|
||||
uint t25 = 0x36b1b9d8u;
|
||||
uint t26 = t24 ^ t25;
|
||||
uint t27 = 0x00000005u;
|
||||
uint t28 = t26 ^ t27;
|
||||
uint t29 = 0x00000005u;
|
||||
uint t30 = t28 ^ t29;
|
||||
uint t31 = 0x00000019u;
|
||||
uint t32 = t30 ^ t31;
|
||||
uint t33 = 0x00000005u;
|
||||
uint t34 = t32 ^ t33;
|
||||
uint t35 = 0x00000000u;
|
||||
uint t36 = t34 ^ t35;
|
||||
uint t37 = t0 ^ t36;
|
||||
output[index] = t37;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
001c: branch.uniform 0x0024 taken=false
|
||||
0028: branch.uniform 0x0030 taken=false
|
||||
0034: branch.uniform 0x003c taken=true
|
||||
0040: branch.uniform 0x0048 taken=false
|
||||
004c: branch.uniform 0x0054 taken=false
|
||||
0058: branch.uniform 0x0060 taken=true
|
||||
0064: branch.uniform 0x006c taken=false
|
||||
007c: branch.uniform 0x0088 taken=true
|
||||
008c: branch.uniform 0x0098 taken=false
|
||||
009c: branch.uniform 0x00a8 taken=true
|
||||
00ac: branch.uniform 0x00b8 taken=false
|
||||
00bc: branch.uniform 0x00c8 taken=false
|
||||
00c8: t13 = const.u32 0x00000d5b
|
||||
00cc: t14 = xor.b32 t0, t13
|
||||
00d0: store.u32 output[index], t14
|
||||
@@ -0,0 +1,11 @@
|
||||
#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 t13 = 0x00000d5bu;
|
||||
uint t14 = t0 ^ t13;
|
||||
output[index] = t14;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0040: branch.uniform 0x004c taken=true
|
||||
004c: t2 = const.u32 0xff0fffff
|
||||
0050: t3 = const.u32 0x787ffff8
|
||||
0054: t4 = xor.b32 t2, t3
|
||||
0058: t5 = const.u32 0xffffffff
|
||||
005c: t6 = xor.b32 t4, t5
|
||||
0060: t7 = const.u32 0x00f00000
|
||||
0064: t8 = xor.b32 t6, t7
|
||||
0068: t9 = const.u32 0xf000ff00
|
||||
006c: t10 = xor.b32 t8, t9
|
||||
0070: t11 = xor.b32 t0, t10
|
||||
0074: store.u32 output[index], t11
|
||||
@@ -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 t2 = 0xff0fffffu;
|
||||
uint t3 = 0x787ffff8u;
|
||||
uint t4 = t2 ^ t3;
|
||||
uint t5 = 0xffffffffu;
|
||||
uint t6 = t4 ^ t5;
|
||||
uint t7 = 0x00f00000u;
|
||||
uint t8 = t6 ^ t7;
|
||||
uint t9 = 0xf000ff00u;
|
||||
uint t10 = t8 ^ t9;
|
||||
uint t11 = t0 ^ t10;
|
||||
output[index] = t11;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0060: branch.uniform 0x006c taken=true
|
||||
006c: t2 = const.u32 0xffffff0f
|
||||
0070: t3 = const.u32 0x0f000000
|
||||
0074: t4 = xor.b32 t2, t3
|
||||
0078: t5 = const.u32 0x00000004
|
||||
007c: t6 = xor.b32 t4, t5
|
||||
0080: t7 = const.u32 0x0000001c
|
||||
0084: t8 = xor.b32 t6, t7
|
||||
0088: t9 = const.u32 0x00000016
|
||||
008c: t10 = xor.b32 t8, t9
|
||||
0090: t11 = const.u32 0x00000010
|
||||
0094: t12 = xor.b32 t10, t11
|
||||
0098: t13 = const.u32 0x00000018
|
||||
009c: t14 = xor.b32 t12, t13
|
||||
00a0: t15 = const.u32 0x0000000c
|
||||
00a4: t16 = xor.b32 t14, t15
|
||||
00a8: t17 = const.u32 0xfffffff0
|
||||
00ac: t18 = xor.b32 t16, t17
|
||||
00b0: t19 = const.u32 0xffff8000
|
||||
00b4: t20 = xor.b32 t18, t19
|
||||
00b8: t21 = const.u32 0x00008000
|
||||
00bc: t22 = xor.b32 t20, t21
|
||||
00c0: t23 = const.u32 0x00007fff
|
||||
00c4: t24 = xor.b32 t22, t23
|
||||
00c8: t25 = const.u32 0xffffffff
|
||||
00cc: t26 = xor.b32 t24, t25
|
||||
00d0: t27 = xor.b32 t0, t26
|
||||
00d4: store.u32 output[index], t27
|
||||
@@ -0,0 +1,35 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t2 = 0xffffff0fu;
|
||||
uint t3 = 0x0f000000u;
|
||||
uint t4 = t2 ^ t3;
|
||||
uint t5 = 0x00000004u;
|
||||
uint t6 = t4 ^ t5;
|
||||
uint t7 = 0x0000001cu;
|
||||
uint t8 = t6 ^ t7;
|
||||
uint t9 = 0x00000016u;
|
||||
uint t10 = t8 ^ t9;
|
||||
uint t11 = 0x00000010u;
|
||||
uint t12 = t10 ^ t11;
|
||||
uint t13 = 0x00000018u;
|
||||
uint t14 = t12 ^ t13;
|
||||
uint t15 = 0x0000000cu;
|
||||
uint t16 = t14 ^ t15;
|
||||
uint t17 = 0xfffffff0u;
|
||||
uint t18 = t16 ^ t17;
|
||||
uint t19 = 0xffff8000u;
|
||||
uint t20 = t18 ^ t19;
|
||||
uint t21 = 0x00008000u;
|
||||
uint t22 = t20 ^ t21;
|
||||
uint t23 = 0x00007fffu;
|
||||
uint t24 = t22 ^ t23;
|
||||
uint t25 = 0xffffffffu;
|
||||
uint t26 = t24 ^ t25;
|
||||
uint t27 = t0 ^ t26;
|
||||
output[index] = t27;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,77 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOP2 vectors for the registry-declared arithmetic, select and
|
||||
// bit-field forms: signed and unsigned min/max (including a tie, which gives S1
|
||||
// and SCC = 0), select on both SCC values, bit-field mask, low and high
|
||||
// multiplies, both bit-field extracts, absolute difference and the four
|
||||
// shift-and-add forms. BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; the
|
||||
// last SCC writer (LSHL2_ADD, no carry) clears it for the s_cbranch_scc0.
|
||||
// Values from the guide's 12.1 pseudocode, with s8 = 0x89abcdef (negative as
|
||||
// i32) and s9 = 5.
|
||||
// Expected: input ^ 0x81157dfe (the XOR of s10-s27 below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0x89abcdef
|
||||
s_mov_b32 s9, 5
|
||||
s_min_i32 s10, s8, s9 // s10 = 0x89abcdef, SCC = 1 (S0 < S1 signed)
|
||||
s_cselect_b32 s11, s9, s8 // s11 = 5 (SCC = 1 picks S0), SCC unchanged
|
||||
s_max_u32 s12, s8, s9 // s12 = 0x89abcdef, SCC = 1
|
||||
s_bfm_b32 s13, 12, 4 // s13 = 0xfff << 4 = 0xfff0, SCC unchanged
|
||||
s_lshl1_add_u32 s14, s8, s9 // (s8 << 1) + 5 = 0x1_13579be3: s14 = 0x13579be3, SCC = 1
|
||||
s_mul_i32 s15, s8, s9 // 5 * s8 = 0x2_b05b05ab: s15 = 0xb05b05ab
|
||||
s_bfe_u32 s16, s8, 0x80004 // offset 4, width 8: s16 = 0xde, SCC = 1
|
||||
s_bfe_i32 s17, s8, 0x80004 // 0xde sign-extended from bit 7: s17 = 0xffffffde, SCC = 1
|
||||
s_absdiff_i32 s18, s9, s8 // 5 - (-0x76543211) = 0x76543216: s18, SCC = 1
|
||||
s_lshl3_add_u32 s19, s8, s8 // 9 * s8 = 0x4_d70a3d67: s19 = 0xd70a3d67, SCC = 1
|
||||
s_lshl4_add_u32 s20, s9, -16 // 80 + 0xfffffff0 = 0x1_00000040: s20 = 0x40, SCC = 1
|
||||
s_mul_hi_u32 s21, s8, s8 // high word of s8 * s8 (unsigned): s21 = 0x4a0955b6
|
||||
s_mul_hi_i32 s22, s8, s8 // high word of 0x76543211^2: s22 = 0x36b1b9d8
|
||||
s_max_i32 s23, s8, s9 // s23 = 5, SCC = 0 (S0 not greater)
|
||||
s_min_u32 s24, s9, 5 // tie: s24 = 5 (S1), SCC = 0
|
||||
s_lshl2_add_u32 s25, s9, s9 // 20 + 5: s25 = 25, SCC = 0 (no carry)
|
||||
s_cselect_b32 s26, s8, s9 // s26 = 5 (SCC = 0 picks S1), SCC unchanged
|
||||
s_mul_hi_u32 s27, s9, s9 // s27 = 0, SCC unchanged (0)
|
||||
s_cbranch_scc0 .Lzero
|
||||
v_mov_b32_e32 v2, 0
|
||||
s_branch .Ldone
|
||||
.Lzero:
|
||||
v_mov_b32_e32 v2, s10
|
||||
v_mov_b32_e32 v3, s11
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s12
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s13
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s14
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s15
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s16
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s17
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s18
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s19
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s20
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s21
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s22
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s23
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s24
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s25
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s26
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s27
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x81157dfe
|
||||
.Ldone:
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOPC vectors: each of the twelve 32-bit integer compares sets SCC,
|
||||
// and an s_cbranch_scc0 skips setting that compare's bit in s20, so s20
|
||||
// records every result. -1 and 1 separate signed from unsigned ordering;
|
||||
// inline and literal operands appear in the second position.
|
||||
// Expected: input ^ 0x00000d5b (bits worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, -1
|
||||
s_mov_b32 s9, 1
|
||||
s_mov_b32 s20, 0
|
||||
s_cmp_eq_i32 s8, -1 // -1 == -1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip0
|
||||
s_or_b32 s20, s20, 1
|
||||
.Lskip0:
|
||||
s_cmp_lg_i32 s8, s9 // -1 != 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip1
|
||||
s_or_b32 s20, s20, 2
|
||||
.Lskip1:
|
||||
s_cmp_gt_i32 s8, s9 // -1 > 1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip2
|
||||
s_or_b32 s20, s20, 4
|
||||
.Lskip2:
|
||||
s_cmp_ge_i32 s9, s9 // 1 >= 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip3
|
||||
s_or_b32 s20, s20, 8
|
||||
.Lskip3:
|
||||
s_cmp_lt_i32 s8, s9 // -1 < 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip4
|
||||
s_or_b32 s20, s20, 16
|
||||
.Lskip4:
|
||||
s_cmp_le_i32 s9, s8 // 1 <= -1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip5
|
||||
s_or_b32 s20, s20, 32
|
||||
.Lskip5:
|
||||
s_cmp_eq_u32 s9, 1 // 1 == 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip6
|
||||
s_or_b32 s20, s20, 64
|
||||
.Lskip6:
|
||||
s_mov_b32 s10, 0x89abcdef
|
||||
s_cmp_lg_u32 s10, 0x89abcdef // 0x89abcdef != 0x89abcdef: SCC = 0 (literal)
|
||||
s_cbranch_scc0 .Lskip7
|
||||
s_or_b32 s20, s20, 0x80
|
||||
.Lskip7:
|
||||
s_cmp_gt_u32 s8, s9 // 0xffffffff > 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip8
|
||||
s_or_b32 s20, s20, 0x100
|
||||
.Lskip8:
|
||||
s_cmp_ge_u32 s9, s8 // 1 >= 0xffffffff: SCC = 0
|
||||
s_cbranch_scc0 .Lskip9
|
||||
s_or_b32 s20, s20, 0x200
|
||||
.Lskip9:
|
||||
s_cmp_lt_u32 s9, s8 // 1 < 0xffffffff: SCC = 1
|
||||
s_cbranch_scc0 .Lskip10
|
||||
s_or_b32 s20, s20, 0x400
|
||||
.Lskip10:
|
||||
s_cmp_le_u32 s9, 64 // 1 <= 64: SCC = 1
|
||||
s_cbranch_scc0 .Lskip11
|
||||
s_or_b32 s20, s20, 0x800
|
||||
.Lskip11:
|
||||
v_mov_b32_e32 v2, s20
|
||||
v_xor_b32_e32 v2, v1, v2 // s20 = 0x00000d5b
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,38 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOP2 vectors for the registry-declared logical and shift forms:
|
||||
// ANDN2/ORN2 with a literal and an inline -1, NAND with aliased sources,
|
||||
// NOR/XNOR chains, shift counts that use only S1[4:0] (36 -> 4, a literal
|
||||
// 0xffffffe1 -> 1, 31), an arithmetic shift of a negative and a positive value,
|
||||
// and an SCC branch on a zero shift result. SGPR results are moved into VGPRs.
|
||||
// Expected: input ^ 0x887f00f8 (worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0xf0f0ff00
|
||||
s_andn2_b32 s9, s8, 0xff00ff00 // s9 = 0x00f00000, SCC = 1
|
||||
s_orn2_b32 s10, s9, -1 // s10 = 0x00f00000, SCC = 1
|
||||
s_nand_b32 s11, s8, s8 // s11 = 0x0f0f00ff, SCC = 1
|
||||
s_nor_b32 s12, s11, s9 // s12 = 0xf000ff00, SCC = 1
|
||||
s_xnor_b32 s13, s12, s8 // s13 = 0xff0fffff, SCC = 1
|
||||
s_lshl_b32 s14, s13, 36 // s14 = 0xf0fffff0 (count 4), SCC = 1
|
||||
s_lshr_b32 s15, s14, 0xffffffe1 // s15 = 0x787ffff8 (count 1), SCC = 1
|
||||
s_ashr_i32 s16, s14, 31 // s16 = 0xffffffff, SCC = 1
|
||||
s_ashr_i32 s17, s15, 31 // s17 = 0, SCC = 0
|
||||
s_cbranch_scc0 .Lzero
|
||||
v_mov_b32_e32 v2, 0
|
||||
s_branch .Ldone
|
||||
.Lzero:
|
||||
v_mov_b32_e32 v2, s13
|
||||
v_mov_b32_e32 v3, s15
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v4, s16
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_mov_b32_e32 v5, s10
|
||||
v_xor_b32_e32 v2, v2, v5
|
||||
v_mov_b32_e32 v6, s12
|
||||
v_xor_b32_e32 v2, v2, v6 // 0xff0fffff ^ 0x787ffff8 ^ 0xffffffff ^ 0x00f00000 ^ 0xf000ff00
|
||||
v_xor_b32_e32 v2, v1, v2
|
||||
.Ldone:
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOP1 vectors for the registry-declared unary forms: complement, bit
|
||||
// reverse, both bit counts, both find-first searches (one finding nothing, which
|
||||
// gives -1), both find-last-bit forms, sign extension from 8 and 16 bits, and
|
||||
// absolute value. SCC is set by NOT/BCNT/ABS only: an ABS of zero clears it, and
|
||||
// the following SEXT and FF1 leave it clear for the s_cbranch_scc0.
|
||||
// Expected: input ^ 0x0f0080f5 (worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0xf0
|
||||
s_not_b32 s9, s8 // s9 = 0xffffff0f, SCC = 1
|
||||
s_brev_b32 s10, s8 // s10 = 0x0f000000
|
||||
s_bcnt1_i32_b32 s11, s8 // s11 = 4, SCC = 1
|
||||
s_bcnt0_i32_b32 s12, s8 // s12 = 28, SCC = 1
|
||||
s_ff1_i32_b32 s13, 0x400000 // s13 = 22
|
||||
s_ff0_i32_b32 s14, 0xffff // s14 = 16
|
||||
s_flbit_i32_b32 s15, s8 // s15 = 24
|
||||
s_flbit_i32 s16, 0xfff00000 // s16 = 12 (bits equal to the sign above bit 19)
|
||||
s_sext_i32_i8 s17, s8 // s17 = 0xfffffff0
|
||||
s_sext_i32_i16 s18, 0x18000 // s18 = 0xffff8000
|
||||
s_abs_i32 s19, s18 // s19 = 0x8000, SCC = 1
|
||||
s_abs_i32 s20, 0 // s20 = 0, SCC = 0
|
||||
s_sext_i32_i16 s21, 0x7fff // s21 = 0x7fff, SCC unchanged (0)
|
||||
s_ff1_i32_b32 s22, 0 // s22 = 0xffffffff (none found), SCC unchanged (0)
|
||||
s_cbranch_scc0 .Lzero
|
||||
v_mov_b32_e32 v2, 0
|
||||
s_branch .Ldone
|
||||
.Lzero:
|
||||
v_mov_b32_e32 v2, s9
|
||||
v_mov_b32_e32 v3, s10
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s11
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s12
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s13
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s14
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s15
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s16
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s17
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s18
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s19
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s21
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s22
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x0f0080f5
|
||||
.Ldone:
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
@@ -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; 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; 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"
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Generate the gfx1030 semantic coverage report from the checked-in inventories."""
|
||||
|
||||
import argparse
|
||||
from collections import Counter, defaultdict
|
||||
import difflib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import runpy
|
||||
import sys
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
|
||||
sys.exit("semantic_coverage.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = Path("crates/isa/data/rdna2.jsonl")
|
||||
REGISTRY = Path("crates/isa/semantics/rdna2.toml")
|
||||
DECODER = Path("crates/decoder/src/lib.rs")
|
||||
GENERATED = Path("crates/isa/src/semantics_gen.rs")
|
||||
STATUS = Path("docs/status.toml")
|
||||
REPORT = Path("docs/shaders/semantic-coverage.md")
|
||||
|
||||
DECODER_HEADER = re.compile(
|
||||
r'const HANDWRITTEN_FORMS: \[\(&str, EncodingFamily\); (\d+)\] = \['
|
||||
)
|
||||
# The decoder's full list is its hand-written forms plus every registry form.
|
||||
DECODER_TOTAL = re.compile(
|
||||
r'pub const SEMANTIC_FORMS: \[\(&str, EncodingFamily\); '
|
||||
r'HANDWRITTEN_FORMS\.len\(\) \+ FORM_IDS\.len\(\)\] ='
|
||||
)
|
||||
DECODER_ENTRY = re.compile(r'\("([A-Z0-9_]+)", EncodingFamily::([A-Za-z0-9]+)\),')
|
||||
STATUS_ALIASES = {
|
||||
"s_waitcnt vmcnt(0)": ("SOPP", "S_WAITCNT"),
|
||||
"s_waitcnt_vscnt null, 0": ("SOPK", "S_WAITCNT_VSCNT"),
|
||||
}
|
||||
COLUMNS = (
|
||||
"Identified", "Encoding-validated", "Declared", "Decoder-supported",
|
||||
"IR", "MSL", "Reference-verified", "Metal-verified", "Unsupported operand variants",
|
||||
)
|
||||
|
||||
|
||||
def load_snapshot(root):
|
||||
# Reuse the metadata generator's base-form rules, including literal-only
|
||||
# forms and the relative moves whose base condition is not "default".
|
||||
metadata = runpy.run_path(str(root / "crates/isa/generate_rdna2_meta.py"))
|
||||
encodings = metadata["BASE_ENCODINGS"] | metadata["EXTENSIONS"]
|
||||
snapshot = (root / SNAPSHOT).read_text(encoding="utf-8")
|
||||
variants = []
|
||||
for number, line in enumerate(snapshot.splitlines(), 1):
|
||||
location = f"{SNAPSHOT}:{number}"
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"{location}: {error}") from error
|
||||
if not isinstance(row, dict):
|
||||
raise ValueError(f"{location}: expected an object")
|
||||
kind = row.get("kind")
|
||||
if kind == "variant":
|
||||
if (
|
||||
not isinstance(row.get("encoding"), str) or row["encoding"] not in encodings
|
||||
or any(not isinstance(row.get(key), str) or not row[key]
|
||||
for key in ("instruction", "condition"))
|
||||
or type(row.get("opcode")) is not int
|
||||
):
|
||||
raise ValueError(f"{location}: invalid variant {row!r}")
|
||||
variants.append((location, row))
|
||||
elif kind not in ("source", "encoding", "operand_type", "data_format"):
|
||||
raise ValueError(f"{location}: unknown row kind {kind!r}")
|
||||
try:
|
||||
_, _, forms = metadata["forms_from_snapshot"](snapshot)
|
||||
except (SystemExit, ValueError, KeyError, IndexError, TypeError) as error:
|
||||
raise ValueError(f"{SNAPSHOT}: {error}") from error
|
||||
identified = {(form["encoding"].upper(), form["name"]): form["opcode"] for form in forms}
|
||||
if not identified or len(identified) != len(forms):
|
||||
raise ValueError(f"{SNAPSHOT}: expected unique, nonempty base forms")
|
||||
for location, row in variants:
|
||||
encoding = row["encoding"]
|
||||
base, _ = metadata["EXTENSIONS"].get(encoding, (encoding, None))
|
||||
key = (metadata["BASE_ENCODINGS"][base].upper(), row["instruction"])
|
||||
if key not in identified:
|
||||
raise ValueError(f"{location}: cannot map {encoding} variant to base form {key}")
|
||||
return identified
|
||||
|
||||
|
||||
def parse_decoder(source):
|
||||
lines = source.splitlines()
|
||||
if sum(bool(DECODER_TOTAL.fullmatch(line.strip())) for line in lines) != 1:
|
||||
raise ValueError(f"{DECODER}: expected SEMANTIC_FORMS = hand-written + registry forms")
|
||||
starts = [i for i, line in enumerate(lines)
|
||||
if re.match(r"\s*const HANDWRITTEN_FORMS\b", line)]
|
||||
if len(starts) != 1:
|
||||
raise ValueError(f"{DECODER}: expected one HANDWRITTEN_FORMS declaration")
|
||||
start = starts[0]
|
||||
header = DECODER_HEADER.fullmatch(lines[start].strip())
|
||||
if not header:
|
||||
raise ValueError(f"{DECODER}:{start + 1}: unrecognized SEMANTIC_FORMS declaration")
|
||||
|
||||
forms = set()
|
||||
for number, line in enumerate(lines[start + 1:], start + 2):
|
||||
line = line.partition("//")[0].strip()
|
||||
if line == "];":
|
||||
if len(forms) != int(header[1]):
|
||||
raise ValueError(f"{DECODER}:{number}: SEMANTIC_FORMS length mismatch")
|
||||
return forms
|
||||
if not line:
|
||||
continue
|
||||
entry = DECODER_ENTRY.fullmatch(line)
|
||||
if not entry:
|
||||
raise ValueError(f"{DECODER}:{number}: unrecognized SEMANTIC_FORMS entry {line!r}")
|
||||
key = (entry[2].upper(), entry[1])
|
||||
if key in forms:
|
||||
raise ValueError(f"{DECODER}:{number}: duplicate form {key}")
|
||||
forms.add(key)
|
||||
raise ValueError(f"{DECODER}: unterminated SEMANTIC_FORMS")
|
||||
|
||||
|
||||
GENERATED_HEADER = re.compile(r"pub const FORM_IDS: \[\(&str, EncodingFamily\); (\d+)\] = \[")
|
||||
|
||||
|
||||
def parse_generated(source):
|
||||
"""Registry forms compiled into the decoder, read from the generated FORM_IDS table."""
|
||||
lines = source.splitlines()
|
||||
starts = [i for i, line in enumerate(lines) if GENERATED_HEADER.fullmatch(line.strip())]
|
||||
if len(starts) != 1:
|
||||
raise ValueError(f"{GENERATED}: expected one FORM_IDS declaration")
|
||||
forms = set()
|
||||
rows = 0
|
||||
for number, line in enumerate(lines[starts[0] + 1:], starts[0] + 2):
|
||||
line = line.strip()
|
||||
if line == "];":
|
||||
if rows != len(forms):
|
||||
raise ValueError(f"{GENERATED}:{number}: duplicate FORM_IDS entry")
|
||||
if len(forms) != int(GENERATED_HEADER.fullmatch(lines[starts[0]].strip())[1]):
|
||||
raise ValueError(f"{GENERATED}:{number}: FORM_IDS length mismatch")
|
||||
return forms
|
||||
entry = DECODER_ENTRY.fullmatch(line)
|
||||
if not entry:
|
||||
raise ValueError(f"{GENERATED}:{number}: unrecognized FORM_IDS entry {line!r}")
|
||||
forms.add((entry[2].upper(), entry[1]))
|
||||
rows += 1
|
||||
raise ValueError(f"{GENERATED}: unterminated FORM_IDS")
|
||||
|
||||
|
||||
def read_declarations(registry, identified):
|
||||
if type(registry.get("schema")) is not int or registry["schema"] != 1:
|
||||
raise ValueError(f"{REGISTRY}: expected schema 1")
|
||||
families = {family for family, _ in identified}
|
||||
rules = {}
|
||||
for name, rule in registry["operand_rules"].items():
|
||||
location = f"{REGISTRY}: operand_rules.{name}"
|
||||
family = rule["family"]
|
||||
unsupported = rule["unsupported"]
|
||||
if family not in families:
|
||||
raise ValueError(f"{location}: unknown family {family!r}")
|
||||
if not isinstance(unsupported, list) or any(
|
||||
not isinstance(variant, str) or not re.fullmatch(r"[a-zA-Z0-9_]+", variant)
|
||||
for variant in unsupported
|
||||
):
|
||||
raise ValueError(f"{location}: invalid unsupported list")
|
||||
rules[name] = (family, set(unsupported))
|
||||
|
||||
declared = set()
|
||||
for form in registry["form"]:
|
||||
key = (form["family"], form["name"])
|
||||
if key not in identified:
|
||||
raise ValueError(f"{REGISTRY}: unknown form {key}")
|
||||
if type(form["opcode"]) is not int or form["opcode"] != identified[key]:
|
||||
raise ValueError(f"{REGISTRY}: opcode mismatch for {key}")
|
||||
if key in declared:
|
||||
raise ValueError(f"{REGISTRY}: duplicate form {key}")
|
||||
rule = form["operands"]
|
||||
if rule not in rules or rules[rule][0] != key[0]:
|
||||
raise ValueError(f"{REGISTRY}: invalid operand rule {rule!r} for {key}")
|
||||
declared.add(key)
|
||||
return declared, rules
|
||||
|
||||
|
||||
def status_form(row, identified):
|
||||
name = row["form"]
|
||||
if not isinstance(name, str) or not isinstance(row["encoding"], str):
|
||||
raise ValueError(f"{STATUS}: invalid form or encoding in {row!r}")
|
||||
families = {family for family, _ in identified}
|
||||
family_hint = row["encoding"].split(",", 1)[0].strip().upper()
|
||||
if name in STATUS_ALIASES:
|
||||
candidates = [STATUS_ALIASES[name]]
|
||||
else:
|
||||
mnemonic = name.upper()
|
||||
eligible = families
|
||||
if mnemonic.endswith("_E32"):
|
||||
mnemonic = mnemonic.removesuffix("_E32")
|
||||
eligible = families & {"VOP1", "VOP2", "VOPC"}
|
||||
elif mnemonic.endswith("_E64"):
|
||||
mnemonic = mnemonic.removesuffix("_E64")
|
||||
eligible = families & {"VOP3", "VOP3SDST"}
|
||||
candidates = sorted((family, mnemonic) for family in eligible
|
||||
if (family, mnemonic) in identified)
|
||||
if family_hint in families:
|
||||
candidates = [key for key in candidates if key[0] == family_hint]
|
||||
if len(candidates) != 1 or candidates[0] not in identified:
|
||||
raise ValueError(f"{STATUS}: cannot uniquely map {name!r} ({candidates})")
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def collect_coverage(identified, registry, decoder, status):
|
||||
declared, rules = read_declarations(registry, identified)
|
||||
unknown = decoder.difference(identified)
|
||||
if unknown:
|
||||
raise ValueError(f"{DECODER}: unknown forms {sorted(unknown)}")
|
||||
|
||||
encoded, lowered, reference, metal = set(), set(), set(), set()
|
||||
seen = set()
|
||||
for row in status["instruction"]:
|
||||
key = status_form(row, identified)
|
||||
if key in seen:
|
||||
raise ValueError(f"{STATUS}: duplicate evidence for {key}")
|
||||
seen.add(key)
|
||||
for field in ("llvm", "lowering", "reference", "cpu", "gpu"):
|
||||
if field in row and not isinstance(row[field], str):
|
||||
raise ValueError(f"{STATUS}: {key} has invalid {field} evidence")
|
||||
if row.get("llvm") == "three-way passed":
|
||||
encoded.add(key)
|
||||
lowering = row.get("lowering", "").strip().lower()
|
||||
# This status schema uses one field for the IR-to-MSL path. A
|
||||
# compile-time resolution also implements that path for the form.
|
||||
if (
|
||||
lowering.startswith(("msl ", "resolved ", "verified ", "constant or ", "per-thread "))
|
||||
and not re.search(r"\b(?:stub|placeholder|planned|unsupported|pending|todo|unimplemented|not implemented|not yet)\b", lowering)
|
||||
):
|
||||
lowered.add(key)
|
||||
elif lowering:
|
||||
raise ValueError(f"{STATUS}: {key} has unrecognized lowering {row['lowering']!r}")
|
||||
# Verified evidence also requires the status row to say the form decodes.
|
||||
decodes = row.get("decoded") is True
|
||||
if decodes and row.get("reference") == "implemented" and row.get("cpu") == "fixture verified":
|
||||
reference.add(key)
|
||||
if decodes and row.get("gpu") in {"fixture verified", "fixture verified on Apple M5"}:
|
||||
metal.add(key)
|
||||
|
||||
counts = [Counter(family for family, _ in forms) for forms in (
|
||||
identified, encoded, declared, decoder, lowered, lowered, reference, metal,
|
||||
)]
|
||||
unsupported = defaultdict(set)
|
||||
for family, variants in rules.values():
|
||||
unsupported[family].update(variants)
|
||||
return {
|
||||
family: (*[count[family] for count in counts], len(unsupported[family]))
|
||||
for family in sorted(counts[0])
|
||||
}, rules
|
||||
|
||||
|
||||
def render_report(counts, rules):
|
||||
lines = [
|
||||
"# gfx1030 semantic coverage",
|
||||
"",
|
||||
"<!-- Generated by scripts/audit/semantic_coverage.py. -->",
|
||||
"",
|
||||
"Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms",
|
||||
"come from the semantic registry. Decoder support is the decoder's hand-written",
|
||||
"list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.",
|
||||
"",
|
||||
"The status inventory records LLVM three-way encoding checks, intermediate",
|
||||
"representation (IR) and Metal Shading Language (MSL) lowering, and fixture",
|
||||
"verification. IR and MSL share the inventory's lowering field. Reference",
|
||||
"verification requires an implemented reference and verified CPU fixture.",
|
||||
"Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending",
|
||||
"acceptance remain outside the verified count. All results concern synthetic fixtures.",
|
||||
"",
|
||||
"| Family | " + " | ".join(COLUMNS) + " |",
|
||||
"| --- |" + " ---: |" * len(COLUMNS),
|
||||
]
|
||||
for family, values in counts.items():
|
||||
lines.append(f"| {family} | " + " | ".join(map(str, values)) + " |")
|
||||
lines.append("| **Total** | " + " | ".join(map(str, map(sum, zip(*counts.values())))) + " |")
|
||||
lines.extend([
|
||||
"",
|
||||
"## Unsupported operand variants",
|
||||
"",
|
||||
"The table counts distinct variant names per family across registry operand rules.",
|
||||
"",
|
||||
"| Family | Operand rule | Unsupported variants |",
|
||||
"| --- | --- | --- |",
|
||||
])
|
||||
for family, name, variants in sorted((family, name, variants)
|
||||
for name, (family, variants) in rules.items()):
|
||||
names = ", ".join(f"`{variant}`" for variant in sorted(variants))
|
||||
lines.append(f"| {family} | `{name}` | {names or 'None listed'} |")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true", help="compare without writing")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
identified = load_snapshot(ROOT)
|
||||
registry = tomllib.loads((ROOT / REGISTRY).read_text(encoding="utf-8"))
|
||||
decoder = parse_decoder((ROOT / DECODER).read_text(encoding="utf-8")) | parse_generated(
|
||||
(ROOT / GENERATED).read_text(encoding="utf-8"))
|
||||
status = tomllib.loads((ROOT / STATUS).read_text(encoding="utf-8"))
|
||||
report = render_report(*collect_coverage(identified, registry, decoder, status)).encode()
|
||||
path = ROOT / REPORT
|
||||
if not args.check:
|
||||
path.write_bytes(report)
|
||||
print(f"Wrote {REPORT}")
|
||||
return 0
|
||||
committed = path.read_bytes() if path.exists() else b""
|
||||
if committed == report:
|
||||
print(f"{REPORT} is up to date")
|
||||
return 0
|
||||
before = committed.decode("utf-8", errors="replace").splitlines(keepends=True)
|
||||
after = report.decode().splitlines(keepends=True)
|
||||
diff = list(difflib.unified_diff(before, after, fromfile=str(REPORT),
|
||||
tofile="regenerated", n=0))
|
||||
print(f"{REPORT} differs from the regenerated report", file=sys.stderr)
|
||||
for line in diff[:12]:
|
||||
print(line.rstrip("\n"), file=sys.stderr)
|
||||
if len(diff) > 12:
|
||||
print("…", file=sys.stderr)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
print(f"semantic_coverage: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check.
|
||||
# Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
root=$(pwd)
|
||||
|
||||
fail() { echo "build-app: $*" >&2; exit 1; }
|
||||
[ "$(uname -s)" = Darwin ] || fail "macOS is required"
|
||||
[ "$(uname -m)" = arm64 ] || fail "a native arm64 host is required"
|
||||
[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 0 ] || fail "running under Rosetta is not supported"
|
||||
command -v cargo >/dev/null || fail "cargo not found; install Rust 1.100"
|
||||
command -v swift >/dev/null || fail "swift not found; install the Xcode command line tools"
|
||||
|
||||
target=aarch64-apple-darwin
|
||||
# Match the app's LSMinimumSystemVersion so the static library links cleanly.
|
||||
MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --target "$target"
|
||||
swift build --package-path app -c release --arch arm64 \
|
||||
-Xlinker -L -Xlinker "$root/target/$target/release"
|
||||
|
||||
bundle="$root/build/Xenora.app"
|
||||
rm -rf "$bundle"
|
||||
mkdir -p "$bundle/Contents/MacOS"
|
||||
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora"
|
||||
cat > "$bundle/Contents/Info.plist" <<PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key><string>Xenora</string>
|
||||
<key>CFBundleIdentifier</key><string>local.xenora.Xenora</string>
|
||||
<key>CFBundleName</key><string>Xenora</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key><string>0.1.0</string>
|
||||
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
||||
<key>NSHighResolutionCapable</key><true/>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeName</key><string>Windows Executable</string>
|
||||
<key>CFBundleTypeRole</key><string>Viewer</string>
|
||||
<key>LSHandlerRank</key><string>Alternate</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array><string>com.microsoft.windows-executable</string></array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
# Ad-hoc signature for local development only. No entitlements are requested:
|
||||
# this build executes no guest code, so it needs no JIT entitlement.
|
||||
codesign --force --sign - "$bundle"
|
||||
|
||||
binary="$bundle/Contents/MacOS/Xenora"
|
||||
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
|
||||
"$binary" --smoke
|
||||
echo "build-app: built $bundle"
|
||||
@@ -25,6 +25,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
|
||||
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# The native app interface runs the trusted fixture's guest draw on Metal.
|
||||
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
|
||||
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
|
||||
# and VOPC compares.
|
||||
cargo test --locked -p xenora-semantic-review --no-run
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import unittest
|
||||
|
||||
from audit import semantic_coverage as coverage
|
||||
|
||||
|
||||
class SemanticCoverageTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.identified = {("SOP2", "S_ADD_U32"): 0, ("SOP2", "S_SUB_U32"): 1}
|
||||
self.registry = {
|
||||
"schema": 1,
|
||||
"form": [{
|
||||
"family": "SOP2", "name": "S_ADD_U32", "opcode": 0,
|
||||
"operands": "scalar", "verify": ["metal", "reference", "llvm_encoding"],
|
||||
}],
|
||||
"operand_rules": {
|
||||
"scalar": {"family": "SOP2", "unsupported": ["two_literals"]},
|
||||
},
|
||||
}
|
||||
|
||||
def counts(self, *rows):
|
||||
counts, _ = coverage.collect_coverage(
|
||||
self.identified, self.registry, {("SOP2", "S_SUB_U32")},
|
||||
{"instruction": list(rows)},
|
||||
)
|
||||
return dict(zip(coverage.COLUMNS, counts["SOP2"]))
|
||||
|
||||
def test_declared_without_metal_evidence_is_not_metal_verified(self):
|
||||
counts = self.counts()
|
||||
self.assertEqual(counts["Declared"], 1)
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["Encoding-validated"], 0)
|
||||
|
||||
def test_status_evidence_counts_for_handwritten_form(self):
|
||||
counts = self.counts({
|
||||
"form": "s_sub_u32", "encoding": "SOP2, scalar operands",
|
||||
"llvm": "three-way passed", "lowering": "resolved scalar state and SCC",
|
||||
"reference": "implemented", "cpu": "fixture verified",
|
||||
"gpu": "fixture verified on Apple M5", "decoded": True,
|
||||
})
|
||||
self.assertEqual(counts, {
|
||||
"Identified": 2, "Encoding-validated": 1, "Declared": 1,
|
||||
"Decoder-supported": 1, "IR": 1, "MSL": 1, "Reference-verified": 1,
|
||||
"Metal-verified": 1, "Unsupported operand variants": 1,
|
||||
})
|
||||
|
||||
def test_pending_readback_does_not_count(self):
|
||||
counts = self.counts({
|
||||
"form": "s_add_u32", "encoding": "SOP2", "lowering": "resolved scalar state and SCC",
|
||||
"reference": "implemented", "cpu": "local known-answer test passed",
|
||||
"gpu": "local Apple M5 readback passed; acceptance pending",
|
||||
})
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["IR"], 1)
|
||||
|
||||
def test_verified_evidence_needs_a_decoding_row(self):
|
||||
counts = self.counts({
|
||||
"form": "s_sub_u32", "encoding": "SOP2", "reference": "implemented",
|
||||
"cpu": "fixture verified", "gpu": "fixture verified", "decoded": False,
|
||||
})
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
|
||||
def test_declared_but_not_compiled_is_not_decoder_supported(self):
|
||||
# S_ADD_U32 is declared in the registry but absent from the compiled tables.
|
||||
self.assertEqual(self.counts()["Decoder-supported"], 1)
|
||||
|
||||
def test_generated_table_parser(self):
|
||||
source = (
|
||||
"pub const FORM_IDS: [(&str, EncodingFamily); 1] = [\n"
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n];'
|
||||
)
|
||||
self.assertEqual(coverage.parse_generated(source), {("SOP2", "S_ADD_U32")})
|
||||
with self.assertRaisesRegex(ValueError, "length mismatch"):
|
||||
coverage.parse_generated(source.replace("; 1]", "; 2]"))
|
||||
duplicated = source.replace("; 1]", "; 2]").replace(
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n',
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n' * 2,
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "duplicate FORM_IDS entry"):
|
||||
coverage.parse_generated(duplicated)
|
||||
|
||||
def test_stub_or_unrecognized_lowering_fails(self):
|
||||
for lowering in ("stub", "MSL placeholder add", "MSL unimplemented", "something new"):
|
||||
with self.assertRaisesRegex(ValueError, "unrecognized lowering"):
|
||||
self.counts({"form": "s_add_u32", "encoding": "SOP2", "lowering": lowering})
|
||||
|
||||
def test_status_suffix_disambiguates_encoding(self):
|
||||
forms = {("VOP2", "V_AND_B32"): 1, ("VOP3", "V_AND_B32"): 2}
|
||||
self.assertEqual(coverage.status_form(
|
||||
{"form": "v_and_b32_e32", "encoding": "Two VGPR sources"}, forms,
|
||||
), ("VOP2", "V_AND_B32"))
|
||||
with self.assertRaisesRegex(ValueError, "cannot uniquely map"):
|
||||
coverage.status_form(
|
||||
{"form": "v_and_b32", "encoding": "Two VGPR sources"}, forms,
|
||||
)
|
||||
|
||||
def test_unknown_status_form_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, "cannot uniquely map.*s_typo"):
|
||||
self.counts({"form": "s_typo", "encoding": "SOP2"})
|
||||
|
||||
def test_decoder_parser_rejects_unrecognized_entry(self):
|
||||
header = (
|
||||
"pub const SEMANTIC_FORMS: [(&str, EncodingFamily); "
|
||||
"HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =\n"
|
||||
"const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 1] = ["
|
||||
)
|
||||
self.assertEqual(coverage.parse_decoder(
|
||||
f'{header}\n ("S_ADD_U32", EncodingFamily::Sop2),\n];',
|
||||
), {("SOP2", "S_ADD_U32")})
|
||||
with self.assertRaisesRegex(ValueError, "unrecognized SEMANTIC_FORMS entry"):
|
||||
coverage.parse_decoder(f"{header}\n unknown!(),\n];")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,830 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Unit tests for crates/isa/generate_semantics.py.
|
||||
|
||||
Each rejection rule is fed a small in-memory registry that breaks exactly that
|
||||
rule, checked against a tiny hand-written XML snapshot. The real registry and
|
||||
snapshot are only read, never edited. Run from the repository root:
|
||||
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
"""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "crates/isa/generate_semantics.py"
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("generate_semantics", SCRIPT)
|
||||
gen = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(gen)
|
||||
|
||||
SHA = "0" * 64
|
||||
|
||||
# Minimal stand-in for crates/isa/data/rdna2.jsonl: the SOP2 encoding and the
|
||||
# default variants of the four forms the fixture declares (values copied from
|
||||
# the AMD XML snapshot).
|
||||
U32 = "FMT_NUM_U32"
|
||||
I32 = "FMT_NUM_I32"
|
||||
|
||||
|
||||
def _operands(data_format, scc_in=False, src1_format=None, scc_out=True):
|
||||
rows = [
|
||||
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
|
||||
["SSRC0", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
|
||||
["SSRC1", src1_format or data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
|
||||
]
|
||||
if scc_out:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True])
|
||||
if scc_in:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, True, False, True, True])
|
||||
return rows
|
||||
|
||||
|
||||
def snapshot():
|
||||
sop2_base = 0x80000000
|
||||
encoding = {
|
||||
"name": "ENC_SOP2",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["SDST", [[16, 7]]],
|
||||
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
|
||||
],
|
||||
"identifier_mask": 0xFF800000,
|
||||
"identifiers": [
|
||||
sop2_base | (op << 23) for op in (0, 2, 4, 6, 10, 14, 34, 38, 40, 47, 53)
|
||||
],
|
||||
}
|
||||
variants = {}
|
||||
for name, opcode, operands in (
|
||||
("S_ADD_U32", 0, _operands(U32)),
|
||||
("S_ADD_I32", 2, _operands(I32)),
|
||||
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
|
||||
("S_AND_B32", 14, _operands(U32)),
|
||||
# The XML gives S_ASHR_I32 a signed S0 and an unsigned shift count.
|
||||
("S_ASHR_I32", 34, _operands(I32, src1_format=U32)),
|
||||
# Values copied from the AMD XML snapshot for the arithmetic fixture.
|
||||
("S_MIN_I32", 6, _operands(I32)),
|
||||
("S_CSELECT_B32", 10, _operands("FMT_NUM_B32", scc_in=True, scc_out=False)),
|
||||
("S_MUL_I32", 38, _operands(I32, scc_out=False)),
|
||||
("S_BFE_I32", 40, _operands(I32, src1_format=U32)),
|
||||
("S_LSHL2_ADD_U32", 47, _operands(U32)),
|
||||
("S_MUL_HI_U32", 53, _operands(U32, scc_out=False)),
|
||||
):
|
||||
variants[(name, "ENC_SOP2")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
sopc = {
|
||||
"name": "ENC_SOPC",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["OP", [[16, 7]]], ["ENCODING", [[23, 9]]],
|
||||
],
|
||||
"identifier_mask": 0xFFFF0000,
|
||||
"identifiers": [0xBF000000 | (op << 16) for op in (4, 10)],
|
||||
}
|
||||
for name, opcode, data_format in (("S_CMP_LT_I32", 4, I32), ("S_CMP_LT_U32", 10, U32)):
|
||||
variants[(name, "ENC_SOPC")] = {
|
||||
"instruction": name, "encoding": "ENC_SOPC", "opcode": opcode,
|
||||
"operands": _operands(data_format)[1:],
|
||||
}
|
||||
sop1 = {
|
||||
"name": "ENC_SOP1",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["OP", [[8, 8]]], ["SDST", [[16, 7]]], ["ENCODING", [[23, 9]]],
|
||||
],
|
||||
"identifier_mask": 0xFF80FF00,
|
||||
"identifiers": [0xBE800000 | (op << 8) for op in (7, 11, 25)],
|
||||
}
|
||||
|
||||
def unary(dst, src, size, scc):
|
||||
rows = [
|
||||
["SDST", dst, "OPR_SDST", 32, False, True, False, True],
|
||||
["SSRC0", src, "OPR_SSRC_NOLDS", size, True, False, False, True],
|
||||
]
|
||||
if scc:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True])
|
||||
return rows
|
||||
|
||||
for name, opcode, operands in (
|
||||
("S_NOT_B32", 7, unary(U32, U32, 32, True)),
|
||||
("S_BREV_B32", 11, unary(U32, U32, 32, False)),
|
||||
("S_SEXT_I32_I8", 25, unary(I32, "FMT_NUM_I8", 8, False)),
|
||||
):
|
||||
variants[(name, "ENC_SOP1")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP1", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
return {
|
||||
"source": {"sha256": SHA},
|
||||
"encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1},
|
||||
"variants": variants,
|
||||
}
|
||||
|
||||
|
||||
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
|
||||
return {
|
||||
"name": name, "family": "SOP2", "opcode": opcode, "variant": variant,
|
||||
"operation": operation, "signedness": signedness, "carry_in": carry_in,
|
||||
"width": 32, "scc": scc, "vcc": "unchanged", "exec": "unchanged", "wave": "any",
|
||||
"operands": "sop2_sgpr",
|
||||
"spec": [{"document": "guide", "section": "12.1", "page": 101}],
|
||||
"verify": ["reference", "independent"],
|
||||
}
|
||||
|
||||
|
||||
def unaries():
|
||||
reg = registry()
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop1_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.OPERAND_RULES["sop1_sgpr"]["unsupported"])
|
||||
reg["operand_rules"]["sop1_sgpr"] = rule
|
||||
|
||||
def unary(name, opcode, variant, operation, signedness, scc, **extra):
|
||||
form = _form(name, opcode, variant, operation, signedness, scc)
|
||||
form.update(family="SOP1", operands="sop1_sgpr", **extra)
|
||||
return form
|
||||
|
||||
reg["form"] += [
|
||||
unary("S_NOT_B32", 7, "NotB32", "not", "bitwise", "nonzero"),
|
||||
unary("S_BREV_B32", 11, "BrevB32", "brev", "bitwise", "unchanged"),
|
||||
unary("S_SEXT_I32_I8", 25, "SextI32I8", "sext", "signed", "unchanged", source_bits=8),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def ariths():
|
||||
reg = registry()
|
||||
reg["form"] += [
|
||||
_form("S_MIN_I32", 6, "MinI32", "min", "signed", "selected_src0"),
|
||||
_form("S_CSELECT_B32", 10, "CselectB32", "cselect", "bitwise", "unchanged", carry_in="scc"),
|
||||
_form("S_MUL_I32", 38, "MulI32", "mul", "signed", "unchanged"),
|
||||
_form("S_BFE_I32", 40, "BfeI32", "bfe", "signed", "nonzero"),
|
||||
dict(
|
||||
_form("S_LSHL2_ADD_U32", 47, "Lshl2AddU32", "lshl_add", "unsigned", "carry_out"),
|
||||
shift_amount=2,
|
||||
),
|
||||
_form("S_MUL_HI_U32", 53, "MulHiU32", "mul_hi", "unsigned", "unchanged"),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def compares():
|
||||
reg = registry()
|
||||
reg["form"] += [
|
||||
_compare("S_CMP_LT_I32", 4, "CmpLtI32", "lt", "signed"),
|
||||
_compare("S_CMP_LT_U32", 10, "CmpLtU32", "lt", "unsigned"),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def _compare(name, opcode, variant, relation, signedness):
|
||||
form = _form(name, opcode, variant, "compare", signedness, "relation")
|
||||
form.update(family="SOPC", relation=relation, operands="sopc_scalar")
|
||||
return form
|
||||
|
||||
|
||||
def registry():
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS)
|
||||
compare_rule = copy.deepcopy(gen.OPERAND_RULES["sopc_scalar"]["shape"])
|
||||
compare_rule["unsupported"] = sorted(gen.OPERAND_RULES["sopc_scalar"]["unsupported"])
|
||||
return {
|
||||
"schema": 1,
|
||||
"architecture": "gfx1030",
|
||||
"source_sha256": SHA,
|
||||
"documents": copy.deepcopy(gen.PINNED_DOCUMENTS),
|
||||
"operand_rules": {"sop2_sgpr": rule, "sopc_scalar": compare_rule},
|
||||
"form": [
|
||||
_form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"),
|
||||
_form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"),
|
||||
_form("S_ADDC_U32", 4, "AddcU32", "add", "unsigned", "carry_out", carry_in="scc"),
|
||||
_form("S_AND_B32", 14, "AndB32", "and", "bitwise", "nonzero"),
|
||||
dict(
|
||||
_form("S_ASHR_I32", 34, "AshrI32", "ashr", "signed", "nonzero"),
|
||||
shift_count_bits=5,
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def form(reg, name):
|
||||
return next(item for item in reg["form"] if item["name"] == name)
|
||||
|
||||
|
||||
class Validate(unittest.TestCase):
|
||||
def errors(self, reg, snap=None):
|
||||
return gen.validate(reg, snap if snap is not None else snapshot())
|
||||
|
||||
def rejects(self, reg, fragment, snap=None):
|
||||
errors = self.errors(reg, snap)
|
||||
self.assertTrue(
|
||||
any(fragment in error for error in errors),
|
||||
f"expected an error containing {fragment!r}, got {errors}",
|
||||
)
|
||||
|
||||
# ---- acceptance ----
|
||||
|
||||
def test_accepts_the_fixture(self):
|
||||
self.assertEqual(self.errors(registry()), [])
|
||||
|
||||
def test_accepts_the_real_registry(self):
|
||||
self.assertEqual(gen.validate(gen.load_registry(), gen.load_snapshot()), [])
|
||||
|
||||
# ---- top level ----
|
||||
|
||||
def test_rejects_wrong_schema(self):
|
||||
reg = registry()
|
||||
reg["schema"] = 2
|
||||
self.rejects(reg, "schema 2 is not 1")
|
||||
|
||||
def test_rejects_source_sha256_mismatch(self):
|
||||
reg = registry()
|
||||
reg["source_sha256"] = "f" * 64
|
||||
self.rejects(reg, "source_sha256 does not match")
|
||||
|
||||
def test_rejects_unknown_top_level_key(self):
|
||||
reg = registry()
|
||||
reg["notes"] = "x"
|
||||
self.rejects(reg, "unknown top-level keys ['notes']")
|
||||
|
||||
def test_rejects_empty_registry(self):
|
||||
reg = registry()
|
||||
reg["form"] = []
|
||||
self.rejects(reg, "declares no forms")
|
||||
|
||||
# ---- incomplete or unknown fields ----
|
||||
|
||||
def test_rejects_missing_required_field(self):
|
||||
reg = registry()
|
||||
del form(reg, "S_ADD_U32")["scc"]
|
||||
self.rejects(reg, "S_ADD_U32: incomplete, missing ['scc']")
|
||||
|
||||
def test_rejects_unknown_form_key(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["expression"] = "a + b"
|
||||
self.rejects(reg, "S_ADD_U32: unknown keys ['expression']")
|
||||
|
||||
# ---- closed vocabularies ----
|
||||
|
||||
def test_rejects_unknown_operation(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["operation"] = "fma"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operation 'fma'")
|
||||
|
||||
def test_rejects_unknown_scc_effect(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["scc"] = "overflow"
|
||||
self.rejects(reg, "S_ADD_U32: unknown scc 'overflow'")
|
||||
|
||||
def test_rejects_unknown_mask_effect(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["vcc"] = "written"
|
||||
self.rejects(reg, "S_ADD_U32: unknown vcc 'written'")
|
||||
|
||||
def test_rejects_unsupported_width(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["width"] = 64
|
||||
self.rejects(reg, "S_ADD_U32: width 64 is not supported")
|
||||
|
||||
def test_rejects_unknown_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = ["reference", "hardware"]
|
||||
self.rejects(reg, "S_ADD_U32: unknown verification requirement")
|
||||
|
||||
def test_rejects_empty_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = []
|
||||
self.rejects(reg, "S_ADD_U32: no verification requirement")
|
||||
|
||||
# ---- contradictions ----
|
||||
|
||||
def test_rejects_bitwise_operation_declared_signed(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["signedness"] = "signed"
|
||||
self.rejects(reg, "S_AND_B32: signedness signed contradicts operation and")
|
||||
|
||||
def test_rejects_carry_in_on_logical_operation(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["carry_in"] = "scc"
|
||||
self.rejects(reg, "S_AND_B32: carry_in scc contradicts and/bitwise")
|
||||
|
||||
def test_rejects_carry_out_on_signed_form(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_I32")["scc"] = "carry_out"
|
||||
self.rejects(reg, "S_ADD_I32: scc carry_out contradicts add/signed")
|
||||
|
||||
def test_rejects_scc_unchanged_on_a_form_that_writes_it(self):
|
||||
# Declared as preserving SCC while the primitive and the XML both write it.
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["scc"] = "unchanged"
|
||||
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts add/unsigned")
|
||||
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_carry_in_the_xml_does_not_read(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["carry_in"] = "scc"
|
||||
self.rejects(reg, "S_ADD_U32: carry_in scc contradicts the XML SCC input")
|
||||
|
||||
def test_rejects_signedness_contradicting_xml_format(self):
|
||||
reg = registry()
|
||||
f = form(reg, "S_ADD_I32")
|
||||
f["signedness"], f["scc"] = "unsigned", "carry_out"
|
||||
self.rejects(reg, "S_ADD_I32: signedness unsigned contradicts XML format FMT_NUM_I32")
|
||||
|
||||
# ---- identity against the XML snapshot ----
|
||||
|
||||
def test_rejects_opcode_mismatch(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["opcode"] = 1
|
||||
self.rejects(reg, "S_ADD_U32: opcode 1 disagrees with the XML opcode 0")
|
||||
|
||||
def test_rejects_family_mismatch(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["family"] = "SOPC"
|
||||
self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2")
|
||||
self.rejects(reg, "S_ADD_U32: no default ENC_SOPC variant in the XML snapshot")
|
||||
form(reg, "S_ADD_U32")["family"] = "SOPK"
|
||||
self.rejects(reg, "S_ADD_U32: family SOPK has no XML encoding ENC_SOPK")
|
||||
|
||||
def test_rejects_form_absent_from_the_xml(self):
|
||||
reg = registry()
|
||||
reg["form"].append(_form("S_ABSDIFF_I32", 44, "AbsdiffI32", "absdiff", "signed", "nonzero"))
|
||||
self.rejects(reg, "S_ABSDIFF_I32: no default ENC_SOP2 variant in the XML snapshot")
|
||||
|
||||
# ---- duplicates ----
|
||||
|
||||
def test_rejects_duplicate_name(self):
|
||||
reg = registry()
|
||||
reg["form"].append(copy.deepcopy(form(reg, "S_ADD_U32")))
|
||||
self.rejects(reg, "S_ADD_U32: duplicate name S_ADD_U32")
|
||||
|
||||
def test_rejects_same_encoding_claimed_twice(self):
|
||||
reg = registry()
|
||||
twin = copy.deepcopy(form(reg, "S_ADD_U32"))
|
||||
twin["name"], twin["variant"] = "S_ADD_U32_COPY", "AddU32Copy"
|
||||
reg["form"].append(twin)
|
||||
self.rejects(reg, "S_ADD_U32_COPY: duplicate opcode ('SOP2', 0)")
|
||||
|
||||
def test_rejects_duplicate_variant(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_I32")["variant"] = "AddU32"
|
||||
self.rejects(reg, "S_ADD_I32: duplicate variant AddU32")
|
||||
|
||||
# ---- references ----
|
||||
|
||||
def test_rejects_missing_guide_reference(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"] = [{"document": "xml", "section": "1", "page": 0}]
|
||||
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
|
||||
|
||||
def test_rejects_undeclared_document(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"].append({"document": "blog", "section": "1", "page": 1})
|
||||
self.rejects(reg, "S_ADD_U32: spec cites undeclared document 'blog'")
|
||||
|
||||
# ---- operand rules ----
|
||||
|
||||
def test_rejects_unknown_operand_rule_on_a_form(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["operands"] = "vop2_vgpr"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operand rule 'vop2_vgpr'")
|
||||
|
||||
def test_rejects_operand_rule_the_decoder_does_not_implement(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["vop2_vgpr"] = {"family": "VOP2"}
|
||||
self.rejects(reg, "operand rule vop2_vgpr: not implemented by the decoder")
|
||||
|
||||
def test_rejects_operand_rule_shape_differing_from_the_decoder(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
|
||||
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
|
||||
|
||||
def test_rejects_a_shift_without_a_count_width(self):
|
||||
reg = registry()
|
||||
del reg["form"][-1]["shift_count_bits"]
|
||||
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got None")
|
||||
|
||||
def test_rejects_a_wrong_count_width(self):
|
||||
reg = registry()
|
||||
reg["form"][-1]["shift_count_bits"] = 6
|
||||
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got 6")
|
||||
|
||||
def test_rejects_a_count_width_on_a_non_shift(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["shift_count_bits"] = 5
|
||||
self.rejects(reg, "S_ADD_U32: shift_count_bits on a non-shift operation")
|
||||
|
||||
def test_rejects_a_signed_shift_count_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(I32)
|
||||
self.rejects(registry(), "S_ASHR_I32: control operand SSRC1 has XML format FMT_NUM_I32", snap)
|
||||
|
||||
def test_rejects_a_float_shift_count_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(
|
||||
I32, src1_format="FMT_NUM_F32"
|
||||
)
|
||||
self.rejects(registry(), "S_ASHR_I32: control operand SSRC1 has XML format FMT_NUM_F32", snap)
|
||||
|
||||
def test_rejects_a_float_source_format(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_AND_B32", "ENC_SOP2")]["operands"] = _operands("FMT_NUM_F32")
|
||||
self.rejects(registry(), "S_AND_B32: signedness bitwise contradicts XML format FMT_NUM_F32", snap)
|
||||
|
||||
def test_rejects_a_negative_count_width(self):
|
||||
reg = registry()
|
||||
reg["form"][-1]["shift_count_bits"] = -1
|
||||
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got -1")
|
||||
|
||||
def test_rejects_an_unsigned_arithmetic_shift(self):
|
||||
reg = registry()
|
||||
reg["form"][-1]["signedness"] = "unsigned"
|
||||
self.rejects(reg, "S_ASHR_I32: no primitive implements ashr/unsigned")
|
||||
|
||||
def test_renders_the_declared_count_mask(self):
|
||||
self.assertIn(
|
||||
"let (value, scc) = primitive::ashr_nonzero_i32(src0, src1 & 0x1f);",
|
||||
gen.render(registry(), snapshot()),
|
||||
)
|
||||
|
||||
def test_accepts_unaries(self):
|
||||
self.assertEqual(self.errors(unaries()), [])
|
||||
|
||||
def test_rejects_a_sext_without_source_bits(self):
|
||||
reg = unaries()
|
||||
del reg["form"][-1]["source_bits"]
|
||||
self.rejects(reg, "S_SEXT_I32_I8: source_bits must be one of [8, 16], got None")
|
||||
|
||||
def test_rejects_a_sext_whose_source_bits_contradict_the_xml(self):
|
||||
reg = unaries()
|
||||
reg["form"][-1]["source_bits"] = 16
|
||||
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 is 8 bits in the XML, declared 16")
|
||||
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 has XML format FMT_NUM_I8, not FMT_NUM_I16")
|
||||
|
||||
def test_rejects_source_bits_on_another_operation(self):
|
||||
reg = unaries()
|
||||
reg["form"][-2]["source_bits"] = 8
|
||||
self.rejects(reg, "S_BREV_B32: source_bits on a non-sext operation")
|
||||
|
||||
def test_rejects_an_scc_write_the_xml_does_not_show(self):
|
||||
reg = unaries()
|
||||
reg["form"][-2]["operation"] = "not"
|
||||
reg["form"][-2]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_BREV_B32: scc nonzero contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_a_unary_operation_under_a_binary_rule(self):
|
||||
reg = unaries()
|
||||
reg["form"][0]["operation"] = "not"
|
||||
reg["form"][0]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_ADD_U32: operation not does not fit rule sop2_sgpr")
|
||||
|
||||
def test_renders_unary_scc_as_optional(self):
|
||||
text = gen.render(unaries(), snapshot())
|
||||
self.assertIn("Self::BrevB32 => (primitive::brev_b32(src), None),", text)
|
||||
self.assertIn("Self::SextI32I8 => (primitive::sext_i32(src, 8), None),", text)
|
||||
self.assertIn("let (value, scc) = primitive::not_nonzero_b32(src);", text)
|
||||
|
||||
def test_accepts_ariths(self):
|
||||
self.assertEqual(self.errors(ariths()), [])
|
||||
|
||||
def test_rejects_min_with_a_nonzero_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MIN_I32")["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_MIN_I32: scc nonzero contradicts min/signed (requires selected_src0)")
|
||||
|
||||
def test_rejects_a_select_that_does_not_read_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_CSELECT_B32")["carry_in"] = "none"
|
||||
self.rejects(reg, "S_CSELECT_B32: operation cselect reads SCC (requires carry_in scc)")
|
||||
self.rejects(reg, "S_CSELECT_B32: carry_in none contradicts the XML SCC input")
|
||||
|
||||
def test_rejects_a_select_that_writes_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_CSELECT_B32")["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_CSELECT_B32: scc nonzero contradicts cselect/bitwise (requires unchanged)")
|
||||
self.rejects(reg, "S_CSELECT_B32: scc nonzero contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_a_typed_select(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_CSELECT_B32")["signedness"] = "unsigned"
|
||||
self.rejects(reg, "S_CSELECT_B32: signedness unsigned contradicts operation cselect")
|
||||
|
||||
def test_rejects_a_multiply_that_writes_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MUL_I32")["scc"] = "signed_overflow"
|
||||
self.rejects(reg, "S_MUL_I32: scc signed_overflow contradicts mul/signed (requires unchanged)")
|
||||
|
||||
def test_rejects_a_bitwise_multiply(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MUL_HI_U32")["signedness"] = "bitwise"
|
||||
self.rejects(reg, "S_MUL_HI_U32: signedness bitwise contradicts operation mul_hi")
|
||||
|
||||
def test_rejects_a_signed_bfe_descriptor_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_BFE_I32", "ENC_SOP2")]["operands"] = _operands(I32)
|
||||
self.rejects(ariths(), "S_BFE_I32: control operand SSRC1 has XML format FMT_NUM_I32", snap)
|
||||
|
||||
def test_rejects_a_signed_bfe_data_operand_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_BFE_I32", "ENC_SOP2")]["operands"] = _operands(U32)
|
||||
self.rejects(ariths(), "S_BFE_I32: signedness signed contradicts XML format FMT_NUM_U32", snap)
|
||||
|
||||
def test_rejects_shift_add_without_or_with_a_wrong_amount(self):
|
||||
for amount, shown in ((None, "None"), (0, "0"), (5, "5"), (True, "True"), ("2", "'2'")):
|
||||
with self.subTest(amount=amount):
|
||||
reg = ariths()
|
||||
if amount is None:
|
||||
del form(reg, "S_LSHL2_ADD_U32")["shift_amount"]
|
||||
else:
|
||||
form(reg, "S_LSHL2_ADD_U32")["shift_amount"] = amount
|
||||
self.rejects(reg, f"S_LSHL2_ADD_U32: shift_amount must be one of [1, 2, 3, 4], got {shown}")
|
||||
|
||||
def test_rejects_a_shift_amount_on_another_operation(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MIN_I32")["shift_amount"] = 1
|
||||
self.rejects(reg, "S_MIN_I32: shift_amount on a non-lshl_add operation")
|
||||
|
||||
def test_renders_alu_scc_as_optional_and_the_declared_data(self):
|
||||
text = gen.render(ariths(), snapshot())
|
||||
self.assertIn("Self::CselectB32 => (primitive::cselect_b32(src0, src1, scc_in), None),", text)
|
||||
self.assertIn("Self::MulHiU32 => (primitive::mul_hi_u32(src0, src1), None),", text)
|
||||
self.assertIn("let (value, scc) = primitive::lshl_add_carry_u32(src0, src1, 2);", text)
|
||||
self.assertIn("let (value, scc) = primitive::min_i32(src0, src1);", text)
|
||||
self.assertIn("Self::CselectB32 => true,", text.split("fn reads_scc", 1)[1].split("}", 1)[0])
|
||||
self.assertIn("Self::CselectB32 => false,", text.split("fn writes_scc", 1)[1].split("}", 1)[0])
|
||||
self.assertIn("shift_amount: 2,", text)
|
||||
self.assertIn("scc: SccEffect::SelectedSrc0,", text)
|
||||
|
||||
def test_accepts_compares(self):
|
||||
self.assertEqual(self.errors(compares()), [])
|
||||
|
||||
def test_rejects_a_compare_without_a_relation(self):
|
||||
reg = compares()
|
||||
del reg["form"][-1]["relation"]
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation None")
|
||||
|
||||
def test_rejects_an_unknown_relation(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["relation"] = "ne"
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation 'ne'")
|
||||
|
||||
def test_rejects_a_non_string_relation(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["relation"] = ["lt"]
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation ['lt']")
|
||||
|
||||
def test_rejects_a_rule_without_sources(self):
|
||||
reg = compares()
|
||||
del reg["operand_rules"]["sopc_scalar"]["src"]
|
||||
self.rejects(reg, "operand rule sopc_scalar: declaration differs from the decoder's implemented rule")
|
||||
|
||||
def test_rejects_a_relation_on_a_non_compare(self):
|
||||
reg = compares()
|
||||
reg["form"][0]["relation"] = "lt"
|
||||
self.rejects(reg, "S_ADD_U32: relation on a non-compare operation")
|
||||
|
||||
def test_rejects_a_compare_with_another_scc_effect(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_CMP_LT_U32: scc nonzero contradicts compare (requires relation)")
|
||||
|
||||
def test_rejects_a_bitwise_compare(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["signedness"] = "bitwise"
|
||||
self.rejects(reg, "S_CMP_LT_U32: no primitive implements lt/bitwise")
|
||||
|
||||
def test_rejects_a_compare_whose_signedness_contradicts_the_xml(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["signedness"] = "signed"
|
||||
self.rejects(reg, "S_CMP_LT_U32: signedness signed contradicts XML format FMT_NUM_U32")
|
||||
|
||||
def test_rejects_a_compare_under_an_alu_rule(self):
|
||||
reg = compares()
|
||||
reg["form"][0]["operation"] = "compare"
|
||||
reg["form"][0]["relation"] = "lt"
|
||||
reg["form"][0]["scc"] = "relation"
|
||||
self.rejects(reg, "S_ADD_U32: operation compare does not fit rule sop2_sgpr")
|
||||
|
||||
def test_renders_compare_dispatch_and_relation(self):
|
||||
text = gen.render(compares(), snapshot())
|
||||
self.assertIn("if word & 0xff80_0000 != 0xbf00_0000 {", text)
|
||||
self.assertIn("Self::CmpLtI32 => primitive::lt_i32(src0, src1),", text)
|
||||
self.assertIn("Self::CmpLtU32 => primitive::lt_u32(src0, src1),", text)
|
||||
self.assertIn("relation: Some(CompareRelation::Less),", text)
|
||||
|
||||
def test_rejects_an_incomplete_unsupported_list(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
|
||||
self.rejects(
|
||||
reg, "operand rule sop2_sgpr: unsupported combos differ from those the decoder rejects"
|
||||
)
|
||||
|
||||
def test_rejects_a_citation_to_another_file(self):
|
||||
reg = registry()
|
||||
reg["documents"]["guide"]["file"] = "missing.pdf"
|
||||
self.rejects(reg, "document guide: differs from the pinned public document")
|
||||
|
||||
def test_rejects_an_unenforced_wave_restriction(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["wave"] = "wave32"
|
||||
self.rejects(reg, "S_ADD_U32: wave wave32 has no decoder enforcement yet")
|
||||
|
||||
def test_rejects_a_reserved_variant(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["variant"] = "Self"
|
||||
self.rejects(reg, "S_ADD_U32: variant 'Self' is reserved")
|
||||
|
||||
def test_rejects_a_boolean_schema(self):
|
||||
reg = registry()
|
||||
reg["schema"] = True
|
||||
self.rejects(reg, "schema True is not 1")
|
||||
|
||||
def test_rejects_unknown_unsupported_combo(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_lds")
|
||||
self.rejects(reg, "operand rule sop2_sgpr: unknown unsupported combos ['dst_lds']")
|
||||
|
||||
def test_rejects_duplicate_unsupported_combo(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_vcc")
|
||||
self.rejects(reg, "operand rule sop2_sgpr: duplicate unsupported combos")
|
||||
|
||||
# ---- remaining vocabulary, identity and reference rules ----
|
||||
|
||||
def test_rejects_wrong_architecture(self):
|
||||
reg = registry()
|
||||
reg["architecture"] = "gfx1100"
|
||||
self.rejects(reg, "architecture 'gfx1100' is not gfx1030")
|
||||
|
||||
def test_rejects_unknown_document(self):
|
||||
reg = registry()
|
||||
reg["documents"]["blog"] = {"title": "blog"}
|
||||
self.rejects(reg, "unknown document blog")
|
||||
|
||||
def test_rejects_unknown_signedness_carry_in_exec_and_wave(self):
|
||||
for key, value in (
|
||||
("signedness", "float"), ("carry_in", "vcc"), ("exec", "written"), ("wave", "wave64"),
|
||||
):
|
||||
with self.subTest(key=key):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")[key] = value
|
||||
self.rejects(reg, f"S_ADD_U32: unknown {key} {value!r}")
|
||||
|
||||
def test_rejects_invalid_name_variant_and_opcode(self):
|
||||
for key, value, fragment in (
|
||||
("name", "s_add_u32", "s_add_u32: invalid name"),
|
||||
("variant", "add_u32", "S_ADD_U32: invalid variant 'add_u32'"),
|
||||
("opcode", -1, "S_ADD_U32: invalid opcode"),
|
||||
("opcode", True, "S_ADD_U32: invalid opcode"),
|
||||
):
|
||||
with self.subTest(key=key, value=value):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")[key] = value
|
||||
self.rejects(reg, fragment)
|
||||
|
||||
def test_rejects_declaration_no_primitive_implements(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["operation"] = "sub"
|
||||
self.rejects(reg, "S_AND_B32: no primitive implements sub/bitwise")
|
||||
|
||||
def test_rejects_duplicate_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = ["reference", "reference"]
|
||||
self.rejects(reg, "S_ADD_U32: duplicate verification requirement")
|
||||
|
||||
def test_rejects_malformed_spec_references(self):
|
||||
for ref, fragment in (
|
||||
({"document": "guide", "section": "12.1"}, "spec reference needs exactly document, section, page"),
|
||||
({"document": "guide", "section": "12.x", "page": 101}, "invalid spec section '12.x'"),
|
||||
({"document": "guide", "section": "12.1", "page": -1}, "invalid spec page"),
|
||||
):
|
||||
with self.subTest(ref=ref):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"].append(ref)
|
||||
self.rejects(reg, f"S_ADD_U32: {fragment}")
|
||||
|
||||
def test_rejects_guide_reference_without_a_page(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"] = [{"document": "guide", "section": "12.1", "page": 0}]
|
||||
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
|
||||
|
||||
def test_rejects_opcode_outside_the_encoding_identifiers(self):
|
||||
snap = snapshot()
|
||||
snap["encodings"]["ENC_SOP2"]["identifiers"].remove(0x80000000 | (14 << 23))
|
||||
self.rejects(registry(), "S_AND_B32: opcode 14 is not an identifier of ENC_SOP2", snap)
|
||||
|
||||
def test_rejects_xml_operand_disagreements(self):
|
||||
cases = (
|
||||
("missing", lambda ops: ops.pop(2), "S_ADD_U32: XML has no operand SSRC1"),
|
||||
("width", lambda ops: ops[1].__setitem__(3, 64), "S_ADD_U32: SSRC0 is 64 bits in the XML"),
|
||||
("direction", lambda ops: ops[0].__setitem__(4, True),
|
||||
"S_ADD_U32: SDST direction disagrees with the XML"),
|
||||
("extra", lambda ops: ops.append(["SIMM16", U32, "OPR_SIMM16", 16, True, False, False, True]),
|
||||
"S_ADD_U32: XML operands ['SIMM16'] are not covered by rule sop2_sgpr"),
|
||||
)
|
||||
for label, change, fragment in cases:
|
||||
with self.subTest(case=label):
|
||||
snap = snapshot()
|
||||
change(snap["variants"][("S_ADD_U32", "ENC_SOP2")]["operands"])
|
||||
self.rejects(registry(), fragment, snap)
|
||||
|
||||
|
||||
def _reorder(value):
|
||||
"""Reverse the key order of every mapping, keeping list order."""
|
||||
if isinstance(value, dict):
|
||||
return {key: _reorder(value[key]) for key in reversed(list(value))}
|
||||
if isinstance(value, list):
|
||||
return [_reorder(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_two_renders_are_identical(self):
|
||||
self.assertEqual(gen.render(registry(), snapshot()), gen.render(registry(), snapshot()))
|
||||
|
||||
def test_render_ignores_mapping_key_order(self):
|
||||
reg = registry()
|
||||
reordered = _reorder(reg)
|
||||
self.assertNotEqual(list(reg["form"][0]), list(reordered["form"][0]))
|
||||
self.assertEqual(gen.render(reg, snapshot()), gen.render(reordered, snapshot()))
|
||||
|
||||
def test_dispatch_table_is_indexed_by_opcode(self):
|
||||
reg = registry()
|
||||
reg["form"].reverse()
|
||||
text = gen.render(reg, snapshot())
|
||||
body = text.split("const SCALAR_ALU_OP_BY_OPCODE: [Option<ScalarAluOp>; 128] = [", 1)[1].split("];", 1)[0]
|
||||
rows = [line.strip() for line in body.splitlines() if line.strip()]
|
||||
self.assertEqual(len(rows), 128)
|
||||
declared = {index: row for index, row in enumerate(rows) if row != "None,"}
|
||||
self.assertEqual(sorted(declared), [0, 2, 4, 14, 34])
|
||||
self.assertEqual(declared[34], "Some(ScalarAluOp::AshrI32),")
|
||||
self.assertIn("if word & 0xc000_0000 != 0x8000_0000 {", text)
|
||||
self.assertIn("SCALAR_ALU_OP_BY_OPCODE[((word >> 23) & 0x7f) as usize]", text)
|
||||
|
||||
def test_rejects_identifiers_that_do_not_share_the_encoding_bits(self):
|
||||
snap = snapshot()
|
||||
snap["encodings"]["ENC_SOP2"]["identifiers"].append(0x40000000)
|
||||
with self.assertRaisesRegex(ValueError, "do not split into fixed bits and OP"):
|
||||
gen.render(registry(), snap)
|
||||
|
||||
def test_real_registry_renders_the_committed_file(self):
|
||||
text = gen.render(gen.load_registry(), gen.load_snapshot())
|
||||
self.assertEqual(text, gen.RUST.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
class CommandLine(unittest.TestCase):
|
||||
def run_cli(self, *arguments):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SCRIPT), *map(str, arguments)],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.dir = Path(self.tmp.name)
|
||||
|
||||
def test_check_passes_on_the_committed_file(self):
|
||||
result = self.run_cli("--check")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_check_passes_on_a_fresh_file_and_fails_on_a_stale_one(self):
|
||||
output = self.dir / "semantics_gen.rs"
|
||||
result = self.run_cli("generate", "--output", output)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
fresh = output.read_text(encoding="utf-8")
|
||||
self.assertEqual(self.run_cli("--check", "--output", output).returncode, 0)
|
||||
|
||||
output.write_text(fresh.replace("pub const GENERATED_SCHEMA: u32 = 1;", "pub const GENERATED_SCHEMA: u32 = 2;"))
|
||||
stale = self.run_cli("--check", "--output", output)
|
||||
self.assertEqual(stale.returncode, 1)
|
||||
self.assertIn("is stale", stale.stderr)
|
||||
# --check never writes.
|
||||
self.assertNotEqual(output.read_text(encoding="utf-8"), fresh)
|
||||
|
||||
def test_check_fails_when_the_generated_file_is_missing(self):
|
||||
self.assertEqual(self.run_cli("--check", "--output", self.dir / "absent.rs").returncode, 1)
|
||||
|
||||
def test_invalid_registry_fails_every_mode_without_writing(self):
|
||||
bad = self.dir / "rdna2.toml"
|
||||
text = gen.REGISTRY.read_text(encoding="utf-8")
|
||||
bad.write_text(text.replace("\nschema = 1\n", "\nschema = 2\n", 1), encoding="utf-8")
|
||||
output = self.dir / "out.rs"
|
||||
for mode in (("validate",), ("generate",), ("--check",)):
|
||||
result = self.run_cli(*mode, "--registry", bad, "--output", output)
|
||||
self.assertEqual(result.returncode, 1, mode)
|
||||
self.assertIn("error: schema 2 is not 1", result.stderr)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_validate_reports_the_form_count(self):
|
||||
result = self.run_cli("validate")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,9 +8,13 @@
|
||||
//! field layout and executes them with an explicit program-counter machine, so
|
||||
//! a defect in the production decoder or reference cannot cancel out here.
|
||||
//!
|
||||
//! Scope matches the demo fixtures: scalar move/compare/branch, SOP2 unsigned
|
||||
//! Scope matches the demo fixtures: scalar move, eleven SOP1 unary forms
|
||||
//! (NOT, BREV, BCNT0/1, FF0/1, FLBIT, FLBIT_I32, SEXT_I8/I16, ABS), the twelve SOPC 32-bit integer
|
||||
//! compares, branch, SOP2 unsigned
|
||||
//! and signed add and subtract, add-with-carry, subtract-with-borrow, AND, OR
|
||||
//! and XOR, VOP1 move
|
||||
//! and XOR, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
|
||||
//! ASHR (32-bit), the 32-bit integer forms MIN/MAX (I32, U32), CSELECT, BFM,
|
||||
//! MUL_I32, BFE (U32, I32), ABSDIFF, LSHL1-4_ADD and MUL_HI (U32, I32), VOP1 move
|
||||
//! (including from an SGPR),
|
||||
//! VOP2 bitwise, shift, arithmetic-shift and float, VOP3 add-no-carry, MUBUF
|
||||
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
|
||||
@@ -50,9 +54,13 @@ enum CmpSrc {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Insn {
|
||||
SMov(u8, Src),
|
||||
/// SOP2 opcode 0-5, 14, 16 or 18.
|
||||
/// SOP1 unary opcode 7, 11, 13, 15, 17, 19, 21, 23, 25, 26 or 52.
|
||||
SUnary(u32, u8, Src),
|
||||
/// SOP2 opcode 0-10, 14, 16, 18, an even opcode 20-36, 38-40, 44, 46-49,
|
||||
/// 53 or 54.
|
||||
SAlu(u32, u8, Src, Src),
|
||||
SCmpEq(Src, Src),
|
||||
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
|
||||
SCmp(u32, Src, Src),
|
||||
BranchScc0(usize),
|
||||
BranchMaskZero {
|
||||
target: usize,
|
||||
@@ -205,6 +213,20 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
None
|
||||
})
|
||||
}
|
||||
Insn::SUnary(opcode, dst, src) => {
|
||||
if dst < 8 {
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
} else {
|
||||
read_s(&sgpr, src).map(|value| {
|
||||
let (result, flag) = scalar_unary(opcode, value);
|
||||
sgpr[dst as usize] = Some(result);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::SMov(dst, src) => {
|
||||
if dst < 8 {
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
@@ -218,9 +240,9 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::SCmpEq(a, b) => read_s(&sgpr, a).and_then(|a| {
|
||||
Insn::SCmp(opcode, a, b) => read_s(&sgpr, a).and_then(|a| {
|
||||
read_s(&sgpr, b).map(|b| {
|
||||
scc = Some(a == b);
|
||||
scc = Some(scalar_compare(opcode, a, b));
|
||||
None
|
||||
})
|
||||
}),
|
||||
@@ -298,8 +320,87 @@ fn scalar_alu(
|
||||
};
|
||||
let (a, b) = (read(a)?, read(b)?);
|
||||
let carry_in = || scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"));
|
||||
let bit = |word: u32, i: u32| (word >> i) & 1 == 1;
|
||||
let (value, flag) = match opcode {
|
||||
0 => ripple(a, b, false),
|
||||
// RDNA 2 ISA guide 12.1: MIN/MAX pick S0 iff S0 < S1 (> for MAX), the
|
||||
// order a borrow out of S0 - S1 (or S1 - S0) shows; signed forms flip
|
||||
// both sign bits first. SCC = whether S0 was picked (0 on a tie).
|
||||
6..=9 => {
|
||||
let flip = if opcode % 2 == 0 { 0x8000_0000 } else { 0 };
|
||||
let (x, y) = (a ^ flip, b ^ flip);
|
||||
let (p, q) = if opcode < 8 { (x, y) } else { (y, x) };
|
||||
let first = !ripple(p, !q, true).1;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
// CSELECT: D = SCC ? S0 : S1.
|
||||
10 => {
|
||||
let pick_first = carry_in()?;
|
||||
(if pick_first { a } else { b }, false)
|
||||
}
|
||||
// BFM: bit i of D is set iff S1[4:0] <= i < S1[4:0] + S0[4:0].
|
||||
36 => {
|
||||
let (size, start) = (a % 32, b % 32);
|
||||
let value = (0..32)
|
||||
.filter(|&i| i >= start && i < start + size)
|
||||
.fold(0, |d, i| d | 1 << i);
|
||||
(value, false)
|
||||
}
|
||||
// MUL_I32 and MUL_HI: the 64-bit unsigned product by shift and add;
|
||||
// the signed high word subtracts S1 when S0 < 0 and S0 when S1 < 0
|
||||
// (two's complement correction).
|
||||
38 | 53 | 54 => {
|
||||
let product = (0..32)
|
||||
.filter(|&i| bit(b, i))
|
||||
.fold(0_u64, |sum, i| sum + (u64::from(a) << i));
|
||||
let (low, mut high) = (product as u32, (product >> 32) as u32);
|
||||
if opcode == 54 {
|
||||
if bit(a, 31) {
|
||||
high = ripple(high, !b, true).0;
|
||||
}
|
||||
if bit(b, 31) {
|
||||
high = ripple(high, !a, true).0;
|
||||
}
|
||||
}
|
||||
(if opcode == 38 { low } else { high }, false)
|
||||
}
|
||||
// BFE: D[i] = S0[offset + i] for i < width (offset S1[4:0], width
|
||||
// S1[22:16]); positions past bit 31 read 0 (U32) or S0[31] (I32), and
|
||||
// I32 copies D[width - 1] into the bits at and above width. SCC = D != 0.
|
||||
39 | 40 => {
|
||||
let (start, width) = (b % 32, (b >> 16) % 128);
|
||||
let source = |i: u32| match start + i {
|
||||
at @ 0..=31 => bit(a, at),
|
||||
_ => opcode == 40 && bit(a, 31),
|
||||
};
|
||||
let value = (0..32).fold(0, |d, i| {
|
||||
let set = if i < width {
|
||||
source(i)
|
||||
} else {
|
||||
opcode == 40 && width > 0 && source(width - 1)
|
||||
};
|
||||
d | u32::from(set) << i
|
||||
});
|
||||
(value, value != 0)
|
||||
}
|
||||
// ABSDIFF: the 32-bit S0 - S1, negated when bit 31 is set
|
||||
// (0x80000000 stays). SCC = D != 0.
|
||||
44 => {
|
||||
let difference = ripple(a, !b, true).0;
|
||||
let value = if bit(difference, 31) {
|
||||
ripple(!difference, 0, true).0
|
||||
} else {
|
||||
difference
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
// LSHLn_ADD, n = 1-4: D = (S0 << n) + S1; SCC = 1 iff the exact sum
|
||||
// reaches 2^32, i.e. bits shifted out of S0 or a carry out of the add.
|
||||
46..=49 => {
|
||||
let n = opcode - 45;
|
||||
let (value, carry) = ripple(a << n, b, false);
|
||||
(value, carry || a >> (32 - n) != 0)
|
||||
}
|
||||
// RDNA 2 ISA guide 12.1: signed overflow from the sign bits,
|
||||
// add: S0[31] == S1[31] != D[31]; subtract: S0[31] != S1[31] != D[31].
|
||||
2 | 3 => {
|
||||
@@ -320,6 +421,18 @@ fn scalar_alu(
|
||||
let (value, carry) = ripple(a, !b, !borrow);
|
||||
(value, !carry)
|
||||
}
|
||||
// RDNA 2 ISA guide 12.1: the shifts use only S1[4:0], taken here as
|
||||
// the remainder modulo 32, and scale by a power of two in exact
|
||||
// arithmetic; ASHR is floor division of the signed S0. SCC = D != 0.
|
||||
30 | 32 | 34 => {
|
||||
let scale = 1_i64 << (b % 32);
|
||||
let value = match opcode {
|
||||
30 => (i64::from(a) * scale).rem_euclid(1 << 32),
|
||||
32 => i64::from(a) / scale,
|
||||
_ => i64::from(a as i32).div_euclid(scale).rem_euclid(1 << 32),
|
||||
} as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
_ => {
|
||||
let mut value = 0;
|
||||
for bit in 0..32 {
|
||||
@@ -327,7 +440,12 @@ fn scalar_alu(
|
||||
let set = match opcode {
|
||||
14 => x && y,
|
||||
16 => x || y,
|
||||
_ => x != y,
|
||||
18 => x != y,
|
||||
20 => x && !y,
|
||||
22 => x || !y,
|
||||
24 => !(x && y),
|
||||
26 => !(x || y),
|
||||
_ => x == y,
|
||||
};
|
||||
value |= u32::from(set) << bit;
|
||||
}
|
||||
@@ -335,10 +453,77 @@ fn scalar_alu(
|
||||
}
|
||||
};
|
||||
sgpr[dst as usize] = Some(value);
|
||||
*scc = Some(flag);
|
||||
// CSELECT, BFM, MUL_I32 and MUL_HI have no SCC line in guide 12.1 ("n" in
|
||||
// Tables 11, 12 and 14): SCC stays as it was, possibly unset.
|
||||
if !matches!(opcode, 10 | 36 | 38 | 53 | 54) {
|
||||
*scc = Some(flag);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// RDNA 2 ISA guide 12.4: SCC = (S0 <relation> S1). Signed operands (opcodes
|
||||
/// 0-5) are ordered by flipping both sign bits and comparing unsigned.
|
||||
fn scalar_compare(opcode: u32, a: u32, b: u32) -> bool {
|
||||
let (a, b) = if opcode < 6 {
|
||||
(a ^ 0x8000_0000, b ^ 0x8000_0000)
|
||||
} else {
|
||||
(a, b)
|
||||
};
|
||||
match opcode % 6 {
|
||||
0 => a == b,
|
||||
1 => a != b,
|
||||
2 => a > b,
|
||||
3 => a >= b,
|
||||
4 => a < b,
|
||||
_ => a <= b,
|
||||
}
|
||||
}
|
||||
|
||||
/// RDNA 2 ISA guide 12.3, evaluated with arithmetic on the value (no host bit
|
||||
/// intrinsics): D and, for NOT, BCNT0, BCNT1 and ABS, SCC = (D != 0).
|
||||
fn scalar_unary(opcode: u32, value: u32) -> (u32, Option<bool>) {
|
||||
// The bits from the LSB, as repeated halving produces them.
|
||||
let mut bits = [false; 32];
|
||||
let mut rest = u64::from(value);
|
||||
for slot in &mut bits {
|
||||
*slot = rest % 2 == 1;
|
||||
rest /= 2;
|
||||
}
|
||||
let word = |bits: &dyn Fn(usize) -> bool| {
|
||||
(0..32).rev().fold(0u64, |w, i| w * 2 + u64::from(bits(i))) as u32
|
||||
};
|
||||
let position = |found: Option<usize>| found.map_or(u32::MAX, |i| i as u32);
|
||||
let ones = bits.iter().filter(|&&b| b).count() as u32;
|
||||
let result = match opcode {
|
||||
7 => 0xffff_ffff - value,
|
||||
11 => word(&|i| bits[31 - i]),
|
||||
13 => 32 - ones,
|
||||
15 => ones,
|
||||
17 => position(bits.iter().position(|&b| !b)),
|
||||
19 => position(bits.iter().position(|&b| b)),
|
||||
21 => position(bits.iter().rev().position(|&b| b)),
|
||||
23 => position(
|
||||
bits.iter()
|
||||
.rev()
|
||||
.skip(1)
|
||||
.position(|&b| b != bits[31])
|
||||
.map(|i| i + 1),
|
||||
),
|
||||
// signext of the low 8 or 16 bits: subtract 2^n when the value mod 2^n
|
||||
// is at least 2^(n-1).
|
||||
25 | 26 => {
|
||||
let span = if opcode == 25 { 256 } else { 65_536 };
|
||||
let low = i64::from(value) % span;
|
||||
let signed = if low >= span / 2 { low - span } else { low };
|
||||
signed.rem_euclid(1 << 32) as u32
|
||||
}
|
||||
// |S0| modulo 2^32, so INT_MIN stays 0x80000000.
|
||||
_ => i64::from(value as i32).abs().rem_euclid(1 << 32) as u32,
|
||||
};
|
||||
let flag = matches!(opcode, 7 | 13 | 15 | 52).then_some(result != 0);
|
||||
(result, flag)
|
||||
}
|
||||
|
||||
fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
|
||||
if reg == 0 {
|
||||
return Err(format!("{offset:#x}: v0 is the resource index"));
|
||||
@@ -786,6 +971,18 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
}
|
||||
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
|
||||
}
|
||||
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15.
|
||||
let sop1_op = (first >> 8) & 0xff;
|
||||
if first >> 23 == 0b1_0111_1101
|
||||
&& matches!(sop1_op, 7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52)
|
||||
{
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(fail("unsupported SOP1 destination"));
|
||||
}
|
||||
let (src, len) = scalar_source(code, offset, first as u8)?;
|
||||
return Ok((Insn::SUnary(sop1_op, dst, src), len));
|
||||
}
|
||||
if first & 0xff80_ff00 == 0xbe80_0300 {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 107 && dst < 126 {
|
||||
@@ -795,7 +992,29 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
return Ok((Insn::SMov(dst, src), len));
|
||||
}
|
||||
// SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22.
|
||||
if first >> 30 == 0b10 && matches!((first >> 23) & 0x7f, 0..=5 | 14 | 16 | 18) {
|
||||
if first >> 30 == 0b10
|
||||
&& matches!(
|
||||
(first >> 23) & 0x7f,
|
||||
0..=10
|
||||
| 14
|
||||
| 16
|
||||
| 18
|
||||
| 20
|
||||
| 22
|
||||
| 24
|
||||
| 26
|
||||
| 28
|
||||
| 30
|
||||
| 32
|
||||
| 34
|
||||
| 36
|
||||
| 38..=40
|
||||
| 44
|
||||
| 46..=49
|
||||
| 53
|
||||
| 54
|
||||
)
|
||||
{
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(fail("unsupported SOP2 destination"));
|
||||
@@ -808,7 +1027,8 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
let (sb, lb) = scalar_source(code, offset, b)?;
|
||||
return Ok((Insn::SAlu((first >> 23) & 0x7f, dst, sa, sb), la.max(lb)));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf06_0000 {
|
||||
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22.
|
||||
if first >> 23 == 0b1_0111_1110 && (first >> 16) & 0x7f <= 11 {
|
||||
let a = first as u8;
|
||||
let b = (first >> 8) as u8;
|
||||
if a == 255 && b == 255 {
|
||||
@@ -816,7 +1036,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
}
|
||||
let (sa, la) = scalar_source(code, offset, a)?;
|
||||
let (sb, lb) = scalar_source(code, offset, b)?;
|
||||
return Ok((Insn::SCmpEq(sa, sb), la.max(lb)));
|
||||
return Ok((Insn::SCmp((first >> 16) & 0x7f, sa, sb), la.max(lb)));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf82_0000 {
|
||||
return Ok((Insn::Branch(branch_target(first, offset)?), 4));
|
||||
|
||||
@@ -768,6 +768,18 @@ mod review {
|
||||
}
|
||||
|
||||
const SCALAR_ALU_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-alu.bin");
|
||||
const SCALAR_LOGIC_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-logic.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-logic.s from the guide's 12.1 pseudocode.
|
||||
const SCALAR_LOGIC_KEY: u32 = 0x887f_00f8;
|
||||
const SCALAR_COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-compare.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-compare.s from the guide's 12.4 pseudocode.
|
||||
const SCALAR_COMPARE_KEY: u32 = 0x0000_0d5b;
|
||||
const SCALAR_UNARY_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-unary.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-unary.s from the guide's 12.3 pseudocode.
|
||||
const SCALAR_UNARY_KEY: u32 = 0x0f00_80f5;
|
||||
const SCALAR_ARITH_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-arith.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-arith.s from the guide's 12.1 pseudocode.
|
||||
const SCALAR_ARITH_KEY: u32 = 0x8115_7dfe;
|
||||
// SOP2 opcodes of the supported subset (RDNA 2 XML opcode table).
|
||||
const SOP2_OPCODES: [u32; 9] = [0, 1, 2, 3, 4, 5, 14, 16, 18];
|
||||
const SCALAR_VALUES: [u32; 10] = [
|
||||
@@ -869,6 +881,70 @@ mod review {
|
||||
verify(&nonzero, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_logic_fixture_chains_registry_logical_and_shift_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_LOGIC_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
|
||||
verify(SCALAR_LOGIC_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_LOGIC_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_ashr_i32 s17, s15, 31"));
|
||||
// The SCC-zero edge is observable: with a shift count of 30 instead of
|
||||
// 31, s17 = 0x787ffff8 >> 30 = 1, SCC = 1, and v2 = 0.
|
||||
let mut nonzero = SCALAR_LOGIC_FIXTURE.to_vec();
|
||||
let at = nonzero
|
||||
.windows(4)
|
||||
.position(|word| word == [0x0f, 0x9f, 0x11, 0x91])
|
||||
.unwrap();
|
||||
nonzero[at + 1] = 0x9e;
|
||||
verify(&nonzero, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_fixture_records_every_registry_compare() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_COMPARE_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
|
||||
verify(SCALAR_COMPARE_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_COMPARE_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_fixture_chains_registry_unary_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_UNARY_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
|
||||
verify(SCALAR_UNARY_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_UNARY_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_abs_i32 s20, 0"));
|
||||
// SCC stays clear across the SEXT and FF1 that follow s_abs_i32 s20, 0:
|
||||
// with s_abs_i32 s20, 1 instead, SCC = 1 and v2 = 0.
|
||||
let mut set = SCALAR_UNARY_FIXTURE.to_vec();
|
||||
let at = set
|
||||
.windows(4)
|
||||
.position(|word| word == [0x80, 0x34, 0x94, 0xbe])
|
||||
.unwrap();
|
||||
set[at] = 0x81;
|
||||
verify(&set, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_arith_fixture_chains_registry_arithmetic_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_ARITH_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_ARITH_KEY).collect();
|
||||
verify(SCALAR_ARITH_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_ARITH_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_lshl2_add_u32 s25, s9, s9"));
|
||||
// SCC stays clear across the CSELECT and MUL_HI that follow
|
||||
// s_lshl2_add_u32 s25, s9, s9: with s_lshl2_add_u32 s25, s9, -1 instead,
|
||||
// 20 + 0xffffffff carries, SCC = 1 and v2 = 0.
|
||||
let mut set = SCALAR_ARITH_FIXTURE.to_vec();
|
||||
let at = set
|
||||
.windows(4)
|
||||
.position(|word| word == [0x09, 0x09, 0x99, 0x97])
|
||||
.unwrap();
|
||||
set[at + 1] = 0xc1;
|
||||
verify(&set, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
/// The translator's own folding: v2 = D as a constant, and the SCC-zero edge
|
||||
/// is taken exactly when SCC is clear.
|
||||
fn assert_translated(code: &[u8], expected: &[u32; 2]) {
|
||||
@@ -1020,8 +1096,8 @@ mod review {
|
||||
#[test]
|
||||
fn scalar_alu_rejects_forms_outside_the_subset() {
|
||||
// load 8, wait 4, two literal moves 8 each, s_cmp 4: the SOP2 word is at 0x20.
|
||||
for opcode in [6, 15, 17, 19] {
|
||||
// s_min_i32 and the 64-bit bitwise forms.
|
||||
for opcode in [11, 15, 17, 19] {
|
||||
// s_cselect_b64 and the 64-bit bitwise forms.
|
||||
rejected_at(
|
||||
&sop2_program(&[sop2(opcode, 10, 8, 9)], 10, 1, 2, Some(false)),
|
||||
0x20,
|
||||
@@ -1089,6 +1165,14 @@ mod review {
|
||||
let input: Vec<u32> = (0..64).map(|lane| lane * 0x0101_0101).collect();
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ 0x0000_000e).collect();
|
||||
assert_eq!(run(SCALAR_ALU_FIXTURE, &input), expected);
|
||||
let logic: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
|
||||
assert_eq!(run(SCALAR_LOGIC_FIXTURE, &input), logic);
|
||||
let compares: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
|
||||
assert_eq!(run(SCALAR_COMPARE_FIXTURE, &input), compares);
|
||||
let unary: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
|
||||
assert_eq!(run(SCALAR_UNARY_FIXTURE, &input), unary);
|
||||
let arith: Vec<_> = input.iter().map(|word| word ^ SCALAR_ARITH_KEY).collect();
|
||||
assert_eq!(run(SCALAR_ARITH_FIXTURE, &input), arith);
|
||||
let mut vectors = sop2_vectors();
|
||||
vectors.extend(sop2_operand_cases());
|
||||
vectors.extend(signed_immediate_overflows());
|
||||
@@ -1097,7 +1181,7 @@ mod review {
|
||||
}
|
||||
eprintln!(
|
||||
"{} SOP2 programs matched on native Metal",
|
||||
vectors.len() + 1
|
||||
vectors.len() + 5
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Operand-domain verification for the supported SOP2 and VOPC forms (part of
|
||||
//! #215, stage E).
|
||||
//!
|
||||
//! Every case runs three ways: the expected value written out below from the
|
||||
//! public AMD "RDNA 2" Instruction Set Architecture Reference Guide, the
|
||||
//! reference interpreter `xenora_ref`, and the translated MSL on native Metal.
|
||||
//! The expected values come only from `oracle`, which imports nothing from the
|
||||
//! ISA crate, the decoder, the shader compiler or the semantic registry, so a
|
||||
//! mistake there cannot also produce the expectation.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
mod harness;
|
||||
#[path = "operand_domains/oracle.rs"]
|
||||
mod oracle;
|
||||
#[path = "operand_domains/sop2.rs"]
|
||||
mod sop2;
|
||||
#[path = "operand_domains/vopc.rs"]
|
||||
mod vopc;
|
||||
|
||||
use harness::{Case, Rejection};
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut all = sop2::cases();
|
||||
all.extend(vopc::cases());
|
||||
all
|
||||
}
|
||||
|
||||
fn rejections() -> Vec<Rejection> {
|
||||
let mut all = sop2::rejections();
|
||||
all.extend(vopc::rejections());
|
||||
all
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operand_domains_match_the_guide_on_the_reference() {
|
||||
let cases = cases();
|
||||
harness::assert_counts(&cases, sop2::COUNTS.iter().chain(vopc::COUNTS));
|
||||
harness::check_reference(&cases).assert_none("reference disagrees with the guide");
|
||||
eprintln!("operand_domains: {} reference cases", cases.len());
|
||||
harness::print_counts(&cases);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_and_truncated_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), sop2::REJECTIONS + vopc::REJECTIONS);
|
||||
harness::check_rejected(&rejections).assert_none("not rejected as the guide requires");
|
||||
eprintln!("operand_domains: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn operand_domains_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
let cases = cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"operand_domains: {} native Metal cases ({programs} distinct programs)",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Running a case on the reference and on Metal. The helpers mirror the ones in
|
||||
//! `known_answers.rs` (copied, not shared, so that file stays untouched).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
use xenora_shader::{Architecture, CompileError, ENTRY_POINT, compile};
|
||||
|
||||
/// One program, its lane input and the guide's expected lane output.
|
||||
pub struct Case {
|
||||
pub form: &'static str,
|
||||
pub family: &'static str,
|
||||
pub label: String,
|
||||
pub code: Vec<u8>,
|
||||
pub input: Vec<u32>,
|
||||
pub expected: Vec<u32>,
|
||||
}
|
||||
|
||||
/// A program every implementation must refuse, at byte `offset`: as truncated
|
||||
/// when `truncated`, else as outside the supported subset.
|
||||
pub struct Rejection {
|
||||
pub family: &'static str,
|
||||
pub truncated: bool,
|
||||
pub label: String,
|
||||
pub code: Vec<u8>,
|
||||
pub offset: usize,
|
||||
}
|
||||
|
||||
pub fn words(code: &[u32]) -> Vec<u8> {
|
||||
code.iter().copied().flat_map(u32::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
/// The cases that failed, grouped by family: the count and the first message.
|
||||
#[derive(Default)]
|
||||
pub struct Failures(BTreeMap<&'static str, (usize, String)>);
|
||||
|
||||
impl Failures {
|
||||
fn record(&mut self, family: &'static str, message: String) {
|
||||
let entry = self.0.entry(family).or_insert((0, message));
|
||||
entry.0 += 1;
|
||||
}
|
||||
|
||||
/// Panics with one line per failing family.
|
||||
pub fn assert_none(&self, what: &str) {
|
||||
let lines: Vec<String> = self
|
||||
.0
|
||||
.iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect();
|
||||
assert!(lines.is_empty(), "{what}:\n{}", lines.join("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_reference(cases: &[Case]) -> Failures {
|
||||
let mut failures = Failures::default();
|
||||
for case in cases {
|
||||
let compiled = compile(Architecture::Gfx1030, &case.code);
|
||||
let reference = xenora_ref::execute(&case.code, &case.input);
|
||||
if compiled.is_err() {
|
||||
failures.record(case.family, format!("{}: {compiled:?}", case.label));
|
||||
} else if reference.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let expected = &case.expected;
|
||||
let message = format!("{}: {reference:?}, expected {expected:?}", case.label);
|
||||
failures.record(case.family, message);
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
pub fn check_rejected(rejections: &[Rejection]) -> Failures {
|
||||
let mut failures = Failures::default();
|
||||
for rejection in rejections {
|
||||
if let Err(message) = rejected_at(rejection) {
|
||||
failures.record(rejection.family, format!("{}: {message}", rejection.label));
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
fn rejected_at(rejection: &Rejection) -> Result<(), String> {
|
||||
let (compiler, compiler_truncated) = match compile(Architecture::Gfx1030, &rejection.code) {
|
||||
Ok(_) => return Err("the compiler accepted it".into()),
|
||||
Err(CompileError::Verify { offset, .. }) => (offset, false),
|
||||
// The decoder crate is not a dependency of this package, so its
|
||||
// `DecodeErrorKind::Truncated` variant is recognised by name.
|
||||
Err(CompileError::Decode(decode)) => (
|
||||
decode.offset,
|
||||
format!("{:?}", decode.kind).starts_with("Truncated "),
|
||||
),
|
||||
Err(other) => return Err(format!("{other:?}")),
|
||||
};
|
||||
let reference = match xenora_ref::execute(&rejection.code, &[0, 1]) {
|
||||
Ok(_) => return Err("the reference accepted it".into()),
|
||||
Err(error) => error,
|
||||
};
|
||||
// The reference names a missing word "truncated ..."; its fall-through
|
||||
// "unsupported or truncated ..." does not say which, and counts as unsupported.
|
||||
let reference_truncated = reference.detail.starts_with("truncated");
|
||||
if compiler != rejection.offset || reference.offset != rejection.offset {
|
||||
return Err(format!(
|
||||
"compiler at {compiler:#x}, reference at {:#x}, expected {:#x}",
|
||||
reference.offset, rejection.offset
|
||||
));
|
||||
}
|
||||
if compiler_truncated != rejection.truncated || reference_truncated != rejection.truncated {
|
||||
return Err(format!(
|
||||
"truncated: compiler {compiler_truncated}, reference {reference_truncated} ({}), \
|
||||
expected {}",
|
||||
reference.detail, rejection.truncated
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs every case on Metal. Cases whose translated MSL and input are identical
|
||||
/// are one program, so each distinct program runs once and its output is
|
||||
/// compared with every case that shares it. The programs are spread over
|
||||
/// `THREADS` threads, each with its own device queue, because pipeline
|
||||
/// compilation dominates the run time. Returns the failures and the number of
|
||||
/// programs.
|
||||
pub fn check_metal(cases: &[Case]) -> (Failures, usize) {
|
||||
const THREADS: usize = 4;
|
||||
let mut programs = BTreeSet::new();
|
||||
let mut failures = Failures::default();
|
||||
let mut keys = Vec::with_capacity(cases.len());
|
||||
for case in cases {
|
||||
match compile(Architecture::Gfx1030, &case.code) {
|
||||
Ok(compiled) => {
|
||||
let key = (compiled.msl, case.input.clone());
|
||||
programs.insert(key.clone());
|
||||
keys.push(Some(key));
|
||||
}
|
||||
Err(error) => {
|
||||
failures.record(case.family, format!("{}: {error:?}", case.label));
|
||||
keys.push(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
let work: Vec<&(String, Vec<u32>)> = programs.iter().collect();
|
||||
let chunk = work.len().div_ceil(THREADS).max(1);
|
||||
let outputs: HashMap<(String, Vec<u32>), Result<Vec<u32>, String>> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = work
|
||||
.chunks(chunk)
|
||||
.map(|part| {
|
||||
s.spawn(move || {
|
||||
let metal = xenora_metal::NativeCompute::new().unwrap();
|
||||
part.iter()
|
||||
.map(|&key| {
|
||||
let output = metal
|
||||
.run_words(&key.0, ENTRY_POINT, &key.1)
|
||||
.map_err(|error| error.to_string());
|
||||
(key.clone(), output)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.flat_map(|handle| handle.join().unwrap())
|
||||
.collect()
|
||||
});
|
||||
for (case, key) in cases.iter().zip(keys) {
|
||||
let Some(key) = key else { continue };
|
||||
match &outputs[&key] {
|
||||
Ok(output) if *output == case.expected => {}
|
||||
Ok(output) => {
|
||||
let expected = &case.expected;
|
||||
let message = format!("{}: {output:?}, expected {expected:?}", case.label);
|
||||
failures.record(case.family, message);
|
||||
}
|
||||
Err(error) => failures.record(case.family, format!("{}: {error}", case.label)),
|
||||
}
|
||||
}
|
||||
(failures, outputs.len())
|
||||
}
|
||||
|
||||
/// The number of cases in each family, which `expected` lists in full.
|
||||
pub fn assert_counts<'a>(
|
||||
cases: &[Case],
|
||||
expected: impl Iterator<Item = &'a (&'static str, usize)>,
|
||||
) {
|
||||
let expected: BTreeMap<_, _> = expected.map(|&(family, n)| (family, n)).collect();
|
||||
assert_eq!(tally(cases, |case| case.family), expected);
|
||||
}
|
||||
|
||||
pub fn print_counts(cases: &[Case]) {
|
||||
for (name, n) in tally(cases, |case| case.form) {
|
||||
eprintln!(" form {name}: {n}");
|
||||
}
|
||||
for (name, n) in tally(cases, |case| case.family) {
|
||||
eprintln!(" family {name}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Expected results transcribed from the AMD "RDNA 2" Instruction Set
|
||||
//! Architecture Reference Guide (30 November 2020). Section numbers refer to
|
||||
//! that guide. Nothing here comes from Xenora's own decoder, ISA tables,
|
||||
//! compiler or semantic registry.
|
||||
|
||||
/// The SOP2 forms under test with their opcode numbers (guide 12.1).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Sop2 {
|
||||
AddU32 = 0,
|
||||
SubU32 = 1,
|
||||
AddI32 = 2,
|
||||
SubI32 = 3,
|
||||
AddcU32 = 4,
|
||||
SubbU32 = 5,
|
||||
AndB32 = 14,
|
||||
OrB32 = 16,
|
||||
XorB32 = 18,
|
||||
}
|
||||
|
||||
pub const SOP2_FORMS: [(Sop2, &str); 9] = [
|
||||
(Sop2::AddU32, "s_add_u32"),
|
||||
(Sop2::SubU32, "s_sub_u32"),
|
||||
(Sop2::AddI32, "s_add_i32"),
|
||||
(Sop2::SubI32, "s_sub_i32"),
|
||||
(Sop2::AddcU32, "s_addc_u32"),
|
||||
(Sop2::SubbU32, "s_subb_u32"),
|
||||
(Sop2::AndB32, "s_and_b32"),
|
||||
(Sop2::OrB32, "s_or_b32"),
|
||||
(Sop2::XorB32, "s_xor_b32"),
|
||||
];
|
||||
|
||||
fn bit31(value: u32) -> bool {
|
||||
value >> 31 == 1
|
||||
}
|
||||
|
||||
/// D and SCC as guide 12.1 writes them; `scc` is the SCC value before the
|
||||
/// instruction. The `>= 0x100000000ULL` tests are evaluated in 64 bits, as the
|
||||
/// ULL constant says.
|
||||
pub fn sop2(op: Sop2, s0: u32, s1: u32, scc: bool) -> (u32, bool) {
|
||||
let (a, b, c) = (u64::from(s0), u64::from(s1), u64::from(scc));
|
||||
match op {
|
||||
// D.u32 = S0.u32 + S1.u32; SCC = S0.u32 + S1.u32 >= 0x100000000ULL.
|
||||
Sop2::AddU32 => (s0.wrapping_add(s1), a + b >= 0x1_0000_0000),
|
||||
// D.u = S0.u - S1.u; SCC = (S1.u > S0.u).
|
||||
Sop2::SubU32 => (s0.wrapping_sub(s1), s1 > s0),
|
||||
// D.i = S0.i + S1.i; SCC = (S0.u[31] == S1.u[31] && S0.u[31] != D.u[31]).
|
||||
Sop2::AddI32 => {
|
||||
let d = s0.wrapping_add(s1);
|
||||
(d, bit31(s0) == bit31(s1) && bit31(s0) != bit31(d))
|
||||
}
|
||||
// D.i = S0.i - S1.i; SCC = (S0.u[31] != S1.u[31] && S0.u[31] != D.u[31]).
|
||||
Sop2::SubI32 => {
|
||||
let d = s0.wrapping_sub(s1);
|
||||
(d, bit31(s0) != bit31(s1) && bit31(s0) != bit31(d))
|
||||
}
|
||||
// D.u32 = S0.u32 + S1.u32 + SCC; SCC = S0.u32 + S1.u32 + SCC >= 0x100000000ULL.
|
||||
Sop2::AddcU32 => (
|
||||
s0.wrapping_add(s1).wrapping_add(u32::from(scc)),
|
||||
a + b + c >= 0x1_0000_0000,
|
||||
),
|
||||
// D.u = S0.u - S1.u - SCC; SCC = (S1.u + SCC > S0.u), "unsigned overflow".
|
||||
// The guide does not say whether S1.u + SCC wraps at 32 bits. It is read
|
||||
// here at full width: only then does SCC report the borrow out of the
|
||||
// subtraction, which the comment names. This decides only S1 = 0xffffffff
|
||||
// with SCC set; `sop2::cases` keeps those in their own family.
|
||||
Sop2::SubbU32 => (s0.wrapping_sub(s1).wrapping_sub(u32::from(scc)), b + c > a),
|
||||
// D = S0 & S1, S0 | S1, S0 ^ S1; SCC = (D != 0).
|
||||
Sop2::AndB32 => (s0 & s1, s0 & s1 != 0),
|
||||
Sop2::OrB32 => (s0 | s1, s0 | s1 != 0),
|
||||
Sop2::XorB32 => (s0 ^ s1, s0 ^ s1 != 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Integer inline constants (guide 5.2, scalar source operand table): codes
|
||||
/// 128-192 are 0..=64 and codes 193-208 are -1..=-16.
|
||||
pub fn inline_integer(code: u32) -> Option<u32> {
|
||||
match code {
|
||||
128..=192 => Some(code - 128),
|
||||
193..=208 => Some((192_i32 - code as i32) as u32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Literal constant code: one 32-bit word follows the instruction (guide 5.2).
|
||||
pub const LITERAL: u32 = 255;
|
||||
|
||||
/// The VOPC integer compares (guide 12.9): V_CMP_{LT,EQ,LE,GT,NE,GE}_I32 are
|
||||
/// opcodes 129-134 and the _U32 forms 193-198.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Compare {
|
||||
pub opcode: u32,
|
||||
pub name: &'static str,
|
||||
}
|
||||
|
||||
pub const COMPARES: [Compare; 12] = [
|
||||
Compare {
|
||||
opcode: 129,
|
||||
name: "v_cmp_lt_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 130,
|
||||
name: "v_cmp_eq_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 131,
|
||||
name: "v_cmp_le_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 132,
|
||||
name: "v_cmp_gt_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 133,
|
||||
name: "v_cmp_ne_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 134,
|
||||
name: "v_cmp_ge_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 193,
|
||||
name: "v_cmp_lt_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 194,
|
||||
name: "v_cmp_eq_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 195,
|
||||
name: "v_cmp_le_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 196,
|
||||
name: "v_cmp_gt_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 197,
|
||||
name: "v_cmp_ne_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 198,
|
||||
name: "v_cmp_ge_u32",
|
||||
},
|
||||
];
|
||||
|
||||
/// "D[threadId] = (S0 < S1)" and so on (guide 12.9), with I32 operands read as
|
||||
/// two's complement and U32 operands as unsigned (chapter 12 suffix rules).
|
||||
pub fn compare(form: Compare, s0: u32, s1: u32) -> bool {
|
||||
let signed = form.name.ends_with("_i32");
|
||||
let order = if signed {
|
||||
(s0 as i32).cmp(&(s1 as i32))
|
||||
} else {
|
||||
s0.cmp(&s1)
|
||||
};
|
||||
match &form.name[6..8] {
|
||||
"lt" => order.is_lt(),
|
||||
"eq" => order.is_eq(),
|
||||
"le" => order.is_le(),
|
||||
"gt" => order.is_gt(),
|
||||
"ne" => order.is_ne(),
|
||||
"ge" => order.is_ge(),
|
||||
other => unreachable!("{other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// VCC for one Wave32 wave (guide 3.9): "VCC[n] = EXEC[n] & (test passed for
|
||||
/// thread[n])", and "VCC is fully written", so inactive lanes read 0.
|
||||
pub fn vcc(exec: u32, passed: impl Fn(usize) -> bool) -> u32 {
|
||||
(0..32)
|
||||
.filter(|&lane| exec >> lane & 1 == 1 && passed(lane))
|
||||
.fold(0, |mask, lane| mask | 1 << lane)
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! SOP2 programs: the operands start in SGPRs (or as inline or literal
|
||||
//! sources), SCC is set or cleared first, and the result reaches the output as
|
||||
//! v2 = D, XORed with the lane input only when SCC is set afterwards. With the
|
||||
//! lane input [0, 0xffffffff] the output is [D, D] or [D, !D].
|
||||
|
||||
use super::harness::{Case, Rejection, words};
|
||||
use super::oracle::{self, LITERAL, SOP2_FORMS, Sop2, sop2 as expect};
|
||||
|
||||
/// Boundary operands: zero, one, signed max/min and min + 1, unsigned max and
|
||||
/// max - 1, and an ordinary pattern.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
u32::MAX,
|
||||
0x1234_5678,
|
||||
];
|
||||
const LITERALS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x1234_5678];
|
||||
/// 64-bit operands for add/addc and sub/subb chains.
|
||||
const WIDE: [u64; 6] = [
|
||||
0,
|
||||
1,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x8000_0000_0000_0000,
|
||||
u64::MAX,
|
||||
];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
pub const COUNTS: &[(&str, usize)] = &[
|
||||
("sop2 domain", 9 * 8 * 8 * 2 - 8),
|
||||
("sop2 subb full-width borrow", 8),
|
||||
("sop2 carry chain", 2 * 6 * 6 * 2 * 2),
|
||||
("sop2 aliasing", 9 * 5 * 2),
|
||||
("sop2 inline integer", 9 * 81 * 2),
|
||||
("sop2 literal", 9 * 6 * 2 * 2),
|
||||
("sop2 max register", 9 * 4),
|
||||
];
|
||||
/// Two literals, 21 special destinations, 9 float inline codes in two slots,
|
||||
/// and a missing literal word in two slots, for each of the 9 forms.
|
||||
pub const REJECTIONS: usize = 9 * (1 + 21 + 9 * 2 + 2);
|
||||
/// The SOP2 word's offset: load 8, wait 4, two literal moves 8 each, s_cmp 4.
|
||||
const ALU_OFFSET: usize = 0x20;
|
||||
|
||||
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.1).
|
||||
pub fn sop2(op: Sop2, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
0x8000_0000 | (op as u32) << 23 | dst << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// `s_mov_b32 s<reg>, literal` (SOP1 opcode 3).
|
||||
fn mov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0xbe80_03ff | reg << 16, value]
|
||||
}
|
||||
|
||||
/// The program around `alu`: `init` sets SGPRs, SCC = `scc`, then `alu`, then
|
||||
/// v2 = s<result>, XORed with v1 when SCC is set.
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init {
|
||||
code.extend(mov(reg, value));
|
||||
}
|
||||
// s_cmp_eq_u32 0, 0 sets SCC; s_cmp_eq_u32 0, 1 clears it.
|
||||
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn lanes((d, scc): (u32, bool)) -> Vec<u32> {
|
||||
vec![d, if scc { !d } else { d }]
|
||||
}
|
||||
|
||||
fn case(
|
||||
form: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
Case {
|
||||
form,
|
||||
family,
|
||||
label: format!("{form} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: lanes(out),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (op, name) in SOP2_FORMS {
|
||||
let alu = [sop2(op, 10, 8, 9)];
|
||||
for a in VALUES {
|
||||
for b in VALUES {
|
||||
for scc in [false, true] {
|
||||
let family = if op == Sop2::SubbU32 && b == u32::MAX && scc {
|
||||
"sop2 subb full-width borrow"
|
||||
} else {
|
||||
"sop2 domain"
|
||||
};
|
||||
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
family,
|
||||
format!("{a:#x}, {b:#x}, scc {scc}"),
|
||||
code,
|
||||
expect(op, a, b, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// dst/src aliasing, SCC set: (dst, src0, src1) with s8 = a, s9 = b.
|
||||
for (a, b) in [(0xffff_fff0, 0x11), (0x8000_0000, 0x8000_0000)] {
|
||||
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
|
||||
let pick = |reg| if reg == 8 { a } else { b };
|
||||
let code = program(&[(8, a), (9, b)], true, &[sop2(op, dst, src0, src1)], dst);
|
||||
let out = expect(op, pick(src0), pick(src1), true);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 aliasing",
|
||||
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Every integer inline constant in each source slot, s8 = 0xfffffff0, SCC set.
|
||||
let a = 0xffff_fff0;
|
||||
for code_point in (128..=208).filter_map(|c| oracle::inline_integer(c).map(|v| (c, v))) {
|
||||
let (selector, value) = code_point;
|
||||
for slot in 0..2 {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(op, 10, selector, 8), expect(op, value, a, true))
|
||||
} else {
|
||||
(sop2(op, 10, 8, selector), expect(op, a, value, true))
|
||||
};
|
||||
let code = program(&[(8, a), (9, 0)], true, &[alu], 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 inline integer",
|
||||
format!("inline {selector} ({value:#x}) slot {slot}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
// A literal word in each source slot, with SCC clear.
|
||||
for a in [1, 0x8000_0000] {
|
||||
for literal in LITERALS {
|
||||
for slot in 0..2 {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(op, 10, LITERAL, 8), expect(op, literal, a, false))
|
||||
} else {
|
||||
(sop2(op, 10, 8, LITERAL), expect(op, a, literal, false))
|
||||
};
|
||||
let code = program(&[(8, a), (9, 0)], false, &[alu, literal], 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 literal",
|
||||
format!("literal {literal:#x} slot {slot}, s8 {a:#x}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// s105, the highest SGPR a SOP2 operand may name (guide 5.2), as
|
||||
// destination and source; s105 = a, s8 = s9 = b, SCC set.
|
||||
let (a, b) = (0x8000_0001, u32::MAX);
|
||||
for (dst, src0, src1) in [(105, 105, 9), (105, 8, 105), (105, 105, 105), (8, 105, 9)] {
|
||||
let pick = |reg| if reg == 105 { a } else { b };
|
||||
let code = program(
|
||||
&[(105, a), (8, b), (9, b)],
|
||||
true,
|
||||
&[sop2(op, dst, src0, src1)],
|
||||
dst,
|
||||
);
|
||||
let out = expect(op, pick(src0), pick(src1), true);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 max register",
|
||||
format!("s{dst} = s{src0}, s{src1}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
cases.extend(chains());
|
||||
cases
|
||||
}
|
||||
|
||||
/// 64-bit add and subtract built from the u32 forms: low word with
|
||||
/// s_add_u32/s_sub_u32, high word with s_addc_u32/s_subb_u32 consuming its
|
||||
/// SCC. SCC is preset both ways first to show the low form overwrites it. Each
|
||||
/// chain runs twice, outputting the low word and then the high word, both with
|
||||
/// the final SCC. The expected words and SCC follow the guide; they are also
|
||||
/// checked against 64-bit arithmetic here.
|
||||
fn chains() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (low, high, name) in [
|
||||
(Sop2::AddU32, Sop2::AddcU32, "s_addc_u32"),
|
||||
(Sop2::SubU32, Sop2::SubbU32, "s_subb_u32"),
|
||||
] {
|
||||
for x in WIDE {
|
||||
for y in WIDE {
|
||||
for preset in [false, true] {
|
||||
let (xl, xh, yl, yh) = (x as u32, (x >> 32) as u32, y as u32, (y >> 32) as u32);
|
||||
let (d_low, carry) = expect(low, xl, yl, preset);
|
||||
let (d_high, scc) = expect(high, xh, yh, carry);
|
||||
let exact = if low == Sop2::AddU32 {
|
||||
(x.wrapping_add(y), x.checked_add(y).is_none())
|
||||
} else {
|
||||
(x.wrapping_sub(y), y > x)
|
||||
};
|
||||
let joined = u64::from(d_high) << 32 | u64::from(d_low);
|
||||
assert_eq!((joined, scc), exact, "{x:#x} {y:#x}");
|
||||
let alu = [sop2(low, 12, 8, 9), sop2(high, 13, 10, 11)];
|
||||
let init = [(8, xl), (9, yl), (10, xh), (11, yh)];
|
||||
for (word, d) in [("low", d_low), ("high", d_high)] {
|
||||
let result = if word == "low" { 12 } else { 13 };
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 carry chain",
|
||||
format!("{x:#x}, {y:#x}, preset {preset}, {word} word"),
|
||||
program(&init, preset, &alu, result),
|
||||
(d, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
pub fn rejections() -> Vec<Rejection> {
|
||||
let mut rejections = Vec::new();
|
||||
let reject = |family, label: String, alu: &[u32]| Rejection {
|
||||
family,
|
||||
truncated: false,
|
||||
label,
|
||||
code: program(&[(8, 1), (9, 2)], false, alu, 10),
|
||||
offset: ALU_OFFSET,
|
||||
};
|
||||
for (op, name) in SOP2_FORMS {
|
||||
// Both sources select the literal. The guide allows at most one literal
|
||||
// constant per instruction; whether two selectors may share one word is
|
||||
// not stated, and Xenora's subset rejects it.
|
||||
rejections.push(reject(
|
||||
"sop2 two literals",
|
||||
format!("{name} two literals"),
|
||||
&[sop2(op, 10, LITERAL, LITERAL), 3, 3],
|
||||
));
|
||||
// VCC_LO, VCC_HI, TTMP0-15, M0, EXEC_LO, EXEC_HI as destination. The
|
||||
// guide lists these as scalar destinations; Xenora's SOP2 subset writes
|
||||
// only s0-s105, so these are rejections of the subset, not of the guide.
|
||||
for dst in (106..=123).chain([124, 126, 127]) {
|
||||
rejections.push(reject(
|
||||
"sop2 special destination",
|
||||
format!("{name} dst {dst}"),
|
||||
&[sop2(op, dst, 8, 9)],
|
||||
));
|
||||
}
|
||||
// Float inline constants 0.5 .. -4.0 and 1/(2*pi) (codes 240-248). The
|
||||
// guide defines them for every source; Xenora's subset rejects them for
|
||||
// these integer forms.
|
||||
for selector in 240..=248 {
|
||||
rejections.push(reject(
|
||||
"sop2 float inline",
|
||||
format!("{name} float inline {selector} src0"),
|
||||
&[sop2(op, 10, selector, 8)],
|
||||
));
|
||||
rejections.push(reject(
|
||||
"sop2 float inline",
|
||||
format!("{name} float inline {selector} src1"),
|
||||
&[sop2(op, 10, 8, selector)],
|
||||
));
|
||||
}
|
||||
// The stream ends where the literal word should be.
|
||||
for (slot, alu) in [(0, sop2(op, 10, LITERAL, 8)), (1, sop2(op, 10, 8, LITERAL))] {
|
||||
let mut code = program(&[(8, 1), (9, 2)], false, &[], 10);
|
||||
code.truncate(ALU_OFFSET);
|
||||
code.extend(alu.to_le_bytes());
|
||||
rejections.push(Rejection {
|
||||
family: "sop2 missing literal",
|
||||
truncated: true,
|
||||
label: format!("{name} missing literal slot {slot}"),
|
||||
code,
|
||||
offset: ALU_OFFSET,
|
||||
});
|
||||
}
|
||||
}
|
||||
rejections
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! VOPC programs on one Wave32 wave: v1 = lane input, v3 (or v255) = a literal
|
||||
//! `b`, an optional EXEC mask around the compare, then every lane outputs
|
||||
//! VCC_LO. The 32 lane inputs are distinct, so a mask bit landing in the wrong
|
||||
//! lane changes the output.
|
||||
//!
|
||||
//! Not covered: whether a compare also writes EXEC. The supported subset has
|
||||
//! no instruction that reads EXEC back, so the EXEC cases restore it before
|
||||
//! the output move.
|
||||
|
||||
use super::harness::{Case, Rejection, words};
|
||||
use super::oracle::{COMPARES, Compare, LITERAL, compare, inline_integer, vcc};
|
||||
|
||||
/// Boundary operands, also the first ten lane inputs: zero, one, signed max - 1
|
||||
/// and max, signed min and min + 1, -16, unsigned max - 1 and max, and a
|
||||
/// pattern.
|
||||
const VALUES: [u32; 10] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fff0,
|
||||
0xffff_fffe,
|
||||
u32::MAX,
|
||||
0x0f0f_0f0f,
|
||||
];
|
||||
/// The other 22 lane inputs: more values near the boundaries and patterns.
|
||||
const MORE_LANES: [u32; 22] = [
|
||||
2,
|
||||
3,
|
||||
15,
|
||||
16,
|
||||
63,
|
||||
64,
|
||||
65,
|
||||
0x7fff_fffd,
|
||||
0x8000_0002,
|
||||
0xffff_fffd,
|
||||
0xffff_ffef,
|
||||
0xffff_fff1,
|
||||
0x4000_0000,
|
||||
0xc000_0000,
|
||||
0x0000_ffff,
|
||||
0xffff_0000,
|
||||
0x1234_5678,
|
||||
0x8765_4321,
|
||||
0x00ff_00ff,
|
||||
0xff00_ff00,
|
||||
0x5555_5555,
|
||||
0xaaaa_aaaa,
|
||||
];
|
||||
const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX];
|
||||
const EXEC_MASKS: [u32; 5] = [0, 0x5555_5555, 0xaaaa_aaaa, 0x8000_0001, 0x0000_ffff];
|
||||
|
||||
pub const COUNTS: &[(&str, usize)] = &[
|
||||
("vopc domain", 12 * 10 * 2),
|
||||
("vopc aliasing", 12),
|
||||
("vopc inline integer", 12 * 81),
|
||||
("vopc literal", 12 * 5),
|
||||
("vopc sgpr source", 12 * 2 * 2),
|
||||
("vopc max register", 12 * 2),
|
||||
("vopc exec mask", 12 * 5),
|
||||
("vopc vccz", 12 * 11),
|
||||
];
|
||||
/// A missing literal word and 9 float inline codes (defined by the guide, outside
|
||||
/// Xenora's subset for integer compares), for each of the 12 forms.
|
||||
pub const REJECTIONS: usize = 12 * (1 + 9);
|
||||
/// The compare's offset: load 8, wait 4, v_mov with literal 8.
|
||||
const COMPARE_OFFSET: usize = 0x14;
|
||||
|
||||
/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8
|
||||
/// (guide 13.3.3); SRC0 256 + n is VGPR n.
|
||||
fn vopc(opcode: u32, src0: u32, vsrc1: u32) -> u32 {
|
||||
0x7c00_0000 | opcode << 17 | vsrc1 << 9 | src0
|
||||
}
|
||||
|
||||
const fn vgpr(n: u32) -> u32 {
|
||||
256 + n
|
||||
}
|
||||
|
||||
/// `v_mov_b32 v<reg>, literal` (VOP1 opcode 1).
|
||||
fn vmov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0x7e00_02ff | reg << 17, value]
|
||||
}
|
||||
|
||||
/// `s_mov_b32 vcc_lo, 0xffffffff`, so a compare that leaves bits untouched
|
||||
/// shows up.
|
||||
const SEED_VCC: [u32; 2] = [0xbeea_03ff, u32::MAX];
|
||||
/// `s_mov_b32 exec_lo, literal` and `s_mov_b32 exec_lo, -1`.
|
||||
const SET_EXEC: u32 = 0xbefe_03ff;
|
||||
const FULL_EXEC: u32 = 0xbefe_03c1;
|
||||
/// After v2 = VCC_LO: `s_cbranch_vccz` over `v_xor_b32 v2, v1, v2`.
|
||||
const VCCZ_TAIL: [u32; 2] = [0xbf86_0001, 0x3a04_0501];
|
||||
|
||||
/// Load v1, v<breg> = b, then `before`, the compare words, `after`, and every
|
||||
/// lane outputs VCC_LO.
|
||||
fn program(breg: u32, b: u32, before: &[u32], compare: &[u32], after: &[u32]) -> Vec<u8> {
|
||||
program_with_tail(breg, b, before, compare, after, &[])
|
||||
}
|
||||
|
||||
/// As `program`, with `tail` between the output move and the store.
|
||||
fn program_with_tail(
|
||||
breg: u32,
|
||||
b: u32,
|
||||
before: &[u32],
|
||||
compare: &[u32],
|
||||
after: &[u32],
|
||||
tail: &[u32],
|
||||
) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
code.extend(vmov(breg, b));
|
||||
code.extend(before);
|
||||
code.extend(compare);
|
||||
code.extend(after);
|
||||
code.push(0x7e04_026a);
|
||||
code.extend(tail);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn lanes() -> Vec<u32> {
|
||||
VALUES.iter().chain(&MORE_LANES).copied().collect()
|
||||
}
|
||||
|
||||
fn case(form: Compare, family: &'static str, label: String, code: Vec<u8>, mask: u32) -> Case {
|
||||
Case {
|
||||
form: form.name,
|
||||
family,
|
||||
label: format!("{} {label}", form.name),
|
||||
code,
|
||||
input: lanes(),
|
||||
expected: vec![mask; 32],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let input = lanes();
|
||||
let all = u32::MAX;
|
||||
let mut cases = Vec::new();
|
||||
for form in COMPARES {
|
||||
let op = form.opcode;
|
||||
for b in VALUES {
|
||||
let code = program(3, b, &[], &[vopc(op, vgpr(1), 3)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
cases.push(case(form, "vopc domain", format!("v1, {b:#x}"), code, mask));
|
||||
let code = program(3, b, &[], &[vopc(op, vgpr(3), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, b, input[n]));
|
||||
cases.push(case(form, "vopc domain", format!("{b:#x}, v1"), code, mask));
|
||||
}
|
||||
let code = program(3, 0, &[], &[vopc(op, vgpr(1), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], input[n]));
|
||||
cases.push(case(form, "vopc aliasing", "v1, v1".into(), code, mask));
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector).unwrap();
|
||||
let code = program(3, 0, &[], &[vopc(op, selector, 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, value, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc inline integer",
|
||||
format!("inline {selector} ({value:#x})"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
for literal in LITERALS {
|
||||
let code = program(3, 0, &[], &[vopc(op, LITERAL, 1), literal], &[]);
|
||||
let mask = vcc(all, |n| compare(form, literal, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc literal",
|
||||
format!("literal {literal:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
// SGPR source s8 and s105, the highest SGPR (guide 5.2).
|
||||
for reg in [8, 105] {
|
||||
for value in [0x8000_0000, 0xffff_fff0] {
|
||||
let set = [0xbe80_03ff | reg << 16, value];
|
||||
let code = program(3, 0, &set, &[vopc(op, reg, 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, value, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc sgpr source",
|
||||
format!("s{reg} = {value:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
}
|
||||
// v255, the highest VGPR, in each slot.
|
||||
let b = 0x8000_0001;
|
||||
let code = program(255, b, &[], &[vopc(op, vgpr(1), 255)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc max register",
|
||||
"v1, v255".into(),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
let code = program(255, b, &[], &[vopc(op, vgpr(255), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, b, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc max register",
|
||||
"v255, v1".into(),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
// Partial and empty EXEC around the compare, with VCC_LO = -1 before
|
||||
// it, so inactive lanes must be cleared ("VCC is fully written");
|
||||
// EXEC_LO = -1 again before the output move so every lane stores VCC_LO.
|
||||
let b = 0x8000_0000;
|
||||
for exec in EXEC_MASKS {
|
||||
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, exec];
|
||||
let code = program(3, b, &before, &[vopc(op, vgpr(1), 3)], &[FULL_EXEC]);
|
||||
let mask = vcc(exec, |n| compare(form, input[n], b));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc exec mask",
|
||||
format!("exec {exec:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
// VCCZ after the compare (guide 3.9: VCCZ is VCC == 0), read with
|
||||
// s_cbranch_vccz: lanes output VCC_LO when it is zero, else input ^ VCC_LO.
|
||||
let vccz = |mask: u32| -> Vec<u32> {
|
||||
if mask == 0 {
|
||||
vec![0; 32]
|
||||
} else {
|
||||
input.iter().map(|lane| lane ^ mask).collect()
|
||||
}
|
||||
};
|
||||
for b in VALUES {
|
||||
let code = program_with_tail(3, b, &[], &[vopc(op, vgpr(1), 3)], &[], &VCCZ_TAIL);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
let mut case = case(form, "vopc vccz", format!("v1, {b:#x}"), code, mask);
|
||||
case.expected = vccz(mask);
|
||||
cases.push(case);
|
||||
}
|
||||
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, 0];
|
||||
let compare_words = [vopc(op, vgpr(1), 3)];
|
||||
let code = program_with_tail(3, 0, &before, &compare_words, &[FULL_EXEC], &VCCZ_TAIL);
|
||||
let mut case = case(form, "vopc vccz", "exec 0".into(), code, 0);
|
||||
case.expected = vccz(0);
|
||||
cases.push(case);
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
pub fn rejections() -> Vec<Rejection> {
|
||||
let mut rejections = Vec::new();
|
||||
for form in COMPARES {
|
||||
let mut code = program(3, 0, &[], &[], &[]);
|
||||
code.truncate(COMPARE_OFFSET);
|
||||
code.extend(vopc(form.opcode, LITERAL, 1).to_le_bytes());
|
||||
rejections.push(Rejection {
|
||||
family: "vopc missing literal",
|
||||
truncated: true,
|
||||
label: format!("{} missing literal", form.name),
|
||||
code,
|
||||
offset: COMPARE_OFFSET,
|
||||
});
|
||||
for selector in 240..=248 {
|
||||
rejections.push(Rejection {
|
||||
family: "vopc float inline",
|
||||
truncated: false,
|
||||
label: format!("{} float inline {selector}", form.name),
|
||||
code: program(3, 0, &[], &[vopc(form.opcode, selector, 1)], &[]),
|
||||
offset: COMPARE_OFFSET,
|
||||
});
|
||||
}
|
||||
}
|
||||
rejections
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for eleven 32-bit SOP1 unary forms (#215):
|
||||
//! `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
|
||||
//! `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
|
||||
//! `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.3 "SOP1 Instructions"
|
||||
//! (pseudocode and functional examples), Tables 12 and 14 in section 5 (which
|
||||
//! forms set SCC), section 13.1.3 for the SOP1 word and the scalar operand
|
||||
//! table for inline integer constants. Nothing here comes from the ISA crate,
|
||||
//! the semantic registry, the decoder or the shader compiler. Every case runs
|
||||
//! on the reference interpreter `xenora_ref` and on the second interpreter
|
||||
//! `independent_ref`; the ignored test also runs the translated MSL on native
|
||||
//! Metal.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
use xenora_shader::{Architecture, CompileError, compile};
|
||||
|
||||
/// The eleven forms with their ENC_SOP1 opcodes (guide 12.3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Form {
|
||||
Not = 7,
|
||||
Brev = 11,
|
||||
Bcnt0 = 13,
|
||||
Bcnt1 = 15,
|
||||
Ff0 = 17,
|
||||
Ff1 = 19,
|
||||
FlbitB32 = 21,
|
||||
FlbitI32 = 23,
|
||||
SextI8 = 25,
|
||||
SextI16 = 26,
|
||||
Abs = 52,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 11] = [
|
||||
(Form::Not, "s_not_b32"),
|
||||
(Form::Brev, "s_brev_b32"),
|
||||
(Form::Bcnt0, "s_bcnt0_i32_b32"),
|
||||
(Form::Bcnt1, "s_bcnt1_i32_b32"),
|
||||
(Form::Ff0, "s_ff0_i32_b32"),
|
||||
(Form::Ff1, "s_ff1_i32_b32"),
|
||||
(Form::FlbitB32, "s_flbit_i32_b32"),
|
||||
(Form::FlbitI32, "s_flbit_i32"),
|
||||
(Form::SextI8, "s_sext_i32_i8"),
|
||||
(Form::SextI16, "s_sext_i32_i16"),
|
||||
(Form::Abs, "s_abs_i32"),
|
||||
];
|
||||
|
||||
fn bit(value: u32, i: u32) -> bool {
|
||||
(value >> i) & 1 == 1
|
||||
}
|
||||
|
||||
/// The guide's D for `form` with S0 = `s0`, and the SCC after it: `Some` for
|
||||
/// the forms that write SCC, `None` for those that leave it unchanged. No form
|
||||
/// reads SCC.
|
||||
fn expect(form: Form, s0: u32) -> (u32, Option<bool>) {
|
||||
// Tables 12 and 14: NOT, BCNT0, BCNT1 and ABS set SCC ("SCC = (D != 0)",
|
||||
// "SCC=result not zero"); BREV, FF0, FF1, FLBIT and SEXT have "n".
|
||||
let not_zero = |d: u32| (d, Some(d != 0));
|
||||
match form {
|
||||
// 7 S_NOT_B32: D = ~S0; SCC = (D != 0).
|
||||
Form::Not => not_zero(!s0),
|
||||
// 11 S_BREV_B32: D.u[31:0] = S0.u[0:31].
|
||||
Form::Brev => (
|
||||
(0..32).fold(0, |d, i| d | u32::from(bit(s0, 31 - i)) << i),
|
||||
None,
|
||||
),
|
||||
// 13 S_BCNT0_I32_B32: D = 0; for i in 0..31: D += (S0[i] == 0 ? 1 : 0);
|
||||
// SCC = (D != 0).
|
||||
Form::Bcnt0 => not_zero((0..32).filter(|&i| !bit(s0, i)).count() as u32),
|
||||
// 15 S_BCNT1_I32_B32: D += (S0[i] == 1 ? 1 : 0); SCC = (D != 0).
|
||||
Form::Bcnt1 => not_zero((0..32).filter(|&i| bit(s0, i)).count() as u32),
|
||||
// 17 S_FF0_I32_B32: D.i = -1; for i in 0..31 (from the LSB): if
|
||||
// S0[i] == 0 then D.i = i; break.
|
||||
Form::Ff0 => ((0..32).find(|&i| !bit(s0, i)).unwrap_or(u32::MAX), None),
|
||||
// 19 S_FF1_I32_B32: D.i = -1; for i in 0..31: if S0[i] == 1 then
|
||||
// D.i = i; break.
|
||||
Form::Ff1 => ((0..32).find(|&i| bit(s0, i)).unwrap_or(u32::MAX), None),
|
||||
// 21 S_FLBIT_I32_B32: D.i = -1; for i in 0..31: if S0[31 - i] == 1
|
||||
// then D.i = i; break. (Zeros before the first one from the MSB.)
|
||||
Form::FlbitB32 => ((0..32).find(|&i| bit(s0, 31 - i)).unwrap_or(u32::MAX), None),
|
||||
// 23 S_FLBIT_I32: D.i = -1; for i in 1..31: if S0[31 - i] != S0[31]
|
||||
// then D.i = i; break. Table 14: -1 if the input is 0 or -1.
|
||||
Form::FlbitI32 => (
|
||||
(1..32)
|
||||
.find(|&i| bit(s0, 31 - i) != bit(s0, 31))
|
||||
.unwrap_or(u32::MAX),
|
||||
None,
|
||||
),
|
||||
// 25 S_SEXT_I32_I8: D.i = signext(S0.i[7:0]), i.e. { 24{S0[7]}, S0[7:0] }.
|
||||
Form::SextI8 => (
|
||||
if bit(s0, 7) {
|
||||
s0 | 0xffff_ff00
|
||||
} else {
|
||||
s0 & 0xff
|
||||
},
|
||||
None,
|
||||
),
|
||||
// 26 S_SEXT_I32_I16: D.i = signext(S0.i[15:0]), i.e. { 16{S0[15]}, S0[15:0] }.
|
||||
Form::SextI16 => (
|
||||
if bit(s0, 15) {
|
||||
s0 | 0xffff_0000
|
||||
} else {
|
||||
s0 & 0xffff
|
||||
},
|
||||
None,
|
||||
),
|
||||
// 52 S_ABS_I32: D.i = (S.i < 0 ? -S.i : S.i); SCC = (D.i != 0). The
|
||||
// guide's example keeps 0x80000000 ("Note this is negative!").
|
||||
Form::Abs => not_zero(if bit(s0, 31) {
|
||||
(!s0).wrapping_add(1)
|
||||
} else {
|
||||
s0
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The functional examples printed in guide 12.3, with D only; the final five
|
||||
/// are derived from the pseudocode, as their comment says.
|
||||
const GUIDE_EXAMPLES: [(Form, u32, u32); 39] = [
|
||||
(Form::Bcnt0, 0x0000_0000, 32),
|
||||
(Form::Bcnt0, 0xcccc_cccc, 16),
|
||||
(Form::Bcnt0, 0xffff_ffff, 0),
|
||||
(Form::Bcnt1, 0x0000_0000, 0),
|
||||
(Form::Bcnt1, 0xcccc_cccc, 16),
|
||||
(Form::Bcnt1, 0xffff_ffff, 32),
|
||||
(Form::Ff0, 0xaaaa_aaaa, 0),
|
||||
(Form::Ff0, 0x5555_5555, 1),
|
||||
(Form::Ff0, 0x0000_0000, 0),
|
||||
(Form::Ff0, 0xffff_ffff, 0xffff_ffff),
|
||||
(Form::Ff0, 0xfffe_ffff, 16),
|
||||
(Form::Ff1, 0xaaaa_aaaa, 1),
|
||||
(Form::Ff1, 0x5555_5555, 0),
|
||||
(Form::Ff1, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::Ff1, 0xffff_ffff, 0),
|
||||
(Form::Ff1, 0x0001_0000, 16),
|
||||
(Form::FlbitB32, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::FlbitB32, 0x0000_cccc, 16),
|
||||
(Form::FlbitB32, 0xffff_3333, 0),
|
||||
(Form::FlbitB32, 0x7fff_ffff, 1),
|
||||
(Form::FlbitB32, 0x8000_0000, 0),
|
||||
(Form::FlbitB32, 0xffff_ffff, 0),
|
||||
(Form::FlbitI32, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::FlbitI32, 0x0000_cccc, 16),
|
||||
(Form::FlbitI32, 0xffff_3333, 16),
|
||||
(Form::FlbitI32, 0x7fff_ffff, 1),
|
||||
(Form::FlbitI32, 0x8000_0000, 1),
|
||||
(Form::FlbitI32, 0xffff_ffff, 0xffff_ffff),
|
||||
(Form::Abs, 0x0000_0001, 0x0000_0001),
|
||||
(Form::Abs, 0x7fff_ffff, 0x7fff_ffff),
|
||||
(Form::Abs, 0x8000_0000, 0x8000_0000),
|
||||
(Form::Abs, 0x8000_0001, 0x7fff_ffff),
|
||||
(Form::Abs, 0x8000_0002, 0x7fff_fffe),
|
||||
(Form::Abs, 0xffff_ffff, 0x0000_0001),
|
||||
// Not printed as examples; direct readings of the one-line pseudocode.
|
||||
(Form::Not, 0x0f0f_0000, 0xf0f0_ffff),
|
||||
(Form::Brev, 0x0000_0001, 0x8000_0000),
|
||||
(Form::Brev, 0x1234_5678, 0x1e6a_2c48),
|
||||
(Form::SextI8, 0x1234_5680, 0xffff_ff80),
|
||||
(Form::SextI16, 0x1234_7fff, 0x0000_7fff),
|
||||
];
|
||||
|
||||
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
|
||||
/// -1 to -16, as 32-bit words.
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
/// Boundaries, alternating patterns, the guide's example inputs and values
|
||||
/// whose low 8 or 16 bits have the sign bit set (or just clear).
|
||||
const VALUES: [u32; 24] = [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
0xaaaa_aaaa,
|
||||
0x5555_5555,
|
||||
0xcccc_cccc,
|
||||
0x0000_cccc,
|
||||
0xffff_3333,
|
||||
0xfffe_ffff,
|
||||
0x0001_0000,
|
||||
0x0000_007f,
|
||||
0x0000_0080,
|
||||
0x0000_00ff,
|
||||
0x0000_7fff,
|
||||
0x0000_8000,
|
||||
0x0000_ffff,
|
||||
0xffff_ff7f,
|
||||
0x1234_8080,
|
||||
0x1234_5678,
|
||||
];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 7] = [
|
||||
("sop1 domain", 11 * 24 * 2),
|
||||
("sop1 single bit", 11 * 64 * 2),
|
||||
("sop1 guide example", 39 * 2),
|
||||
("sop1 inline integer", 11 * 81 * 2),
|
||||
("sop1 literal", 11 * 6 * 2),
|
||||
("sop1 aliasing", 11 * 3 * 2 * 2),
|
||||
("sop1 max register", 11 * 3 * 2),
|
||||
];
|
||||
/// Per form: 6 destinations and 15 sources outside the supported subset.
|
||||
const REJECTIONS: usize = 11 * (6 + 15);
|
||||
|
||||
/// ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.3).
|
||||
fn sop1(op: u32, dst: u32, src0: u32) -> u32 {
|
||||
0xbe80_0000 | dst << 16 | op << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
|
||||
/// `scc` with `s_and_b32 s12, x, x` (x = 1 or 0), run `alu`, then
|
||||
/// v2 = s<result>, `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2.
|
||||
/// With the lane input [0, !0] the output is [R, R] when SCC is clear after
|
||||
/// `alu` and [R, !R] when it is set.
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
let x = if scc { 129 } else { 128 };
|
||||
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
/// The case for `form` with S0 = `s0` and SCC = `scc` before it, reading back
|
||||
/// `result`, whose value afterwards is `r` (D unless another register is read).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn case(
|
||||
(form, name): (Form, &'static str),
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
s0: u32,
|
||||
scc: bool,
|
||||
r: Option<u32>,
|
||||
) -> Case {
|
||||
let (d, written) = expect(form, s0);
|
||||
let r = r.unwrap_or(d);
|
||||
let label = format!("{name} {label}, scc before {scc}");
|
||||
let scc = written.unwrap_or(scc);
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label,
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for scc in [false, true] {
|
||||
let single = (0..32).flat_map(|k| [1 << k, !(1 << k)]);
|
||||
let values = VALUES.iter().map(|&v| (v, "sop1 domain"));
|
||||
let examples = GUIDE_EXAMPLES
|
||||
.iter()
|
||||
.filter(|example| example.0 == form)
|
||||
.map(|example| (example.1, "sop1 guide example"));
|
||||
let all = values
|
||||
.chain(single.map(|v| (v, "sop1 single bit")))
|
||||
.chain(examples);
|
||||
for (value, family) in all {
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 10);
|
||||
let label = format!("{value:#x}");
|
||||
cases.push(case((form, name), family, label, code, value, scc, None));
|
||||
}
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
let code = program(&[], scc, &[sop1(op, 10, selector)], 10);
|
||||
let label = format!("inline {value:#x}");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 inline integer",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
for value in [0, 1, 0x8000_0000, u32::MAX, 0x1234_8080, 0x0001_0000] {
|
||||
let code = program(&[], scc, &[sop1(op, 10, LITERAL), value], 10);
|
||||
let label = format!("literal {value:#x}");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 literal",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
// s8 = op(s8), and s10 = op(s8) reading s8 back unchanged.
|
||||
for value in [0x8000_0000, 0x0000_80ff, u32::MAX] {
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 8, 8)], 8);
|
||||
let label = format!("s8 = op s8 ({value:#x})");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 aliasing",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 8);
|
||||
let label = format!("s8 kept after s10 = op s8 ({value:#x})");
|
||||
let kept = Some(value);
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 aliasing",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
kept,
|
||||
));
|
||||
}
|
||||
// The highest SGPR, s105 (0b1101001), as source, destination or both.
|
||||
let value = 0x0000_8001;
|
||||
for (dst, src, init) in [(105, 105, 105), (10, 105, 105), (105, 8, 8)] {
|
||||
let code = program(&[(init, value)], scc, &[sop1(op, dst, src)], dst);
|
||||
let label = format!("s{dst} = op s{src} ({value:#x})");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 max register",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOP1 word's byte offset in `program` with one init pair.
|
||||
const ALU_OFFSET: usize = 12 + 8 + 4;
|
||||
|
||||
/// Programs both interpreters must refuse at the SOP1 word.
|
||||
fn rejections() -> Vec<(String, Vec<u8>)> {
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
// VCC_LO, VCC_HI, M0, NULL, EXEC_LO, EXEC_HI as SDST.
|
||||
for dst in [106, 107, 124, 125, 126, 127] {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, dst, 8)], 10);
|
||||
all.push((format!("{name} destination {dst}"), code));
|
||||
}
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, SCC, and the float inline
|
||||
// constants 240-248 as SSRC0.
|
||||
for src in [106, 107, 124, 126, 127, 253].into_iter().chain(240..=248) {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, 10, src)], 10);
|
||||
all.push((format!("{name} source {src}"), code));
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn assert_rejected_at_alu(label: &str, code: &[u8]) {
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(
|
||||
error.offset, ALU_OFFSET,
|
||||
"reference rejected {label} elsewhere"
|
||||
),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{ALU_OFFSET:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expectations_reproduce_the_guide_examples() {
|
||||
for (form, s0, d) in GUIDE_EXAMPLES {
|
||||
assert_eq!(expect(form, s0).0, d, "{form:?}({s0:#x})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop1_unary_forms_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, |code, input| {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
});
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop1_unary: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop1_unary_forms_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop1_unary: {} independent-interpreter cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_sop1_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code) in &rejections {
|
||||
assert_rejected_at_alu(label, code);
|
||||
}
|
||||
eprintln!("sop1_unary: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_sop1_opcodes_stay_unsupported() {
|
||||
// Every 8-bit SOP1 opcode except s_mov_b32 (3) and the eleven forms.
|
||||
let supported: Vec<u32> = FORMS
|
||||
.iter()
|
||||
.map(|&(form, _)| form as u32)
|
||||
.chain([3])
|
||||
.collect();
|
||||
for op in (0..=255).filter(|op| !supported.contains(op)) {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, 10, 8)], 10);
|
||||
assert_rejected_at_alu(&format!("opcode {op}"), &code);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn sop1_unary_forms_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code) in rejections() {
|
||||
// A decode error at the SOP1 word, so a later failure cannot stand in.
|
||||
match compile(Architecture::Gfx1030, &code) {
|
||||
Err(CompileError::Decode(error)) => assert_eq!(
|
||||
error.offset, ALU_OFFSET,
|
||||
"compiler rejected {label} elsewhere: {error:?}"
|
||||
),
|
||||
other => panic!("compiler did not reject {label} at decode: {other:?}"),
|
||||
}
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sop1_unary: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for sixteen 32-bit SOP2 integer forms (#215):
|
||||
//! `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`,
|
||||
//! `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`,
|
||||
//! `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions"
|
||||
//! (pseudocode and the ABSDIFF functional examples), Tables 11, 12 and 14 in
|
||||
//! section 5 (which forms set SCC, and that CSELECT reads it), section 13.1.1
|
||||
//! for the SOP2 word and the scalar operand table for inline integer
|
||||
//! constants. Nothing here comes from the ISA crate, the semantic registry, the
|
||||
//! decoder or the shader compiler. Every case runs on the reference interpreter
|
||||
//! `xenora_ref` and on the second interpreter `independent_ref`; the ignored
|
||||
//! test also runs the translated MSL on native Metal.
|
||||
//!
|
||||
//! Reading of the pseudocode where the guide leaves C-like operators open:
|
||||
//! arithmetic is exact (unbounded integers, as the guide's own
|
||||
//! `>= 0x100000000ULL` carry tests require) and D keeps the low 32 bits. So a
|
||||
//! BFE width of 32 or more gives an all-ones mask, and LSHLn_ADD's SCC is the
|
||||
//! carry out of the whole `(S0 << N) + S1`, including bits shifted out of S0.
|
||||
//! These are guide readings, not hardware evidence.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
use xenora_shader::{Architecture, CompileError, compile};
|
||||
|
||||
/// The sixteen forms with their ENC_SOP2 opcodes (guide 12.1).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Form {
|
||||
MinI32 = 6,
|
||||
MinU32 = 7,
|
||||
MaxI32 = 8,
|
||||
MaxU32 = 9,
|
||||
Cselect = 10,
|
||||
Bfm = 36,
|
||||
Mul = 38,
|
||||
BfeU32 = 39,
|
||||
BfeI32 = 40,
|
||||
Absdiff = 44,
|
||||
Lshl1Add = 46,
|
||||
Lshl2Add = 47,
|
||||
Lshl3Add = 48,
|
||||
Lshl4Add = 49,
|
||||
MulHiU32 = 53,
|
||||
MulHiI32 = 54,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 16] = [
|
||||
(Form::MinI32, "s_min_i32"),
|
||||
(Form::MinU32, "s_min_u32"),
|
||||
(Form::MaxI32, "s_max_i32"),
|
||||
(Form::MaxU32, "s_max_u32"),
|
||||
(Form::Cselect, "s_cselect_b32"),
|
||||
(Form::Bfm, "s_bfm_b32"),
|
||||
(Form::Mul, "s_mul_i32"),
|
||||
(Form::BfeU32, "s_bfe_u32"),
|
||||
(Form::BfeI32, "s_bfe_i32"),
|
||||
(Form::Absdiff, "s_absdiff_i32"),
|
||||
(Form::Lshl1Add, "s_lshl1_add_u32"),
|
||||
(Form::Lshl2Add, "s_lshl2_add_u32"),
|
||||
(Form::Lshl3Add, "s_lshl3_add_u32"),
|
||||
(Form::Lshl4Add, "s_lshl4_add_u32"),
|
||||
(Form::MulHiU32, "s_mul_hi_u32"),
|
||||
(Form::MulHiI32, "s_mul_hi_i32"),
|
||||
];
|
||||
|
||||
/// BFE's S1 fields (guide 12.1): "S1[4:0] is field offset, S1[22:16] is field
|
||||
/// width", so the width is seven bits (0-127) and bits 5-15 and 23-31 are
|
||||
/// ignored.
|
||||
fn field(s1: u32) -> (u32, u32) {
|
||||
(s1 & 0x1f, (s1 >> 16) & 0x7f)
|
||||
}
|
||||
|
||||
/// `(1 << width) - 1` in exact arithmetic.
|
||||
fn mask(width: u32) -> i128 {
|
||||
((1u128 << width) - 1) as i128
|
||||
}
|
||||
|
||||
/// The guide's D for `form` with S0 = `s0`, S1 = `s1` and SCC = `scc` before
|
||||
/// it, and the SCC after it: `Some` for the forms that write SCC, `None` for
|
||||
/// those that leave it unchanged. Only CSELECT reads `scc`.
|
||||
fn expect(form: Form, s0: u32, s1: u32, scc: bool) -> (u32, Option<bool>) {
|
||||
let (i0, i1) = (i128::from(s0 as i32), i128::from(s1 as i32));
|
||||
let (u0, u1) = (i128::from(s0), i128::from(s1));
|
||||
// D keeps the low 32 bits of the exact result.
|
||||
let low = |exact: i128| exact as u32;
|
||||
let not_zero = |d: u32| (d, Some(d != 0));
|
||||
match form {
|
||||
// 6 S_MIN_I32: D.i = (S0.i < S1.i) ? S0.i : S1.i; SCC = (S0.i < S1.i).
|
||||
// Equal operands give S1 (the same value) and SCC = 0; Table 11's
|
||||
// "SCC = 1 if S0 was min" agrees only if a tie does not count as S0.
|
||||
Form::MinI32 => (if i0 < i1 { s0 } else { s1 }, Some(i0 < i1)),
|
||||
// 7 S_MIN_U32: D.u = (S0.u < S1.u) ? S0.u : S1.u; SCC = (S0.u < S1.u).
|
||||
Form::MinU32 => (if u0 < u1 { s0 } else { s1 }, Some(u0 < u1)),
|
||||
// 8 S_MAX_I32: D.i = (S0.i > S1.i) ? S0.i : S1.i; SCC = (S0.i > S1.i).
|
||||
Form::MaxI32 => (if i0 > i1 { s0 } else { s1 }, Some(i0 > i1)),
|
||||
// 9 S_MAX_U32: D.u = (S0.u > S1.u) ? S0.u : S1.u; SCC = (S0.u > S1.u).
|
||||
Form::MaxU32 => (if u0 > u1 { s0 } else { s1 }, Some(u0 > u1)),
|
||||
// 10 S_CSELECT_B32: D.u = SCC ? S0.u : S1.u. Table 12: "Sets SCC? n".
|
||||
Form::Cselect => (if scc { s0 } else { s1 }, None),
|
||||
// 36 S_BFM_B32: D.u = ((1 << S0.u[4:0]) - 1) << S1.u[4:0]. Table 14:
|
||||
// "Sets SCC? n".
|
||||
Form::Bfm => (low(mask(s0 & 0x1f) << (s1 & 0x1f)), None),
|
||||
// 38 S_MUL_I32: D.i = S0.i * S1.i; Table 11: "Low 32 bits of result",
|
||||
// "Sets SCC? n".
|
||||
Form::Mul => (low(i0 * i1), None),
|
||||
// 39 S_BFE_U32: D.u = (S0.u >> S1.u[4:0]) & ((1 << S1.u[22:16]) - 1);
|
||||
// SCC = (D.u != 0). Width 0 gives 0; bits past bit 31 of S0 are 0.
|
||||
Form::BfeU32 => {
|
||||
let (offset, width) = field(s1);
|
||||
not_zero(low((u0 >> offset) & mask(width)))
|
||||
}
|
||||
// 40 S_BFE_I32: D.i = signext((S0.i >> S1.u[4:0]) & ((1 << S1.u[22:16])
|
||||
// - 1)); SCC = (D.i != 0). Section 5.7: "Bit Field Extract, then
|
||||
// sign-extend result", i.e. from the field's top bit, width - 1. S0.i
|
||||
// shifts arithmetically, so a field past bit 31 is filled with S0[31].
|
||||
// Width 0 gives 0.
|
||||
Form::BfeI32 => {
|
||||
let (offset, width) = field(s1);
|
||||
let bits = (i0 >> offset) & mask(width);
|
||||
let d = if width > 0 && (bits >> (width - 1)) & 1 == 1 {
|
||||
bits.wrapping_sub(1i128.wrapping_shl(width))
|
||||
} else {
|
||||
bits
|
||||
};
|
||||
not_zero(low(d))
|
||||
}
|
||||
// 44 S_ABSDIFF_I32: D.i = S0.i - S1.i; if (D.i < 0) D.i = -D.i;
|
||||
// SCC = (D.i != 0). D.i is 32-bit: the functional examples give
|
||||
// (0x80000000, 1) => 0x7fffffff and keep 0x80000000 for
|
||||
// (0x80000000, 0), so the difference wraps before the negation.
|
||||
Form::Absdiff => {
|
||||
let d = (s0 as i32).wrapping_sub(s1 as i32);
|
||||
not_zero(if d < 0 { d.wrapping_neg() } else { d } as u32)
|
||||
}
|
||||
// 46-49 S_LSHLn_ADD_U32: D.u = (S0.u << N) + S1.u; SCC = (((S0.u << N)
|
||||
// + S1.u) >= 0x100000000ULL ? 1 : 0), N = 1, 2, 3, 4.
|
||||
Form::Lshl1Add | Form::Lshl2Add | Form::Lshl3Add | Form::Lshl4Add => {
|
||||
let n = form as u32 - 45;
|
||||
let exact = (u0 << n) + u1;
|
||||
(low(exact), Some(exact >= 1 << 32))
|
||||
}
|
||||
// 53 S_MUL_HI_U32: D.u = (S0.u * S1.u) >> 32. No SCC line.
|
||||
Form::MulHiU32 => (low((u0 * u1) >> 32), None),
|
||||
// 54 S_MUL_HI_I32: D.i = (S0.i * S1.i) >> 32 (signed). No SCC line.
|
||||
Form::MulHiI32 => (low((i0 * i1) >> 32), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The ABSDIFF functional examples printed in guide 12.1, with D only, and
|
||||
/// direct readings of other one-line pseudocode.
|
||||
const GUIDE_EXAMPLES: [(Form, u32, u32, u32); 18] = [
|
||||
(Form::Absdiff, 0x0000_0002, 0x0000_0005, 0x0000_0003),
|
||||
(Form::Absdiff, 0xffff_ffff, 0x0000_0000, 0x0000_0001),
|
||||
(Form::Absdiff, 0x8000_0000, 0x0000_0000, 0x8000_0000),
|
||||
(Form::Absdiff, 0x8000_0000, 0x0000_0001, 0x7fff_ffff),
|
||||
(Form::Absdiff, 0x8000_0000, 0xffff_ffff, 0x7fff_ffff),
|
||||
(Form::Absdiff, 0x8000_0000, 0xffff_fffe, 0x7fff_fffe),
|
||||
// Not printed as examples.
|
||||
(Form::Bfm, 4, 8, 0x0000_0f00),
|
||||
(Form::Bfm, 31, 1, 0xffff_fffe),
|
||||
(Form::Bfm, 32, 0, 0),
|
||||
(Form::BfeU32, 0x1234_5678, 0x0008_0004, 0x0000_0067),
|
||||
(Form::BfeU32, 0x8000_0000, 0x0004_001f, 0x0000_0001),
|
||||
(Form::BfeI32, 0x0000_0080, 0x0008_0000, 0xffff_ff80),
|
||||
(Form::BfeI32, 0x8000_0000, 0x0004_001f, 0xffff_ffff),
|
||||
(Form::BfeI32, 0x1234_5678, 0x0040_0000, 0x1234_5678),
|
||||
(Form::MulHiU32, 0xffff_ffff, 0xffff_ffff, 0xffff_fffe),
|
||||
(Form::MulHiI32, 0xffff_ffff, 0xffff_ffff, 0x0000_0000),
|
||||
(Form::MulHiI32, 0x8000_0000, 0x8000_0000, 0x4000_0000),
|
||||
(Form::Lshl4Add, 0x1000_0000, 0x0000_0001, 0x0000_0001),
|
||||
];
|
||||
|
||||
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
|
||||
/// -1 to -16, as 32-bit words.
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
/// Boundaries, their neighbours and alternating patterns; all pairs include
|
||||
/// the equal pairs that are MIN/MAX ties.
|
||||
const VALUES: [u32; 13] = [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
0xaaaa_aaaa,
|
||||
0x5555_5555,
|
||||
0x1234_5678,
|
||||
0x0000_ffff,
|
||||
0xffff_0000,
|
||||
];
|
||||
/// BFE widths around 0, 32 and the seven-bit field, and offsets around 0, 31
|
||||
/// and the five-bit field.
|
||||
const WIDTHS: [u32; 10] = [0, 1, 2, 8, 16, 31, 32, 33, 64, 127];
|
||||
const OFFSETS: [u32; 8] = [0, 1, 4, 16, 28, 31, 32, 63];
|
||||
/// S1 words with bit 23 (just above the width) or every ignored bit set.
|
||||
const BFE_EXTRA: [u32; 2] = [0x0084_0004, 0xff80_ffe4];
|
||||
/// BFM sizes and offsets around the five-bit fields.
|
||||
const BFM_FIELDS: [u32; 9] = [0, 1, 4, 16, 31, 32, 33, 63, 0xffff_ffe1];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 7] = [
|
||||
("sop2 arith domain", 16 * 13 * 13 * 2),
|
||||
("sop2 arith bit field", (2 * 13 * (10 * 8 + 2) + 9 * 9) * 2),
|
||||
("sop2 arith guide example", 18 * 2),
|
||||
("sop2 arith aliasing", 16 * 2 * 5 * 2),
|
||||
("sop2 arith inline integer", 16 * 81 * 2 * 2 * 2),
|
||||
("sop2 arith literal", 16 * 6 * 2 * 2),
|
||||
("sop2 arith max register", 16 * 4 * 2),
|
||||
];
|
||||
/// Per form: two literals, 6 destinations and 15 sources in each slot outside
|
||||
/// the supported subset; and CSELECT with SCC never written.
|
||||
const REJECTIONS: usize = 16 * (1 + 6 + 2 * 15) + 1 + 4;
|
||||
|
||||
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.1).
|
||||
fn sop2(op: u32, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
0x8000_0000 | op << 23 | dst << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
|
||||
/// `scc` with `s_cmp_eq_u32` (or leave it unwritten for `None`), run `alu`, then
|
||||
/// v2 = s<result>, XORed with v1 when SCC is set afterwards, and store v2. With
|
||||
/// the lane input [0, !0] the output is [R, R] when SCC is clear after `alu`
|
||||
/// and [R, !R] when it is set.
|
||||
fn program(init: &[(u32, u32)], scc: Option<bool>, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
match scc {
|
||||
Some(true) => code.push(0xbf06_8080),
|
||||
Some(false) => code.push(0xbf06_8180),
|
||||
None => {}
|
||||
}
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
/// The case for `form` on `s0`, `s1` with SCC = `scc` before it, reading back
|
||||
/// `result`, whose value afterwards is `r` (D unless another register is read).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn case(
|
||||
(form, name): (Form, &'static str),
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
(s0, s1): (u32, u32),
|
||||
scc: bool,
|
||||
r: Option<u32>,
|
||||
) -> Case {
|
||||
let (d, written) = expect(form, s0, s1, scc);
|
||||
let r = r.unwrap_or(d);
|
||||
let label = format!("{name} {label}, scc before {scc}");
|
||||
let scc = written.unwrap_or(scc);
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label,
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
fn pairs(form: Form) -> Vec<(u32, u32, &'static str)> {
|
||||
let mut all: Vec<_> = VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| VALUES.map(|b| (a, b, "sop2 arith domain")))
|
||||
.collect();
|
||||
let family = "sop2 arith bit field";
|
||||
if matches!(form, Form::BfeU32 | Form::BfeI32) {
|
||||
let fields = WIDTHS
|
||||
.iter()
|
||||
.flat_map(|&w| OFFSETS.map(|o| w << 16 | o))
|
||||
.chain(BFE_EXTRA);
|
||||
let fields: Vec<_> = fields.collect();
|
||||
all.extend(
|
||||
VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| fields.iter().map(move |&b| (a, b, family))),
|
||||
);
|
||||
}
|
||||
if form == Form::Bfm {
|
||||
all.extend(
|
||||
BFM_FIELDS
|
||||
.iter()
|
||||
.flat_map(|&a| BFM_FIELDS.map(|b| (a, b, family))),
|
||||
);
|
||||
}
|
||||
let examples = GUIDE_EXAMPLES.iter().filter(|example| example.0 == form);
|
||||
all.extend(examples.map(|example| (example.1, example.2, "sop2 arith guide example")));
|
||||
all
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for scc in [false, true] {
|
||||
let alu = [sop2(op, 10, 8, 9)];
|
||||
for (a, b, family) in pairs(form) {
|
||||
let code = program(&[(8, a), (9, b)], Some(scc), &alu, 10);
|
||||
let label = format!("{a:#x}, {b:#x}");
|
||||
cases.push(case((form, name), family, label, code, (a, b), scc, None));
|
||||
}
|
||||
// dst/src aliasing with s8 = a, s9 = b.
|
||||
for (a, b) in [(0xffff_fff0, 0x0008_0004), (0x8000_0001, 0x8000_0001)] {
|
||||
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
|
||||
let pick = |reg| if reg == 8 { a } else { b };
|
||||
let alu = [sop2(op, dst, src0, src1)];
|
||||
let code = program(&[(8, a), (9, b)], Some(scc), &alu, dst);
|
||||
let label = format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})");
|
||||
let operands = (pick(src0), pick(src1));
|
||||
let family = "sop2 arith aliasing";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
}
|
||||
// Every integer inline constant (-16..64) in each source slot. The
|
||||
// register operand s8 takes two words chosen so a wrong inline value
|
||||
// changes D for at least one of them; as a BFE S1 they are fields
|
||||
// (width 8, offset 0) and (width 32, offset 1).
|
||||
let bfe = matches!(form, Form::BfeU32 | Form::BfeI32);
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
for slot in 0..2 {
|
||||
let others = if slot == 0 && bfe {
|
||||
[0x0008_0000, 0x0020_0001]
|
||||
} else {
|
||||
[0x8000_0f0f, 0x7fff_f0f0]
|
||||
};
|
||||
for other in others {
|
||||
let (alu, operands) = if slot == 0 {
|
||||
(sop2(op, 10, selector, 8), (value, other))
|
||||
} else {
|
||||
(sop2(op, 10, 8, selector), (other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], Some(scc), &[alu], 10);
|
||||
let label = format!("inline {value:#x} in src{slot}, s8 {other:#x}");
|
||||
let family = "sop2 arith inline integer";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The highest SGPR, s105 (0b1101001), as destination, either
|
||||
// source or all three; s8 and s105 differ in sign and as BFE fields.
|
||||
let (a, b, top) = (0x0004_0001, 0x0003_0002, 0x8000_0006);
|
||||
for (dst, src0, src1) in [(105, 8, 9), (10, 105, 8), (10, 8, 105), (105, 105, 105)] {
|
||||
let pick = |reg| match reg {
|
||||
8 => a,
|
||||
9 => b,
|
||||
_ => top,
|
||||
};
|
||||
let alu = [sop2(op, dst, src0, src1)];
|
||||
let code = program(&[(8, a), (9, b), (105, top)], Some(scc), &alu, dst);
|
||||
let label = format!("s{dst} = s{src0}, s{src1}");
|
||||
let operands = (pick(src0), pick(src1));
|
||||
let family = "sop2 arith max register";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
// A 32-bit literal dword after the SOP2 word in each source slot.
|
||||
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x0021_0003] {
|
||||
for slot in 0..2 {
|
||||
let other = 0xc005_0003;
|
||||
let (alu, operands) = if slot == 0 {
|
||||
([sop2(op, 10, LITERAL, 8), value], (value, other))
|
||||
} else {
|
||||
([sop2(op, 10, 8, LITERAL), value], (other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], Some(scc), &alu, 10);
|
||||
let label = format!("literal {value:#x} in src{slot}");
|
||||
let family = "sop2 arith literal";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOP2 word's byte offset in `program` with two init pairs and the SCC
|
||||
/// preset.
|
||||
const ALU_OFFSET: usize = 12 + 16 + 4;
|
||||
|
||||
/// Programs both interpreters must refuse at the SOP2 word, with that offset.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let init = [(8, 1), (9, 2)];
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
// Guide 12.1 (SOP2 note): at most one literal; two are refused.
|
||||
let alu = [sop2(op, 10, LITERAL, LITERAL), 1];
|
||||
let code = program(&init, Some(false), &alu, 10);
|
||||
all.push((format!("{name} two literals"), code, ALU_OFFSET));
|
||||
// VCC_LO, VCC_HI, M0, NULL, EXEC_LO, EXEC_HI as SDST.
|
||||
for dst in [106, 107, 124, 125, 126, 127] {
|
||||
let code = program(&init, Some(false), &[sop2(op, dst, 8, 9)], 10);
|
||||
all.push((format!("{name} destination {dst}"), code, ALU_OFFSET));
|
||||
}
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, SCC, and the float inline
|
||||
// constants 240-248 in either source slot.
|
||||
for src in [106, 107, 124, 126, 127, 253].into_iter().chain(240..=248) {
|
||||
for (src0, src1, slot) in [(src, 9, 0), (8, src, 1)] {
|
||||
let code = program(&init, Some(false), &[sop2(op, 10, src0, src1)], 10);
|
||||
all.push((format!("{name} src{slot} {src}"), code, ALU_OFFSET));
|
||||
}
|
||||
}
|
||||
}
|
||||
// CSELECT reads SCC; here nothing has written it.
|
||||
let code = program(&init, None, &[sop2(Form::Cselect as u32, 10, 8, 9)], 10);
|
||||
all.push(("s_cselect_b32 with SCC unset".into(), code, ALU_OFFSET - 4));
|
||||
// The forms that leave SCC unchanged must keep it unset, so a CSELECT after
|
||||
// them is still refused (at the CSELECT, the second ALU word).
|
||||
for form in [Form::Bfm, Form::Mul, Form::MulHiU32, Form::MulHiI32] {
|
||||
let alu = [
|
||||
sop2(form as u32, 10, 8, 9),
|
||||
sop2(Form::Cselect as u32, 11, 8, 9),
|
||||
];
|
||||
let code = program(&init, None, &alu, 11);
|
||||
all.push((
|
||||
format!("{form:?} then s_cselect_b32 with SCC unset"),
|
||||
code,
|
||||
ALU_OFFSET,
|
||||
));
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn assert_rejected_at(label: &str, code: &[u8], offset: usize) {
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{offset:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expectations_reproduce_the_guide_examples() {
|
||||
for (form, s0, s1, d) in GUIDE_EXAMPLES {
|
||||
assert_eq!(
|
||||
expect(form, s0, s1, false).0,
|
||||
d,
|
||||
"{form:?}({s0:#x}, {s1:#x})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop2_arith_forms_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, |code, input| {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
});
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop2_arith: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop2_arith_forms_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop2_arith: {} independent-interpreter cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_sop2_arith_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, offset) in &rejections {
|
||||
assert_rejected_at(label, code, *offset);
|
||||
}
|
||||
eprintln!("sop2_arith: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_sop2_opcodes_stay_unsupported() {
|
||||
// Every SOP2 opcode (0-95; 96 and up are other encodings) except the
|
||||
// earlier stages' forms (0-5 and the even opcodes 14-34) and these
|
||||
// sixteen. Sources and destination are aligned pairs, all initialized, so
|
||||
// a 64-bit form would read and write only set registers.
|
||||
let earlier = (0..=5).chain((14..=34).step_by(2));
|
||||
let supported: Vec<u32> = FORMS
|
||||
.iter()
|
||||
.map(|&(form, _)| form as u32)
|
||||
.chain(earlier)
|
||||
.collect();
|
||||
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
|
||||
for op in (0..=95).filter(|op| !supported.contains(op)) {
|
||||
let code = program(&init, Some(false), &[sop2(op, 10, 8, 12)], 10);
|
||||
assert_rejected_at(&format!("opcode {op}"), &code, 12 + 32 + 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn sop2_arith_forms_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code, offset) in rejections() {
|
||||
// Refused at the same word as by the interpreters, so a later failure
|
||||
// cannot stand in.
|
||||
let at = match compile(Architecture::Gfx1030, &code) {
|
||||
Err(CompileError::Decode(error)) => error.offset,
|
||||
Err(CompileError::Verify { offset, .. }) => offset,
|
||||
other => panic!("compiler did not reject {label}: {other:?}"),
|
||||
};
|
||||
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sop2_arith: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for the eight SOP2 forms added in #215 stage C:
|
||||
//! `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`,
|
||||
//! `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions" for
|
||||
//! D and SCC of each form, section 5.3 for the SCC rule of bit/logical
|
||||
//! operations, and the scalar operand table (section 3) for inline integer
|
||||
//! constants. Nothing here comes from the ISA crate, the semantic registry, the
|
||||
//! decoder or the shader compiler. Every case runs on the reference interpreter
|
||||
//! `xenora_ref` and on the second interpreter `independent_ref`; the ignored
|
||||
//! test also runs the translated MSL on native Metal.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
|
||||
/// The eight stage C forms with their ENC_SOP2 opcodes (guide 12.1).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Form {
|
||||
Andn2 = 20,
|
||||
Orn2 = 22,
|
||||
Nand = 24,
|
||||
Nor = 26,
|
||||
Xnor = 28,
|
||||
Lshl = 30,
|
||||
Lshr = 32,
|
||||
Ashr = 34,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 8] = [
|
||||
(Form::Andn2, "s_andn2_b32"),
|
||||
(Form::Orn2, "s_orn2_b32"),
|
||||
(Form::Nand, "s_nand_b32"),
|
||||
(Form::Nor, "s_nor_b32"),
|
||||
(Form::Xnor, "s_xnor_b32"),
|
||||
(Form::Lshl, "s_lshl_b32"),
|
||||
(Form::Lshr, "s_lshr_b32"),
|
||||
(Form::Ashr, "s_ashr_i32"),
|
||||
];
|
||||
|
||||
/// The guide's D and SCC for `form` with S0 = `s0` and S1 = `s1`. None of
|
||||
/// these forms reads SCC, so the value of SCC before the instruction is not an
|
||||
/// input.
|
||||
fn expect(form: Form, s0: u32, s1: u32) -> (u32, bool) {
|
||||
let d = match form {
|
||||
// 20 S_ANDN2_B32: D = S0 & ~S1; SCC = (D != 0).
|
||||
Form::Andn2 => s0 & !s1,
|
||||
// 22 S_ORN2_B32: D = S0 | ~S1; SCC = (D != 0).
|
||||
Form::Orn2 => s0 | !s1,
|
||||
// 24 S_NAND_B32: D = ~(S0 & S1); SCC = (D != 0).
|
||||
Form::Nand => !(s0 & s1),
|
||||
// 26 S_NOR_B32: D = ~(S0 | S1); SCC = (D != 0).
|
||||
Form::Nor => !(s0 | s1),
|
||||
// 28 S_XNOR_B32: D = ~(S0 ^ S1); SCC = (D != 0).
|
||||
Form::Xnor => !(s0 ^ s1),
|
||||
// 30 S_LSHL_B32: D.u = S0.u << S1.u[4:0]; SCC = (D.u != 0).
|
||||
Form::Lshl => s0 << (s1 & 0x1f),
|
||||
// 32 S_LSHR_B32: D.u = S0.u >> S1.u[4:0]; SCC = (D.u != 0).
|
||||
Form::Lshr => s0 >> (s1 & 0x1f),
|
||||
// 34 S_ASHR_I32: D.i = signext(S0.i) >> S1.u[4:0]; SCC = (D.i != 0).
|
||||
// S1 is read as unsigned and only its low five bits count, so its
|
||||
// sign never matters; the shift replicates S0's sign bit.
|
||||
Form::Ashr => ((s0 as i32) >> (s1 & 0x1f)) as u32,
|
||||
};
|
||||
// Section 5.3: bit/logical operations set SCC = 1 iff the result is not zero.
|
||||
(d, d != 0)
|
||||
}
|
||||
|
||||
/// Guide section 3 scalar operand table: 128 is 0, 129-192 are 1 to 64 and
|
||||
/// 193-208 are -1 to -16, as 32-bit words.
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
/// Boundary operands and alternating bit patterns.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0xffff_ffff,
|
||||
0xaaaa_aaaa,
|
||||
0x5555_5555,
|
||||
0x1234_5678,
|
||||
];
|
||||
/// Shift counts around the five-bit field, and one whose low bits are 1.
|
||||
const SHIFTS: [u32; 7] = [0, 1, 31, 32, 33, 63, 0xffff_ffe1];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 5] = [
|
||||
("stage c domain", 8 * 8 * 8 * 2),
|
||||
("stage c shift count", 3 * 8 * 7 * 2),
|
||||
("stage c aliasing", 8 * 2 * 5 * 2),
|
||||
("stage c inline integer", 8 * 81 * 2 * 2 * 2),
|
||||
("stage c literal", 8 * 6 * 2 * 2),
|
||||
];
|
||||
|
||||
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7.
|
||||
fn sop2(form: Form, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
0x8000_0000 | (form as u32) << 23 | dst << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
|
||||
/// `scc` with `s_cmp_eq_u32`, run `alu`, then v2 = s<result>, XORed with v1
|
||||
/// when SCC is set afterwards, and store v2. With the lane input [0, !0] the
|
||||
/// output is [D, D] when SCC is clear and [D, !D] when it is set.
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn case(
|
||||
name: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
let (d, scc) = out;
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![d, if scc { !d } else { d }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let shift = matches!(form, Form::Lshl | Form::Lshr | Form::Ashr);
|
||||
for scc in [false, true] {
|
||||
let alu = [sop2(form, 10, 8, 9)];
|
||||
let pairs = VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| VALUES.map(|b| (a, b, "stage c domain")));
|
||||
let counts = VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| SHIFTS.map(|b| (a, b, "stage c shift count")));
|
||||
let counts: Vec<_> = if shift { counts.collect() } else { Vec::new() };
|
||||
for (a, b, family) in pairs.chain(counts) {
|
||||
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
|
||||
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
|
||||
cases.push(case(name, family, label, code, expect(form, a, b)));
|
||||
}
|
||||
// dst/src aliasing with s8 = a, s9 = b.
|
||||
for (a, b) in [(0xffff_fff0, 0x21), (0x8000_0001, 0x8000_0001)] {
|
||||
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
|
||||
let pick = |reg| if reg == 8 { a } else { b };
|
||||
let code = program(&[(8, a), (9, b)], scc, &[sop2(form, dst, src0, src1)], dst);
|
||||
let label =
|
||||
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x}), scc before {scc}");
|
||||
let out = expect(form, pick(src0), pick(src1));
|
||||
cases.push(case(name, "stage c aliasing", label, code, out));
|
||||
}
|
||||
}
|
||||
// Every integer inline constant (-16..64) in each source slot. The
|
||||
// register operand s8 takes a word and its complement, so a wrong
|
||||
// inline value changes D for at least one of them (as a shift
|
||||
// count it is 0x40 and 0x21, i.e. counts 0 and 1).
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
for (slot, other) in [0, 1].into_iter().flat_map(|slot| {
|
||||
let others = if slot == 0 && shift {
|
||||
[0x40, 0x21]
|
||||
} else {
|
||||
[0x8000_0f0f, 0x7fff_f0f0]
|
||||
};
|
||||
others.map(|other| (slot, other))
|
||||
}) {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(form, 10, selector, 8), expect(form, value, other))
|
||||
} else {
|
||||
(sop2(form, 10, 8, selector), expect(form, other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], scc, &[alu], 10);
|
||||
let label =
|
||||
format!("inline {value:#x} in src{slot}, s8 {other:#x}, scc before {scc}");
|
||||
cases.push(case(name, "stage c inline integer", label, code, out));
|
||||
}
|
||||
}
|
||||
// A 32-bit literal dword after the SOP2 word in each source slot.
|
||||
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0xffff_ffe1] {
|
||||
for slot in 0..2 {
|
||||
let other = 0xc000_0003;
|
||||
let (alu, out) = if slot == 0 {
|
||||
(
|
||||
[sop2(form, 10, LITERAL, 8), value],
|
||||
expect(form, value, other),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
[sop2(form, 10, 8, LITERAL), value],
|
||||
expect(form, other, value),
|
||||
)
|
||||
};
|
||||
let code = program(&[(8, other)], scc, &alu, 10);
|
||||
let label = format!("literal {value:#x} in src{slot}, scc before {scc}");
|
||||
cases.push(case(name, "stage c literal", label, code, out));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_c_forms_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, |code, input| {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
});
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop2_stage_c: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_c_forms_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!(
|
||||
"sop2_stage_c: {} independent-interpreter cases",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_opcodes_beside_the_stage_c_forms_stay_unsupported() {
|
||||
// The 64-bit neighbours (opcodes 21-35 odd) read aligned SGPR pairs
|
||||
// (s[10:11] = s[8:9] op s[12:13], all initialized); neither interpreter
|
||||
// supports them, so each must refuse the SOP2 word.
|
||||
for op in (21..=35).step_by(2) {
|
||||
let alu = [0x8000_0000 | op << 23 | 10 << 16 | 12 << 8 | 8];
|
||||
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
|
||||
let code = program(&init, false, &alu, 10);
|
||||
assert!(
|
||||
xenora_ref::execute(&code, &INPUT).is_err(),
|
||||
"reference accepted opcode {op}"
|
||||
);
|
||||
assert!(
|
||||
independent_ref::execute(&code, &INPUT).is_err(),
|
||||
"independent accepted opcode {op}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn stage_c_forms_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sop2_stage_c: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for the twelve SOPC 32-bit integer compares of
|
||||
//! #215 stage D: `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.4 "SOPC Instructions" for
|
||||
//! the SCC of each form, section 13.1.4 for the SOPC word, section 5.3 (compare
|
||||
//! operations set SCC = 1 when true) and the scalar operand table for inline
|
||||
//! integer constants. Nothing here comes from the ISA crate, the semantic
|
||||
//! registry, the decoder or the shader compiler. Every case runs on the
|
||||
//! reference interpreter `xenora_ref` and on the second interpreter
|
||||
//! `independent_ref`; the ignored test also runs the translated MSL on native
|
||||
//! Metal.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
use xenora_shader::{Architecture, compile};
|
||||
|
||||
/// The twelve forms with their ENC_SOPC opcodes (guide 12.4, Table 70).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Form {
|
||||
EqI32 = 0,
|
||||
LgI32 = 1,
|
||||
GtI32 = 2,
|
||||
GeI32 = 3,
|
||||
LtI32 = 4,
|
||||
LeI32 = 5,
|
||||
EqU32 = 6,
|
||||
LgU32 = 7,
|
||||
GtU32 = 8,
|
||||
GeU32 = 9,
|
||||
LtU32 = 10,
|
||||
LeU32 = 11,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 12] = [
|
||||
(Form::EqI32, "s_cmp_eq_i32"),
|
||||
(Form::LgI32, "s_cmp_lg_i32"),
|
||||
(Form::GtI32, "s_cmp_gt_i32"),
|
||||
(Form::GeI32, "s_cmp_ge_i32"),
|
||||
(Form::LtI32, "s_cmp_lt_i32"),
|
||||
(Form::LeI32, "s_cmp_le_i32"),
|
||||
(Form::EqU32, "s_cmp_eq_u32"),
|
||||
(Form::LgU32, "s_cmp_lg_u32"),
|
||||
(Form::GtU32, "s_cmp_gt_u32"),
|
||||
(Form::GeU32, "s_cmp_ge_u32"),
|
||||
(Form::LtU32, "s_cmp_lt_u32"),
|
||||
(Form::LeU32, "s_cmp_le_u32"),
|
||||
];
|
||||
|
||||
/// The guide's SCC for `form` with S0 = `s0` (SSRC0, the left operand) and
|
||||
/// S1 = `s1` (SSRC1). The compares write no SGPR and read no SCC.
|
||||
fn expect(form: Form, s0: u32, s1: u32) -> bool {
|
||||
let (i0, i1) = (s0 as i32, s1 as i32);
|
||||
match form {
|
||||
// 0 S_CMP_EQ_I32 and 6 S_CMP_EQ_U32 ("identical opcodes"): SCC = (S0 == S1).
|
||||
Form::EqI32 | Form::EqU32 => s0 == s1,
|
||||
// 1 S_CMP_LG_I32 and 7 S_CMP_LG_U32 ("identical opcodes"): SCC = (S0 != S1).
|
||||
Form::LgI32 | Form::LgU32 => s0 != s1,
|
||||
// 2 S_CMP_GT_I32: SCC = (S0.i > S1.i).
|
||||
Form::GtI32 => i0 > i1,
|
||||
// 3 S_CMP_GE_I32: SCC = (S0.i >= S1.i).
|
||||
Form::GeI32 => i0 >= i1,
|
||||
// 4 S_CMP_LT_I32: SCC = (S0.i < S1.i).
|
||||
Form::LtI32 => i0 < i1,
|
||||
// 5 S_CMP_LE_I32: SCC = (S0.i <= S1.i).
|
||||
Form::LeI32 => i0 <= i1,
|
||||
// 8 S_CMP_GT_U32: SCC = (S0.u > S1.u).
|
||||
Form::GtU32 => s0 > s1,
|
||||
// 9 S_CMP_GE_U32: SCC = (S0.u >= S1.u).
|
||||
Form::GeU32 => s0 >= s1,
|
||||
// 10 S_CMP_LT_U32: SCC = (S0.u < S1.u).
|
||||
Form::LtU32 => s0 < s1,
|
||||
// 11 S_CMP_LE_U32: SCC = (S0.u <= S1.u).
|
||||
Form::LeU32 => s0 <= s1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
|
||||
/// -1 to -16, as 32-bit words.
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
/// Signed and unsigned boundaries and their neighbours.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
];
|
||||
/// The value s10 holds throughout; the output shows it unchanged.
|
||||
const MARKER: u32 = 0x0f0f_1234;
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 5] = [
|
||||
("sopc domain", 12 * 8 * 8 * 2),
|
||||
("sopc inline integer", 12 * 81 * 3 * 2),
|
||||
("sopc literal", 12 * 5 * 3 * 2),
|
||||
("sopc aliasing", 12 * 3),
|
||||
("sopc no sgpr write", 12 * 5),
|
||||
];
|
||||
/// Per form: two literals, 5 special registers and 9 float inline constants in
|
||||
/// each slot.
|
||||
const REJECTIONS: usize = 12 * (1 + (5 + 9) * 2);
|
||||
|
||||
/// ENCODING 0b10_1111110 in bits 23-31, OP 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.4).
|
||||
fn sopc(op: u32, src0: u32, src1: u32) -> u32 {
|
||||
0xbf00_0000 | op << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair and
|
||||
/// s10 = MARKER, set SCC to `scc` with `s_and_b32 s12, x, x` (x = 1 or 0, a
|
||||
/// SOP2 form, so no compare is involved), run `alu`, then v2 = s<result>,
|
||||
/// `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2. With the lane
|
||||
/// input [0, !0] the output is [R, R] when SCC is clear (branch taken) and
|
||||
/// [R, !R] when it is set (fall through).
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init.iter().chain(&[(10, MARKER)]) {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
let x = if scc { 129 } else { 128 };
|
||||
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn case(
|
||||
name: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
let (r, scc) = out;
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for a in VALUES {
|
||||
for b in VALUES {
|
||||
for scc in [false, true] {
|
||||
let code = program(&[(8, a), (9, b)], scc, &[sopc(op, 8, 9)], 10);
|
||||
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
|
||||
let out = (MARKER, expect(form, a, b));
|
||||
cases.push(case(name, "sopc domain", label, code, out));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every integer inline constant (-16..64) in each slot against a
|
||||
// register that is negative as i32 and large as u32, then 32. SCC
|
||||
// before is the opposite of the result, so a missing write shows.
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
for other in [0xffff_fff8, 0x20, value] {
|
||||
for slot in 0..2 {
|
||||
let (alu, scc) = if slot == 0 {
|
||||
(sopc(op, selector, 8), expect(form, value, other))
|
||||
} else {
|
||||
(sopc(op, 8, selector), expect(form, other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], !scc, &[alu], 10);
|
||||
let label = format!("inline {value:#x} in src{slot}, s8 {other:#x}");
|
||||
cases.push(case(
|
||||
name,
|
||||
"sopc inline integer",
|
||||
label,
|
||||
code,
|
||||
(MARKER, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A literal dword after the SOPC word in each slot.
|
||||
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX] {
|
||||
for other in [0x7fff_ffff, 0x8000_0000, value] {
|
||||
for slot in 0..2 {
|
||||
let (alu, scc) = if slot == 0 {
|
||||
([sopc(op, LITERAL, 8), value], expect(form, value, other))
|
||||
} else {
|
||||
([sopc(op, 8, LITERAL), value], expect(form, other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], !scc, &alu, 10);
|
||||
let label = format!("literal {value:#x} in src{slot}, s8 {other:#x}");
|
||||
cases.push(case(name, "sopc literal", label, code, (MARKER, scc)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// One register in both slots: S0 == S1.
|
||||
for value in [0, 0x8000_0000, u32::MAX] {
|
||||
let scc = expect(form, value, value);
|
||||
let code = program(&[(8, value)], !scc, &[sopc(op, 8, 8)], 10);
|
||||
let label = format!("s8, s8 = {value:#x}");
|
||||
cases.push(case(name, "sopc aliasing", label, code, (MARKER, scc)));
|
||||
}
|
||||
// No SGPR is written: the sources, the marker and s11 (which a SOP2
|
||||
// reading of the word would name as SDST for opcode 11) keep their
|
||||
// values.
|
||||
let (a, b) = (0x8000_0000, 1);
|
||||
let scc = expect(form, a, b);
|
||||
let init = [(8, a), (9, b), (11, 0x1111_1111)];
|
||||
// s12 holds the SCC-setting AND result, 1 when SCC was set before.
|
||||
let s12 = u32::from(!scc);
|
||||
for (reg, value) in [(8, a), (9, b), (10, MARKER), (11, 0x1111_1111), (12, s12)] {
|
||||
let code = program(&init, !scc, &[sopc(op, 8, 9)], reg);
|
||||
let label = format!("s{reg} after s8 {a:#x}, s9 {b:#x}");
|
||||
cases.push(case(name, "sopc no sgpr write", label, code, (value, scc)));
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOPC word's byte offset in `program` with `init` SGPR moves: three
|
||||
/// header words, one 8-byte move per init pair and the marker, and the AND.
|
||||
fn alu_offset(init: usize) -> usize {
|
||||
12 + 8 * (init + 1) + 4
|
||||
}
|
||||
|
||||
/// Both interpreters must refuse `code` at the SOPC word, not later.
|
||||
fn assert_rejected_at_alu(label: &str, code: &[u8], init: usize) {
|
||||
let offset = alu_offset(init);
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{offset:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Programs both interpreters must refuse at the SOPC word, with the number
|
||||
/// of init pairs before it.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
let code = program(&[], false, &[sopc(op, LITERAL, LITERAL), 1], 10);
|
||||
all.push((format!("{name} two literals"), code, 0));
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, and the float inline
|
||||
// constants 240-248 (0.5 .. 1/(2*pi)).
|
||||
for selector in [106, 107, 124, 126, 127].into_iter().chain(240..=248) {
|
||||
for slot in 0..2 {
|
||||
let alu = if slot == 0 {
|
||||
sopc(op, selector, 8)
|
||||
} else {
|
||||
sopc(op, 8, selector)
|
||||
};
|
||||
let code = program(&[(8, 1)], false, &[alu], 10);
|
||||
all.push((format!("{name} source {selector} in src{slot}"), code, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
fn reference(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_d_compares_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, reference);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sopc_stage_d: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_d_compares_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!(
|
||||
"sopc_stage_d: {} independent-interpreter cases",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_compare_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, init) in &rejections {
|
||||
assert_rejected_at_alu(label, code, *init);
|
||||
}
|
||||
eprintln!("sopc_stage_d: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighbouring_sopc_opcodes_stay_unsupported() {
|
||||
// 12-15 are bit tests, 18-19 the 64-bit compares (guide 12.4); 16, 17 and
|
||||
// 20-127 are not listed. Neither interpreter supports any of them.
|
||||
for op in 12..=127 {
|
||||
let code = program(&[(8, 1), (9, 2)], false, &[sopc(op, 8, 9)], 10);
|
||||
assert_rejected_at_alu(&format!("opcode {op}"), &code, 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn stage_d_compares_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code, _) in rejections() {
|
||||
assert!(
|
||||
compile(Architecture::Gfx1030, &code).is_err(),
|
||||
"compiler accepted {label}"
|
||||
);
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sopc_stage_d: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user