Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1834,6 +1834,7 @@ endforeach()
target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp)
target_sources(offscreen_check PRIVATE tests/startup_image_store.cpp)
target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp)
target_sources(offscreen_check PRIVATE tests/startup_entry_words.cpp)
# The storage root handed to the executable ends in a separator and is never cut off
# (src/startup_stubs/storage_root.h); the mutated run is the negative control.
add_executable(startup_storage_root_check tests/startup_storage_root_check.cpp)
Expand Down Expand Up @@ -3206,6 +3207,18 @@ if(EXISTS "${INTAKE_PYTHON}")
# Startup shader translator: signed and unsigned three-source integer min, max and median.
add_test(NAME startup_gfx2hlsl_int_med3_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int_med3_check.py")
# v_med3_f32 with a NaN source is the minimum of the three (ISA p. 343): the preamble's med3_32 tests the
# encoding, the integer medians are unchanged, and the old branchless helper must be rejected.
add_test(NAME startup_gfx2hlsl_f32_med3_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f32_med3_check.py")
# The same four words drawn on WARP and the card, the NaN among them from the entry constants; the
# branchless lowering must mismatch on that lane.
foreach(adapter IN ITEMS warp hardware)
add_test(NAME startup_gfx2hlsl_f32_med3_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f32_med3_check.py" draw "${DXC_EXECUTABLE}"
"$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>)
set_tests_properties(startup_gfx2hlsl_f32_med3_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77)
endforeach()
# Startup shader translator: s_cselect_b32 into the wave32 lane masks vcc_lo and exec_lo.
add_test(NAME startup_gfx2hlsl_cselect_mask_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cselect_mask_check.py")
Expand Down
62 changes: 62 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -15381,6 +15381,68 @@ On Intel UHD Graphics (TGL GT1) with Mesa 26.2.7, DXC 1.10.2605.37 and SPIRV-Too
python3 -B tests/pixel_denorm_vulkan_check.py /path/to/dxc tests/vk_pixel_draw.c --device Intel
VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.json \
python3 -B tests/pixel_denorm_vulkan_check.py /path/to/dxc tests/vk_pixel_draw.c --device llvmpipe
## v_med3_f32 with a NaN source

The RDNA 2 ISA defines `V_MED3_F32` (p. "343 V_MED3_F32") as a NaN branch first:

```
if (isNan(S0.f) || isNan(S1.f) || isNan(S2.f))
D.f = V_MIN3_F32(S0.f, S1.f, S2.f);
else if (V_MAX3_F32(S0.f, S1.f, S2.f) == S0.f)
D.f = V_MAX_F32(S1.f, S2.f);
...
```

A NaN source therefore makes the result the smallest of the three. `tools/startup/gfx2hlsl.py` lowered
`v_med3_f32` to `max(min(a, b), min(max(a, b), c))`, which returns the larger of the non-NaN sources instead.
Drawn with `med3(a, 2.0, 1.0)` on a Radeon RX 9070 XT (driver `32.0.32029.2010`):

| `a` | emitted form | ISA rule |
|---|---|---|
| NaN (`0x7fc00000`) | 2.0 | **1.0** |
| 3.0 | 2.0 | 2.0 |
| 1.5 | 1.5 | 1.5 |
| 0.5 | 1.0 | 1.0 |

The only divergence is the NaN source. The table now points `v_med3_f32` at `med3_32`, whose body is the one
`tools/pixel_aot.py` already uses:

```hlsl
float med3_32(float a, float b, float c) {
uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);
return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));
}
```

The NaN test is on the encoding rather than on `isnan()`, because some desktop compilers fold float NaN
tests, and `min(min(a, b), c)` over operands whose sources D3D's `min()` keeps gives the smallest non-NaN
source. The integer medians (`v_med3_u32`, `v_med3_i32`) are untouched: they compare words and have no NaN.

What the measurement establishes and what it does not: the emitted form rendered 2.0 on the card for a NaN
operand, and the ISA rule is the lower of the non-NaN sources. That the hardware instruction itself computes
`V_MIN3_F32` on a NaN source is **not** established here: HLSL cannot emit `v_med3_f32` (the compiler does not
select it from the median pattern), so the fixture compares the translated text against the ISA rule, not
against the instruction. Reading the instruction directly needs a captured shader or the ISA simulator.

`tests/startup_gfx2hlsl_f32_med3_check.py` holds the controls and the draw. The controls read the emitted
HLSL: the preamble carries `med3_32` with the `0x7f800000u` threshold and the `asuint(x) & 0x7fffffffu` test,
the binary32 table points at it, both the bare and the `_e64` spellings lower to it, and the integer medians
keep their own lowering. Four mutations are rejected: the branchless helper, a `>=` threshold, an `isnan(`
test and a table pointing back at a helper without the branch. The `decode` mode builds
`v_med3_f32 v12, v1, v2, v3` as `0c0057d501050e04` and proves it with `tools/disasm_rdna2.py`.

The draw is a source-built gfx1013 pair whose pixel stage moves the four entry constants s8..s11 into
s44..s47 and applies `v_med3_f32 v(12+lane), v1, v2, v3` with `v2 = 2.0` and `v3 = 1.0`. The inputs arrive as
root 32-bit constants written per draw by `offscreen_check --startup-entry-words`, not as literals: a literal
would be folded at compile time and the lowering under test would never run. The four inputs are
`0x7fc00000`, `0x40400000`, `0x3fc00000` and `0x3f000000`; the expected words are `0x3f800000`,
`0x40000000`, `0x3fc00000` and `0x3f800000`. The control that counts restores the branchless helper in the
same pair and requires a mismatch on the NaN lane alone: `0x40000000` where the ISA asks `0x3f800000`, the
other three lanes unchanged. A negative control that passes is reported as a failure, not accepted.

```powershell
cmake --build --preset dev --target offscreen_check
ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_f32_med3' -V
```

## Vulkan draw of the core translated pixel shaders
Expand Down
7 changes: 4 additions & 3 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,11 @@ The translation is refused when:
- either header has another size;
- the code reads an attribute the table does not list.

The shader cache revision is `x2w-startup-shader-16`. Earlier translations lower `v_fract_f32`
through a bare `frac` instead of the clamped `fract32` helper. The matching compute
(`x2w-startup-shader-16cs`) and fixed slot 57 mesh (`x2w-startup-mesh-57-2`) keys advance
The shader cache revision is `x2w-startup-shader-17`. Earlier translations lower `v_med3_f32` through a
branchless median, which returns the smaller of the other two operands when a source is NaN. The matching
compute (`x2w-startup-shader-17cs`) and fixed slot 57 mesh (`x2w-startup-mesh-57-2`) keys advance
because those stages use the shared lowering.
Revisions before 16 lower `v_fract_f32` through a bare `frac` instead of the clamped `fract32` helper.
Revisions before 15 lower `v_cvt_pk_u8_f32` with a float clamp and accept `s_setreg_imm32_b32` writes of the
rounding mode.
Revisions before 14 evaluate constant `s_brev_b32` at run time instead of folding it into a known word.
Expand Down
4 changes: 2 additions & 2 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void*
{
// Keep pre-fix desktop bytecode and manifests out of this ABI's cache.
// tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL.
constexpr char revision[] = "x2w-startup-shader-16";
constexpr char revision[] = "x2w-startup-shader-17";
const u64 seed = fnv_bytes(revision, sizeof(revision) - 1);
u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed)));
// A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key.
Expand Down Expand Up @@ -364,7 +364,7 @@ void publish_compute_request(const void* desc)
std::vector<unsigned char> fields(sizeof(words));
words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0;
std::memcpy(fields.data(), words, sizeof(words));
constexpr char compute_revision[] = "x2w-startup-shader-16cs"; // tools/startup/gfx2hlsl.py compute_key
constexpr char compute_revision[] = "x2w-startup-shader-17cs"; // tools/startup/gfx2hlsl.py compute_key
u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1);
const std::vector<unsigned char>* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b};
for (const auto* part : order) key = fnv_part(*part, key);
Expand Down
3 changes: 3 additions & 0 deletions tests/desktop_gpu.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con
std::uint32_t* words, UINT width = 1, UINT height = 1,
D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, BOOL front_ccw = FALSE,
UINT vertices = 3);
void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path,
const std::uint32_t* entry, UINT entry_count, std::uint32_t* words,
UINT width = 1, UINT height = 1);
void dump_raw_uav(ID3D12Device* device, const char* shader_path, const char* groups,
const char* bytes, const char* out_path);
void check_spirv_window(ID3D12Device* device, const char* shader_path);
Expand Down
42 changes: 42 additions & 0 deletions tests/offscreen_check.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1488,6 +1488,47 @@ OperationResult run_startup_flat_param(const OperationContext& ctx)
return {OutcomeKind::pass, nullptr};
}

// Comma-separated 8-digit hex words, in order. An empty list or any other shape returns nothing.
static std::vector<std::uint32_t> parse_hex_words(std::string_view text)
{
std::vector<std::uint32_t> words;
while (!text.empty()) {
std::uint32_t value = 0;
const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value, 16);
if (parsed.ec != std::errc{} || parsed.ptr == text.data()) return {};
words.push_back(value);
text.remove_prefix(std::size_t(parsed.ptr - text.data()));
if (text.empty()) break;
if (text.front() != ',') return {};
text.remove_prefix(1);
}
return words;
}

// --startup-entry-words <vs.cso> <ps.cso> <entry words> <expected words>: draws one pixel with a gfx2hlsl
// vertex and pixel pair that reads its operands from the entry constant buffer (tests/startup_entry_words.cpp).
// <entry words> is 1..32 comma-separated 8-digit hex words, ud0 first; the translated vertex stage reads ud0
// as its rectangle-list switch, so a plain triangle fixture keeps it 0. <expected words> is the four words the
// target must hold, compared bit for bit.
OperationResult run_startup_entry_words(const OperationContext& ctx)
{
const auto entry = parse_hex_words(ctx.argv[5]);
const auto expected = parse_hex_words(ctx.argv[6]);
if (entry.empty() || entry.size() > 32)
return {OutcomeKind::fail, "entry constants are not 1..32 hex words"};
if (expected.size() != 4)
return {OutcomeKind::fail, "expected value is not four hex words"};
std::uint32_t words[4]{};
check_startup_entry_words(ctx.device, ctx.argv[3], ctx.argv[4], entry.data(), UINT(entry.size()), words);
if (std::memcmp(words, expected.data(), sizeof(words)) != 0) {
std::fprintf(stderr, "startup_entry_words mismatch expected=%08x,%08x,%08x,%08x "
"actual=%08x,%08x,%08x,%08x\n",
expected[0], expected[1], expected[2], expected[3], words[0], words[1], words[2], words[3]);
return {OutcomeKind::fail, "entry constant readback differs"};
}
return {OutcomeKind::pass, nullptr};
}

constexpr CapabilityGate kNoGate{};
constexpr CapabilityGate kGateSm60BufferOps{
D3D_SHADER_MODEL_6_0, false, false, 0,
Expand Down Expand Up @@ -1609,6 +1650,7 @@ const OperationSpec kOperations[] = {
{"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position},
{"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target},
{"--startup-flat-param", 6, 6, nullptr, kNoGate, run_startup_flat_param},
{"--startup-entry-words", 7, 7, nullptr, kNoGate, run_startup_entry_words},
{"--startup-pixel-words", 8, 8, validate_pixel_words_args, kNoGate, run_startup_pixel_words},
{"--raster-reference", 10, 10, validate_raster_args, kNoGate, run_startup_pixel_words},
// <cso> <groups 1|2> <UAV bytes> <out.bin>: whole raw UAV after one dispatch (#775 GVN parity).
Expand Down
4 changes: 2 additions & 2 deletions tests/startup_compute_request_offline_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@
DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11)
STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003)
STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0)
KEY = 0x4db2818cb07558bf # framed key at revision 16cs
KEY = 0x8421b8080fd0a5e6 # framed key at revision 17cs


def framed_key():
h = 1469598103934665603
for b in b'x2w-startup-shader-16cs':
for b in b'x2w-startup-shader-17cs':
h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff
for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B):
for b in struct.pack('<Q', len(part)) + part:
Expand Down
123 changes: 123 additions & 0 deletions tests/startup_entry_words.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Desktop readback with caller-supplied entry constants for tools/startup/gfx2hlsl.py (v_med3_f32, #2044).
//
// Draws one pixel with a translated vertex and pixel stage and returns the four 32-bit words of
// the colour. The entry constants (cbuffer entry : register(b0)) are visible to both stages, because
// the translated vertex stage reads ud0, the rectangle-list switch; every word comes from the caller,
// so a value under test is never a compile-time literal the shader compiler could fold. The target is
// R32G32B32A32_FLOAT, so the readback is the raw words the pixel stage exported.
#include "desktop_gpu.h"

#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <vector>

using Microsoft::WRL::ComPtr;

namespace {

std::vector<char> read_blob(const char* path)
{
std::ifstream file(path, std::ios::binary);
std::vector<char> bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
if (!file.good() && !file.eof()) throw std::runtime_error(std::string("Cannot read ") + path);
if (bytes.empty()) throw std::runtime_error(std::string("Empty shader ") + path);
return bytes;
}
} // namespace

void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path,
const std::uint32_t* entry, UINT entry_count, std::uint32_t* words,
UINT width, UINT height)
{
const auto vs = read_blob(vertex_path);
const auto ps = read_blob(pixel_path);

D3D12_ROOT_PARAMETER param{};
param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
param.Constants = {0, 0, entry_count};
param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
D3D12_ROOT_SIGNATURE_DESC rs{};
rs.NumParameters = 1;
rs.pParameters = &param;
ComPtr<ID3DBlob> signature, errors;
if (FAILED(D3D12SerializeRootSignature(&rs, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &errors)))
throw std::runtime_error(errors ? static_cast<const char*>(errors->GetBufferPointer())
: "Serialize flat parameter root signature");
ComPtr<ID3D12RootSignature> root;
check(device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&root)),
"Create flat parameter root signature");

D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{};
pd.pRootSignature = root.Get();
pd.VS = {vs.data(), vs.size()};
pd.PS = {ps.data(), ps.size()};
pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
pd.SampleMask = UINT_MAX;
pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
pd.RasterizerState.DepthClipEnable = TRUE;
pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
pd.NumRenderTargets = 1;
pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
pd.SampleDesc.Count = 1;
ComPtr<ID3D12PipelineState> pipeline;
check(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pipeline)), "Create flat parameter PSO");

D3D12_RESOURCE_DESC rd{};
rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
rd.Width = width;
rd.Height = height;
rd.DepthOrArraySize = 1;
rd.MipLevels = 1;
rd.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
rd.SampleDesc.Count = 1;
rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R32G32B32A32_FLOAT, {-1.0f, -1.0f, -1.0f, -1.0f}};
const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear);
D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
UINT64 readback_size = 0;
device->GetCopyableFootprints(&rd, 0, 1, 0, &footprint, nullptr, nullptr, &readback_size);
const auto readback = make_buffer(device, readback_size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST);

D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE};
ComPtr<ID3D12DescriptorHeap> rtvs;
check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create flat parameter RTV heap");
const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart();
device->CreateRenderTargetView(target.Get(), nullptr, rtv);

ComputeCommands commands(device, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT);
auto* list = commands.list.Get();
list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr);
list->SetGraphicsRootSignature(root.Get());
list->SetGraphicsRoot32BitConstants(0, entry_count, entry, 0);
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1};
const D3D12_RECT scissor{0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
list->RSSetViewports(1, &viewport);
list->RSSetScissorRects(1, &scissor);
list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
list->DrawInstanced(3, 1, 0, 0);
transition(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
D3D12_TEXTURE_COPY_LOCATION out{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
out.PlacedFootprint = footprint;
D3D12_TEXTURE_COPY_LOCATION in{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr);
commands.submit_and_wait(device);

void* mapped = nullptr;
const D3D12_RANGE read{0, static_cast<SIZE_T>(readback_size)};
const D3D12_RANGE none{0, 0};
check(readback->Map(0, &read, &mapped), "Map flat parameter readback");
const auto* first = static_cast<const std::uint8_t*>(mapped) + footprint.Offset;
for (UINT y = 0; y < height; ++y) {
std::memcpy(words + size_t(y) * width * 4, first + size_t(y) * footprint.Footprint.RowPitch,
size_t(width) * 4 * sizeof(*words));
}
readback->Unmap(0, &none);
std::printf("startup_entry_words words=%08x,%08x,%08x,%08x\n", words[0], words[1], words[2], words[3]);
}
4 changes: 2 additions & 2 deletions tests/startup_gfx2hlsl_buffer_store_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ def main():
'%s %s' % (result, fail_reason(name)))

# 8. The cache revision moved, so a translation from before the store lowering is never loaded.
check('cache key uses revision 16', G.pipeline_key(b'a', b'b', ROOT) ==
G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-16')))))
check('cache key uses revision 17', G.pipeline_key(b'a', b'b', ROOT) ==
G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-17')))))

if failures:
print('FAILED: ' + ', '.join(failures))
Expand Down
Loading
Loading