Skip to content

sampler_source_census: where each sampled S# comes from; none found in a driver table (SHADER-735) - #4268

Open
Roberto0953 wants to merge 3 commits into
ItsNotRexed:mainfrom
Roberto0953:shader/static-sampler-census
Open

Roberto0953 wants to merge 3 commits into
ItsNotRexed:mainfrom
Roberto0953:shader/static-sampler-census

Conversation

@Roberto0953

@Roberto0953 Roberto0953 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claimed in #3918 (SHADER-735). @rafaelpssz claimed it seconds later and the coordinator asked us to agree a split: review of the classes and counts is welcome, and the s_brev_b32 finding below touches your #2887, so that follow-up is yours if you want it.

Summary

docs/d3d12_vulkan.md section 3.5 left one question open about static samplers: the console driver might hand
them to shaders through a fixed table of its own, and a shader that expected one would read its S# from an address
the layer never fills. The item asks to count, over the corpus, whether any shader does that.

tools/sampler_source_census.py follows the four SGPRs of the sampler operand of every image_sample*,
image_gather4* and image_get_lod back to where their values are made and gives the instruction one class:

class meaning
user_sgprs the S# is user data in the entry SGPRs
user_pointer loaded from memory at an address that starts from a user SGPR (descriptor table or sampler heap; static or run-time offset)
literal four constants built from immediates
other_base held in or loaded through a constant address, a system SGPR or a code-relative address: what a driver table would be. One dword on one path is enough, and it wins over every other class
undetermined anything else, with the reason

It reuses the forward dataflow of tools/heap_index_census.py and adds what the corpus's sampler operands needed:
constants built with s_brev_b32, SGPRs spilled to a VGPR and read back (v_mov_b32 / v_readfirstlane_b32,
v_writelane_b32 / v_readlane_b32), joins that keep the sources of every path, s_getpc_b64, and listings with
embedded data words re-anchored to the FSSM blob the way the translator does (so none is skipped).
--expect-none CLASS... turns the count into a check (exit 1), --jobs N runs it in parallel, --json writes
the full census. It is a census only: no change to the layer or the translator.

What the census shows (counts only)

1.0.2.1 corpus, 26,503 listings, none skipped; 14,025 shaders sample, 366,628 sampling instructions.

stage sampling instructions user_pointer literal user_sgprs other_base undetermined
CS 120,816 63,141 57,674 0 0 1
MS 21,992 10,142 9,723 0 0 2,127
PS 221,157 115,109 106,048 0 0 0
VS 2,663 1,020 1,351 0 0 292
all (195 GS do not sample) 366,628 189,412 174,796 0 0 2,420
  • other_base is 0 in every stage: no sampling instruction was found reading an S# from a constant address, a
    system SGPR or a code-relative address. On this evidence the layer has no driver sampler table to emulate; the
    2,420 undetermined instructions (0.66%) are the part the conservative reading cannot settle, see below.
  • user_pointer: 179,602 at a static offset (0x540 at most), 9,810 at a run-time offset. No constant is added to
    any of these pointers, so constant table address + user index (the same arithmetic as user pointer + constant) does not occur either. All 189,412 are in shaders whose SFI0 sets the sampler-heap bit; a shader
    without the bit samples with literals only.
  • literal: 105,235 in shaders with the sampler-heap bit, 69,561 in shaders without it.
  • undetermined (0.66%, 300 shaders): with every edge followed, one path brings something else into the S#
    registers: 2,355 read the S# back from a VGPR spill slot that one path does not save to (a user_pointer load
    wherever it is saved), 64 get a literal on one path and a user_pointer load on another, 1 gets a value the
    dataflow does not follow. All of them have the same shape: the S# is made or saved inside a region the compiler
    skips with s_cbranch_execz when no lane is active, and sampled after it. Without the taken edge of those
    branches the same analysis classes 2,419 as user_pointer and 1 as literal. The tool reports both; the table
    and --expect-none use the first, conservative one.

What it does not show

  • It reads the shaders, not what the driver writes at the addresses they load from.
  • "User" in the graphics stages means "an entry SGPR below s32" (the translator's assumption); only the compute
    count is measured (COMPUTE_PGM_RSRC2). Question 3 of section 8.2 stays open for that part.
  • Which S# is a root signature's static sampler. The literals are the candidates (a static sampler is known at
    compile time, and half of the sampling instructions build their S# from immediates), but that is a hypothesis
    until the root signatures are matched against them. The doc says so.
  • Lane masks are not modelled: a spill restore is taken to read what the last save on its path wrote, and the
    second reading of the undetermined instructions trusts that nothing samples on the exec-zero path.
  • A descriptor table and a directly indexed sampler heap look the same in the code (both start from a user SGPR),
    so user_pointer does not split them; it is counted by offset kind and by the SFI0 bit instead.

Found on the way (not fixed here)

finding: 28,659 of the literal S# sites, in 6,824 shaders, build one dword with s_brev_b32.
tools/shader_meta.py (_step_state) does not fold that instruction, so those S#s are not in literal_samplers
in the index, and a layer that registers literal samplers from the index would miss them. The census folds it and
counts these sites apart (literal: with s_brev_b32). No game files needed to fix it; a hand-written listing shows
it (four immediates, the third through s_brev_b32: analyse_instructions returns no literal sampler).

Docs

docs/d3d12_vulkan.md: the static-sampler bullet of section 3.5 now says "measured: no sampling instruction was found
reading an S# from a fixed table (0.66% undetermined under the conservative reading)" and points to a new block right after the list, "Where the sampled S# comes from", with the table
above, what each class means, what is not shown and the command. Row 3 of section 8.2 is updated.

Note for whoever merges: #3494 adds lines right after the same bullet. The two changes touch neighbouring lines, so
the second one to land needs a trivial rebase (keep both).

Tests

tests/test_sampler_source_census.py, standard library only, hand-written RDNA2 listings and containers in a
temporary folder (no game files): 28 cases, at least one per class and per form of other_base, plus negative
controls that must not pass as user data: a fixed-table read on one path or in one dword, a spill clobbered before
the restore, another lane read back, a branch that is not an exec-zero skip, a join with too many values, and
--expect-none other_base undetermined failing on a folder with one fixed-table shader.

Run locally (Windows 11, Python 3.13.5, CPU only; no GPU or driver involved):

python -I tests/test_sampler_source_census.py          # 28 tests OK (also under pytest)
python -m compileall -q tools tests
python -I tests/test_text_write_line_endings.py
python -I tests/test_docs_cli_flags.py
python -I tests/test_docs_repo_paths.py
python -I tests/test_docs_links.py
python -I tests/test_docs_list_items.py
python -I tests/test_docs_table_rows.py
python -I tests/test_tool_startup.py
python -I tests/test_tool_stdout_encoding.py
python -I tests/test_heap_index_census.py
python -I scripts/check_no_game_data.py

Reproduce

python -I tools/sampler_source_census.py <work>/shaders/dxbc/disasm --jobs 4 --expect-none other_base

About five minutes with four workers on the full corpus; exit 0, and the table above is its output (run twice, same counts). Nothing from
the game is in the diff: counts only, no shader names, hashes or disassembly.

AI-assisted (Claude Code).

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested a5b6a12 on Windows, CPython 3.14.7, CPU only (no GPU, no game files). I used synthetic listings only.

python -m pytest -q tests/test_sampler_source_census.py gives 28 tests passed. I used a virtual environment with tests/requirements.txt. The tool is new, thus there is no merge-base control.

One point about time complexity. The census analyzes the same source again for each of the four words of a descriptor that one earlier load made. On a straight chain of loads, the work increases exponentially: each extra load makes four copies of the previous work.
At chain depths 2, 3, 4 and 5, I counted 5, 21, 85 and 341 calls to load_source. Each run gives the same correct class: one user_pointer.

Run this script from the repository root:

import runpy, sys
t = runpy.run_path("tests/test_sampler_source_census.py")
for depth in (2, 3, 4, 5):
    w = t["Work"]()
    try:
        lines = [("s_buffer_load_dwordx4 s[28:31], s[28:31], 0", 8), ("s_waitcnt lgkmcnt(0)", 4)] * depth
        w.add("chain", "ps", lines + [t["SAMPLE"], t["END"]])
        calls = [0]
        def profile(frame, event, arg):
            if event == "call" and frame.f_code.co_name == "load_source":
                calls[0] += 1
        sys.setprofile(profile)
        report = t["ssc"].census(w.disasm)
        sys.setprofile(None)
        print(depth, calls[0], report["total"]["classes"]["user_pointer"])
    finally:
        sys.setprofile(None)
        w.close()

The count applies to this constructed chain. I do not know the depth of the chains in the game's shaders.
Possible correction: put the words that come from the same load together, and find their common source one time. Keep the cycle detection.

AI-assisted.

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran this at a5b6a12e on Windows 11: python -I tests/test_sampler_source_census.py -> 28 tests, OK; compileall and git diff --check clean.

The tool classifies where each sampled S# comes from (descriptor table, immediate, driver table) and the tests use synthetic inputs. The documentation keeps counts and offsets only and leaves the "no driver table" conclusion scoped to the measured corpus. No blocking issue.

@rafaelpssz

Copy link
Copy Markdown
Contributor

Thanks @Roberto0953, good find on s_brev_b32. I'll take the follow-up in #2887, since that PR is what reads literal_samplers from the index: _step_state will fold s_brev_b32 of a known constant, with your hand-written case (four immediates, the third through s_brev_b32) as a unit test. I'll post the corpus count before and after once it's in.

@SweatierKey

Copy link
Copy Markdown
Contributor

Tested a5b6a12e on Linux (WSL2, Python 3.13.5, CPU only, no game files): pass.

  • Code read (tools/sampler_source_census.py, docs/d3d12_vulkan.md):
    • Tracks all 4 S# SGPRs across constants (including s_brev_b32/s_not_b32), scalar/buffer loads, VGPR spill/restore, and multi-path joins, with other_base conservatively winning over every other class (including undetermined) and a clearly separated secondary pass dropping s_cbranch_execz skip edges while keeping the conservative pass authoritative for the table and --expect-none.
    • Arithmetic verified across docs/d3d12_vulkan.md: row totals (63,141+57,674+1 = 120,816 CS; 10,142+9,723+2,127 = 21,992 MS; 115,109+106,048 = 221,157 PS; 1,020+1,351+292 = 2,663 VS), column totals (189,412 + 174,796 + 2,420 = 366,628), and sub-breakdowns (179,602 + 9,810 = 189,412; 105,235 + 69,561 = 174,796; 2,355 + 64 + 1 = 2,420; 2,419 + 1 = 2,420) all reconcile cleanly.
  • Checks run (clean worktree on 03b09a08):
    • python3 -I tests/test_sampler_source_census.py -v: 28/28 OK.
    • py_compile, git diff --check, test_ctest_registration.py (4/4), test_docs_links.py (6/6), test_docs_repo_paths.py (2/2), test_text_write_line_endings.py (3/3), test_text_encoding.py (2/2): all pass.
  • Not independently reproduced: 26,503-shader corpus counts (requires local shader dump).

AI-assisted review.

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A nested dynamic pointer load is currently counted as a static user-pointer offset, which makes the census's static/runtime split inaccurate for that shape. Please propagate dynamic provenance through nested loads and add a two-level regression fixture.

Comment thread tools/sampler_source_census.py Outdated
return "constant", dyn, k
if tag[0] == "code":
return "code", dyn, k
if tag[0] != "ld" or tag[1] in seen or tag[1] not in loads:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve dynamic provenance through nested loads. In the ld case, this ignores dyn returned by load_source() and returns only the dynamic flag from an outer offset wrapper. For example, an s_load_dwordx2 from a user pointer at dynamic index s5 can produce an intermediate pointer, then an s_load_dwordx4 at constant 0x40 through it. The second load is reported as user_pointer/static even though its effective address depends on s5. Propagate the inner flag and add a synthetic two-level pointer test; otherwise the reported static/runtime counts and docs are wrong for this chain.

@rafaelpssz

Copy link
Copy Markdown
Contributor

Correction to my note above: the s_brev_b32 fold is listed as SHADER-769 and @SphyserX already has it in #4289, so I'm not doing it in #2887. #2887 picks the fix up through the index once #4289 lands. I'm running a full-corpus count of literal_samplers with main's shader_meta.py and with #4289's, and I'll post the before/after on #4289.

@Roberto0953

Roberto0953 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews.

@shdann, you were right about load_source: fixed in e206f18 (rebased on main 03b09a0). The result of following a load is remembered per load, so a chain is walked once instead of once per dword. Cycle detection is unchanged, and an answer that met a cycle is not remembered, since it depends on where the walk started.

Calls to load_source on your chain (the class stays user_pointer):

depth 2 3 4 5 12 40
before 5 21 85 341 5,592,405 (16 s) not measured
after 2 3 4 5 12 40

Two tests added (30 in all):

  • chains of depth 2 to 40 need at most 2 calls per load; it fails on the previous code;
  • two cycles (a pointer chased in a loop, a V# that is its own source) terminate and stay undetermined.

The corpus census gives the same JSON field for field, so the counts in the doc stand. The corpus has no deep chains: its run time is not slower (320 s before, 272 s after, one run each), which is not a gain to claim.

@rafaelpssz, thanks for taking the s_brev_b32 fold in #2887.

AI-assisted (Claude Code).

Roberto0953 added a commit to Roberto0953/Leonida that referenced this pull request Nov 23, 2026
… dword

Review of ItsNotRexed#4268 (shdann): load_source worked out the source of a load again for every dword that came from it.
A descriptor that an earlier load produced has four dwords, so a chain of loads asked for the first one
4**depth times: 5, 21, 85 and 341 load_source calls at depth 2 to 5 (5,592,405 at depth 12, 16 s for one
listing), with the class right every time.

What load_source finds for a load is now kept by its code offset and asked for once: 2, 3, 4, 5 and 12 calls at
those depths, 40 at depth 40. The cycle check stays as it was (a load whose address depends on the load itself is
given up), and an answer that ran into a cycle is not kept, because that one depends on where the question
started; an answer that met none does not, so the classes cannot change.

Tests (30, all pass; the first new one fails on the code before this commit with "5 load_source calls for a
chain of 2 loads"):
- a chain of s_buffer_load_dwordx4 V#s and one of s_load_dwordx2 pointers, depth 2 to 40: at most two
  load_source calls per load, counted with sys.setprofile, and the class stays user_pointer; the same chain
  from a fixed table stays other_base;
- a pointer chased in a loop and a V# that is its own source through a loop: both end, both are undetermined,
  and the load before the loop keeps its class.

Corpus (1.0.2.1, 26,503 listings, `--jobs 4 --expect-none other_base`, exit 0): the --json output is equal to
the one of the commit before, field by field, so the counts in docs/d3d12_vulkan.md stand. One run each on the
same machine: 320 s before, 272 s after; the corpus has no deep chain, so read that as "not slower", not as the
gain.

Co-Authored-By: Claude <noreply@anthropic.com>
@Roberto0953
Roberto0953 force-pushed the shader/static-sampler-census branch from a5b6a12 to e206f18 Compare November 23, 2026 00:44
@mrbean56

Copy link
Copy Markdown

Tested a5b6a12e on Linux (Debian 13), Python 3.13.5, CPU only: pass.

python -I tests/test_sampler_source_census.py
Ran 28 tests in 0.749s
OK

python -I tests/test_docs_links.py
Ran 6 tests in 0.056s
OK

The 28 synthetic tests and the documentation links pass here as on the author's machine. I did not have a corpus, so the counts in the description were not re-measured. No GPU, no game data. AI-assisted.

@rafaelpssz

Copy link
Copy Markdown
Contributor

@Roberto0953, small correction: I'm not doing the s_brev_b32 fold after all (see my note above). The coordinator listed it as SHADER-769, and @SphyserX has it in #4289. #2887 picks it up through the index once that lands.

What I can add here is a second corpus. I'm running e206f186's census on my own 1.0.2.1 copy now and will post the class counts next to yours.

@rafaelpssz

Copy link
Copy Markdown
Contributor

Second corpus, as promised: e206f186 on my own 1.0.2.1 copy (Windows 11, CPU only, --jobs 2, counts only). Every number in the description reproduces exactly:

  • 26,503 listings read, none skipped. 14,025 shaders sample, with 366,628 sampling instructions.
  • Per class, all stages: user_pointer 189,412, literal 174,796, user_sgprs 0, other_base 0, undetermined 2,420.
  • Per stage it matches the description's table cell for cell:
    • CS 63,141 / 57,674 / 1
    • MS 10,142 / 9,723 / 2,127
    • PS 115,109 / 106,048 / 0
    • VS 1,020 / 1,351 / 292
  • Literal S#s built with s_brev_b32: 7,103 + 2,794 + 18,483 + 279 = 28,659.
  • Without the s_cbranch_execz skips, the undetermined split is user_pointer 2,419 + literal 1.
  • Largest static S# offset is 0x540, and no constant is added to the pointer.

Run time was 1,575 s with 2 jobs on a 16 GB machine; peak process memory 780 MiB.

So on two independent copies there's no S# read from a driver table.

Roberto0953 and others added 3 commits November 23, 2026 08:04
…n a driver table (SHADER-735)

docs/d3d12_vulkan.md section 3.5 left open whether the console driver hands shaders their static samplers
through a fixed table, which the layer would then have to emulate. tools/sampler_source_census.py follows the
four SGPRs of the sampler operand of every image_sample*, image_gather4* and image_get_lod back to where their
values are made and puts the instruction in one class: held in user SGPRs, loaded through a pointer that starts
from user data, built from immediates, held in or loaded through something else (a constant address, a system
SGPR, a code-relative address: what a driver table would be), or undetermined, with the reason.

It reuses the dataflow of tools/heap_index_census.py and adds what the sampler operands needed: constants built
with s_brev_b32, SGPRs spilled to VGPRs and read back, joins that keep the sources of every path, s_getpc_b64,
and listings with embedded data words re-anchored the way the translator does. --expect-none CLASS turns the
count into a check; --jobs N runs it in parallel.

Measured on the 1.0.2.1 corpus (26,503 listings, none skipped; 366,628 sampling instructions in 14,025 shaders):
189,412 loaded through user data, 174,796 literal, 0 in user SGPRs, 0 from another base, 2,420 undetermined
(0.66%, MS and VS, plus one CS). The undetermined ones all come from one shape, an S# made or saved inside a
region that s_cbranch_execz skips when no lane is active; without the taken edge of those branches the same
analysis classes 2,419 as loaded through user data and 1 as literal. The counts, what they do not show and the
command are in docs/d3d12_vulkan.md next to the static-sampler paragraph; question 3 of section 8.2 is updated.

Tests: tests/test_sampler_source_census.py, 28 cases on hand-written RDNA2 listings, one or more per class, with
negative controls (a fixed-table read on one path or in one dword, a clobbered spill, a branch that is not an
exec-zero skip, --expect-none failing on a fixed-table shader). Also run: compileall on tools and tests,
test_text_write_line_endings, test_docs_cli_flags, test_docs_repo_paths, test_docs_links, test_tool_startup,
test_heap_index_census, scripts/check_no_game_data.py. CPU only; no GPU involved.

Co-Authored-By: Claude <noreply@anthropic.com>
… dword

Review of ItsNotRexed#4268 (shdann): load_source worked out the source of a load again for every dword that came from it.
A descriptor that an earlier load produced has four dwords, so a chain of loads asked for the first one
4**depth times: 5, 21, 85 and 341 load_source calls at depth 2 to 5 (5,592,405 at depth 12, 16 s for one
listing), with the class right every time.

What load_source finds for a load is now kept by its code offset and asked for once: 2, 3, 4, 5 and 12 calls at
those depths, 40 at depth 40. The cycle check stays as it was (a load whose address depends on the load itself is
given up), and an answer that ran into a cycle is not kept, because that one depends on where the question
started; an answer that met none does not, so the classes cannot change.

Tests (30, all pass; the first new one fails on the code before this commit with "5 load_source calls for a
chain of 2 loads"):
- a chain of s_buffer_load_dwordx4 V#s and one of s_load_dwordx2 pointers, depth 2 to 40: at most two
  load_source calls per load, counted with sys.setprofile, and the class stays user_pointer; the same chain
  from a fixed table stays other_base;
- a pointer chased in a loop and a V# that is its own source through a loop: both end, both are undetermined,
  and the load before the loop keeps its class.

Corpus (1.0.2.1, 26,503 listings, `--jobs 4 --expect-none other_base`, exit 0): the --json output is equal to
the one of the commit before, field by field, so the counts in docs/d3d12_vulkan.md stand. One run each on the
same machine: 320 s before, 272 s after; the corpus has no deep chain, so read that as "not slower", not as the
gain.

Co-Authored-By: Claude <noreply@anthropic.com>
…uter load run-time

source() dropped the run-time flag of a load it followed, so an S# read at a constant offset through a pointer
that was itself loaded at a run-time index was counted as user_pointer/static, although its address depends on
the index (review of ItsNotRexed#4268). The flag of the inner load now carries through nested pointers and through a V#.

Test: a two-level and a three-level pointer chain and a V# loaded at a run-time index must be dynamic, with the
same shapes at a constant inner offset staying static; it fails on the previous code (static for dynamic).
The corpus census prints the same output line for line (the corpus has no such shape), so the counts in the
doc stand.

Co-Authored-By: Claude <noreply@anthropic.com>
@Roberto0953

Copy link
Copy Markdown
Contributor Author

@Flyander, thanks: you were right, and it is fixed in c33256c (the branch is rebased on main 3faac55; the conflict with #3494 in docs/d3d12_vulkan.md is resolved, both texts kept).

The defect. source() followed a loaded pointer back to its own load but dropped that load's run-time flag, so only an offset wrapper on the outer step could make the result dynamic. Your shape (s_load_dwordx2 from a user pointer at index s5, then s_load_dwordx4 at 0x40 through the result) came out as user_pointer/static.

The fix. The inner load's flag now carries through: a run-time offset on any load of the chain makes everything read through its result run-time, through nested pointers and through a V# (s_buffer_load). One line of logic, in the ld case.

Regression test (test_a_run_time_offset_on_an_inner_load_makes_the_outer_one_run_time, synthetic listings):

Shape Expected Before the fix
two levels, inner load at a run-time index dynamic static (the test fails)
three levels, first load at a run-time index dynamic static
V# loaded at a run-time index, then s_buffer_load at a constant dynamic static
the same two- and three-level shapes with a constant inner offset (controls) static static

31 tests pass with the fix (30 before, plus this one).

Counts. I re-ran the corpus census with the fix: the output is the same line for line as before it, including the static/run-time split (179,602 / 9,810) and the 0x540 largest static offset. The corpus has no S# read through a pointer loaded at a run-time index, so the numbers in the doc stand; the split was wrong for the shape, not for this corpus.

Also re-run after the rebase: the docs tests (links, table rows, list items, CLI flags, repo paths), test_text_write_line_endings, test_heap_index_census, test_tool_startup, scripts/check_no_game_data.py, git diff --check.

Could you take another look?

AI-assisted (Claude Code).

@kapitche

Copy link
Copy Markdown
Contributor

Tested c33256c merged with main 3faac55 on Linux (WSL2), Python 3.12.16: pass.
Ran tests/test_sampler_source_census.py (31 OK), the neighbouring tests/test_heap_index_census.py (OK) and 7 tests/test_docs_*.py files (cli_flags, links, repo_paths, table_rows, list_items, env_vars, python_deps): all OK.
Negative control: tools/sampler_source_census.py is a new file and does not exist on main, so the new tests have nothing to import against main's tree (they cannot pass there).
Docs read: the new SHADER-735 table is internally consistent (stage rows sum to 366,628 and 2,420 undetermined; 179,602 + 9,810 = 189,412; 105,235 + 69,561 = 174,796; 2,355 + 64 + 1 = 2,420; 2,420 / 366,628 = 0.66%). The corpus-level counts need the game dump and were not re-run here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants