upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorKosmabb8 <116897251+Kosmabb8@users.noreply.github.com>2026-11-22 21:41:44 +0100
committerKosmabb8 <116897251+Kosmabb8@users.noreply.github.com>2026-11-22 21:41:44 +0100
commitb60f67a1b917bc4d53662737c36867e2f08a8fce (patch)
tree5348881b1b47b23cd73379847070f2d5c525b119 /scripts
parent134b936f2e594c20547f859922b2f3b8ce93fdbe (diff)
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
mission_tables: merge upstream and retain PSIN scan boundary
Diffstat (limited to 'scripts')
-rw-r--r--scripts/audit_shader4_regs.py7
-rw-r--r--scripts/bench_wave64.py13
-rw-r--r--scripts/build_llvm_mc.ps14
-rw-r--r--scripts/build_runtime.ps110
-rw-r--r--scripts/carve_all.ps120
-rw-r--r--scripts/first_look.ps19
-rw-r--r--scripts/meta_to_xml.ps14
-rw-r--r--scripts/run_gpu_tests.py71
-rw-r--r--scripts/run_wine_tests.py5
-rw-r--r--scripts/vs_input_survey.py138
10 files changed, 260 insertions, 21 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py
index 6bc3b42af..b9a39b43a 100644
--- a/scripts/audit_shader4_regs.py
+++ b/scripts/audit_shader4_regs.py
@@ -224,7 +224,8 @@ def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), l
224 dxbc_dir = dxbc_dir or parent 224 dxbc_dir = dxbc_dir or parent
225 stage_map = load_stage_map(disasm_dir) 225 stage_map = load_stage_map(disasm_dir)
226 226
227 files = sorted(f for f in os.listdir(disasm_dir) if f.endswith(".s")) 227 with os.scandir(disasm_dir) as it:
228 files = sorted(e.name for e in it if e.name.endswith(".s") and e.is_file())
228 if limit is not None: 229 if limit is not None:
229 files = files[:limit] 230 files = files[:limit]
230 231
@@ -382,4 +383,8 @@ def main(argv=None):
382 383
383 384
384if __name__ == "__main__": 385if __name__ == "__main__":
386 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
387 sys.stdout.reconfigure(errors="replace")
388 except (AttributeError, ValueError, OSError):
389 pass
385 sys.exit(main()) 390 sys.exit(main())
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index b41c6e97e..3d77bc2bc 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -3,7 +3,7 @@
3 python -I scripts/bench_wave64.py [--build DIR] [--llvm-mc PATH] [--groups N] [--reps N] [--procs N] [--shader NAME] 3 python -I scripts/bench_wave64.py [--build DIR] [--llvm-mc PATH] [--groups N] [--reps N] [--procs N] [--shader NAME]
4 4
5Three configurations: AMD with its native 64-wide subgroup (no flag), AMD with --wave64-emulate, NVIDIA with 5Three configurations: AMD with its native 64-wide subgroup (no flag), AMD with --wave64-emulate, NVIDIA with
6--wave64-emulate (the GPU is chosen with VK_LOADER_DRIVERS_SELECT='*amd*' / '*nv*'). Each runs `procs` processes of 6--wave64-emulate (the GPU is chosen with VK_LOADER_DRIVERS_SELECT='*amd*,*radeon*' / '*nv*'). Each runs `procs` processes of
7vk_compute_test with VKC_BENCH=`reps` timed dispatches of `groups` workgroups; the table gives the median over all 7vk_compute_test with VKC_BENCH=`reps` timed dispatches of `groups` workgroups; the table gives the median over all
8dispatches, the spread of the per-process medians (other programs share the GPU, so look at it), the number of 8dispatches, the spread of the per-process medians (other programs share the GPU, so look at it), the number of
9translated segments (static: blocks + continuation segments; every continuation segment is one more workgroup barrier 9translated segments (static: blocks + continuation segments; every continuation segment is one more workgroup barrier
@@ -20,7 +20,7 @@ import tempfile
20 20
21ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 21ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22BUILD_PY = os.path.join(ROOT, "runtime", "test", "shaders", "build.py") 22BUILD_PY = os.path.join(ROOT, "runtime", "test", "shaders", "build.py")
23CONFIGS = [("AMD native", "*amd*", False), ("AMD --wave64-emulate", "*amd*", True), 23CONFIGS = [("AMD native", "*amd*,*radeon*", False), ("AMD --wave64-emulate", "*amd*,*radeon*", True),
24 ("NVIDIA --wave64-emulate", "*nv*", True)] 24 ("NVIDIA --wave64-emulate", "*nv*", True)]
25 25
26 26
@@ -52,7 +52,10 @@ def run(tools, spv, groups, reps, driver, emulate):
52 args = [os.path.join(tools, "vk_compute_test" + (".exe" if os.name == "nt" else "")), spv, str(groups), "dump"] 52 args = [os.path.join(tools, "vk_compute_test" + (".exe" if os.name == "nt" else "")), spv, str(groups), "dump"]
53 if not emulate: 53 if not emulate:
54 args.append("--require-wave64") 54 args.append("--require-wave64")
55 r = subprocess.run(args, env=env, capture_output=True, text=True) 55 try:
56 r = subprocess.run(args, env=env, capture_output=True, text=True)
57 except OSError as e:
58 return None, f"{args[0]}: {e}", None
56 out = r.stdout + r.stderr 59 out = r.stdout + r.stderr
57 m = re.search(r"bench ms: median=([\d.]+) min=([\d.]+) max=([\d.]+)", out) 60 m = re.search(r"bench ms: median=([\d.]+) min=([\d.]+) max=([\d.]+)", out)
58 h = re.search(r"bench out fnv1a: (\w+)", out) 61 h = re.search(r"bench out fnv1a: (\w+)", out)
@@ -123,4 +126,8 @@ def main():
123 126
124 127
125if __name__ == "__main__": 128if __name__ == "__main__":
129 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
130 sys.stdout.reconfigure(errors="replace")
131 except (AttributeError, ValueError, OSError):
132 pass
126 sys.exit(main()) 133 sys.exit(main())
diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1
index e66b7df86..657820154 100644
--- a/scripts/build_llvm_mc.ps1
+++ b/scripts/build_llvm_mc.ps1
@@ -70,8 +70,10 @@ $body = @"
70"@ 70"@
71New-Item -ItemType Directory -Force $out | Out-Null 71New-Item -ItemType Directory -Force $out | Out-Null
72# A .cmd file avoids cmd.exe's quote stripping on paths with spaces. 72# A .cmd file avoids cmd.exe's quote stripping on paths with spaces.
73# Switch cmd.exe to UTF-8 before it reads the paths in the batch file.
73$bat = Join-Path $Temp "_build.cmd" 74$bat = Join-Path $Temp "_build.cmd"
74"@echo off`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat 75$batchText = "@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body`r`n"
76[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false))
75 77
76$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru 78$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru
77$null = $p.Handle # keeps the exit code readable after WaitForExit 79$null = $p.Handle # keeps the exit code readable after WaitForExit
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index b251a281c..abc8c3f05 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -21,10 +21,12 @@ $cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe"
21$ninja = Join-Path $cmakeDir "Ninja\ninja.exe" 21$ninja = Join-Path $cmakeDir "Ninja\ninja.exe"
22$cfg = if ($Debug) { "Debug" } else { "RelWithDebInfo" } 22$cfg = if ($Debug) { "Debug" } else { "RelWithDebInfo" }
23$sdl = if ($FetchSdl3) { "-DLEONIDA_SDL3_FETCH=ON" } else { "" } 23$sdl = if ($FetchSdl3) { "-DLEONIDA_SDL3_FETCH=ON" } else { "" }
24# With VULKAN_SDK set, a configure that still finds no Vulkan headers fails instead of dropping the Vulkan D3D12 device.
25$vk = if ($env:VULKAN_SDK) { "-DLEONIDA_REQUIRE_VULKAN=ON" } else { "" }
24 26
25if ((Test-Path $cmake) -and (Test-Path $ninja)) { 27if ((Test-Path $cmake) -and (Test-Path $ninja)) {
26 $body = @" 28 $body = @"
27"$cmake" -S "$src" -B "$out" -G Ninja "-DCMAKE_MAKE_PROGRAM=$ninja" -DCMAKE_BUILD_TYPE=$cfg $sdl || exit /b 1 29"$cmake" -S "$src" -B "$out" -G Ninja "-DCMAKE_MAKE_PROGRAM=$ninja" -DCMAKE_BUILD_TYPE=$cfg $sdl $vk || exit /b 1
28"$cmake" --build "$out" -j $jobs || exit /b 1 30"$cmake" --build "$out" -j $jobs || exit /b 1
29"@ 31"@
30} else { 32} else {
@@ -33,7 +35,7 @@ if ((Test-Path $cmake) -and (Test-Path $ninja)) {
33 Write-Warning "VS C++ CMake tools not found: building with cl.exe directly, without the GameInput shim (SDL3). Install the CMake tools component to get it." 35 Write-Warning "VS C++ CMake tools not found: building with cl.exe directly, without the GameInput shim (SDL3). Install the CMake tools component to get it."
34 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" 36 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue"
35 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } 37 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" }
36 $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } 38 $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" }
37 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" 39 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`""
38 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } 40 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" }
39 $body = @" 41 $body = @"
@@ -61,7 +63,9 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO
61# Switch to UTF-8 (CP 65001) before invoking CMake/Ninja/cl.exe so non-English MSVC /showIncludes prefixes 63# Switch to UTF-8 (CP 65001) before invoking CMake/Ninja/cl.exe so non-English MSVC /showIncludes prefixes
62# (e.g. Spanish "Nota: inclusión del archivo:") match Ninja's msvc_deps_prefix instead of being mojibaked in OEM CP. 64# (e.g. Spanish "Nota: inclusión del archivo:") match Ninja's msvc_deps_prefix instead of being mojibaked in OEM CP.
63$bat = Join-Path $out "_build.cmd" 65$bat = Join-Path $out "_build.cmd"
64"@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat 66# Keep the paths encoded for CP 65001 and start with an ASCII command that cmd.exe can read before switching.
67$batchText = "@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body`r`n"
68[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false))
65 69
66$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru 70$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru
67$null = $p.Handle # keeps the exit code readable after WaitForExit 71$null = $p.Handle # keeps the exit code readable after WaitForExit
diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1
index 6229941f8..6819e4376 100644
--- a/scripts/carve_all.ps1
+++ b/scripts/carve_all.ps1
@@ -9,13 +9,27 @@ $Game = (Resolve-Path -LiteralPath $Game).ProviderPath
9# FullName paths. Deriving the prefix from Resolve-Path then cuts the wrong number of characters and 9# FullName paths. Deriving the prefix from Resolve-Path then cuts the wrong number of characters and
10# re-carves already-caved archives; use the canonical form for both sides of the Substring. 10# re-carves already-caved archives; use the canonical form for both sides of the Substring.
11$prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\' 11$prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\'
12$rows = @() 12$destinations = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::OrdinalIgnoreCase)
13foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -Filter *.rpf | Sort-Object Length) { 13# Validate every destination before accepting any cached index or starting a carve.
14$archives = foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -Filter *.rpf | Sort-Object Length) {
14 $rel = $f.FullName.Substring($prefix.Length) 15 $rel = $f.FullName.Substring($prefix.Length)
15 $dest = Join-Path $Out ([IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_"))) 16 $name = [IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_"))
17 if ($destinations.ContainsKey($name)) {
18 throw ("Archives '{0}' and '{1}' both map to '{2}'." -f $destinations[$name], $rel, $name)
19 }
20 $destinations.Add($name, $rel)
21 [pscustomobject]@{ file = $f; relative = $rel; destination = Join-Path $Out $name }
22}
23
24$rows = @()
25foreach ($archive in $archives) {
26 $f = $archive.file
27 $rel = $archive.relative
28 $dest = $archive.destination
16 if (-not (Test-Path -LiteralPath (Join-Path $dest "index.json"))) { 29 if (-not (Test-Path -LiteralPath (Join-Path $dest "index.json"))) {
17 Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB)) 30 Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB))
18 python -I $tool $f.FullName $dest | Select-Object -Last 1 31 python -I $tool $f.FullName $dest | Select-Object -Last 1
32 if ($LASTEXITCODE -ne 0) { throw "Carving $rel failed (exit $LASTEXITCODE)" }
19 } 33 }
20 $s = (Get-Content -LiteralPath (Join-Path $dest "index.json") -Raw | ConvertFrom-Json).summary 34 $s = (Get-Content -LiteralPath (Join-Path $dest "index.json") -Raw | ConvertFrom-Json).summary
21 $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span 35 $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span
diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1
index 66327a1dd..5871cbc67 100644
--- a/scripts/first_look.ps1
+++ b/scripts/first_look.ps1
@@ -27,7 +27,13 @@ if ($LASTEXITCODE -ne 0) { throw "pe_inspect failed" }
27$rt = Join-Path $root "runtime\build\gta6rt.exe" 27$rt = Join-Path $root "runtime\build\gta6rt.exe"
28if (-not (Test-Path $rt)) { & (Join-Path $PSScriptRoot "build_runtime.ps1") } 28if (-not (Test-Path $rt)) { & (Join-Path $PSScriptRoot "build_runtime.ps1") }
29Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)" 29Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)"
30& $rt --dry-run $Exe --game-dir $GameDir 2>&1 | Tee-Object (Join-Path $out "dryrun.txt") | Select-Object -Last 40 30& {
31 # Keep native stderr in the report without letting Windows PowerShell stop the dry run on it.
32 $ErrorActionPreference = "Continue"
33 $PSNativeCommandUseErrorActionPreference = $false
34 & $rt --dry-run $Exe --game-dir $GameDir 2>&1
35} | Tee-Object (Join-Path $out "dryrun.txt") | Select-Object -Last 40
36$dryRunExitCode = $LASTEXITCODE
31 37
32# Shim to-do list, grouped by DLL, most functions first. 38# Shim to-do list, grouped by DLL, most functions first.
33$report = Get-Content (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json 39$report = Get-Content (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json
@@ -39,3 +45,4 @@ $lines
39$enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } 45$enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name }
40if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } 46if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" }
41Write-Host "`nReports: $out" 47Write-Host "`nReports: $out"
48exit $dryRunExitCode
diff --git a/scripts/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1
index 2efe0c32a..065ad4145 100644
--- a/scripts/meta_to_xml.ps1
+++ b/scripts/meta_to_xml.ps1
@@ -1,7 +1,7 @@
1# Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers. 1# Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers.
2# Run in Windows PowerShell 5.1. 2# Run in Windows PowerShell 5.1.
3# .\meta_to_xml.ps1 -Carve <work>\carve -Out <work>\meta [-Limit N] 3# .\meta_to_xml.ps1 -Carve <work>\carve -Out <work>\meta [-Limit N]
4# Each blob becomes <Out>\<archive>\<offset>.xml. Failures go to <Out>\failures.txt with the parser's message. 4# Each blob becomes <Out>\<archive>\<offset>.xml. Failures go to <Out>\failures.txt with the error message.
5param( 5param(
6 [string]$Carve = "<work>\carve", 6 [string]$Carve = "<work>\carve",
7 [string]$Out = "<work>\meta", 7 [string]$Out = "<work>\meta",
@@ -29,9 +29,9 @@ foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) {
29 if ($Limit -and $n -ge $Limit) { break } 29 if ($Limit -and $n -ge $Limit) { break }
30 $n++ 30 $n++
31 $name = "{0:x12}" -f [int64]$r.off 31 $name = "{0:x12}" -f [int64]$r.off
32 $bytes = [IO.File]::ReadAllBytes((Join-Path $dir.FullName "$name.bin"))
33 $kind = if ($r.head.StartsWith("5053494e")) { "pso" } else { "rbf" } 32 $kind = if ($r.head.StartsWith("5053494e")) { "pso" } else { "rbf" }
34 try { 33 try {
34 $bytes = [IO.File]::ReadAllBytes((Join-Path $dir.FullName "$name.bin"))
35 if ($kind -eq "pso") { 35 if ($kind -eq "pso") {
36 $f = New-Object CodeWalker.GameFiles.PsoFile; $f.Load($bytes) 36 $f = New-Object CodeWalker.GameFiles.PsoFile; $f.Load($bytes)
37 $xml = [CodeWalker.GameFiles.PsoXml]::GetXml($f) 37 $xml = [CodeWalker.GameFiles.PsoXml]::GetXml($f)
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 3a23250fc..7cd0e9dbf 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -38,7 +38,7 @@ from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: tex
38from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT) 38from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT)
39from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS 39from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS
40from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, 40from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip,
41 vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py 41 unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py
42from check import PIXEL_VERTEX, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks 42from check import PIXEL_VERTEX, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks
43from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries 43from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries
44from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide 44from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide
@@ -294,6 +294,11 @@ def w64_emulated() -> bool:
294 # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates 294 # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates
295 # the trailing space cmd.exe's `set VAR=1 &` leaves in the value. 295 # the trailing space cmd.exe's `set VAR=1 &` leaves in the value.
296 return (os.environ.get("LEONIDA_W64_EMULATE") or "").strip().lower() in ("1", "true", "yes", "on") 296 return (os.environ.get("LEONIDA_W64_EMULATE") or "").strip().lower() in ("1", "true", "yes", "on")
297def pc_tail_ubo() -> bool:
298 # LEONIDA_PC_TAIL_UBO=1: translate with --pc-tail-ubo (s0..s31 in 128 push-constant bytes, the tail in a uniform
299 # block at set 1), for devices whose maxPushConstantsSize is 128. The test programs read the same variable
300 # (runtime/test/vk_pc_tail.h) and bind the block; same accepted values as LEONIDA_W64_EMULATE.
301 return (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on")
297def wavemask_check(vk_compute: str, spv: str, env: dict | None, emulated: bool) -> tuple[bool | None, str]: 302def wavemask_check(vk_compute: str, spv: str, env: dict | None, emulated: bool) -> tuple[bool | None, str]:
298 """cs_wavemask, as in check.py: (passed, detail), passed None for a skip. The native build needs a 64-wide 303 """cs_wavemask, as in check.py: (passed, detail), passed None for a skip. The native build needs a 64-wide
299 subgroup and skips where the device has none; with LEONIDA_W64_EMULATE=1 it was translated with 304 subgroup and skips where the device has none; with LEONIDA_W64_EMULATE=1 it was translated with
@@ -312,6 +317,22 @@ def dump_words(msg: str) -> list[int] | None:
312 return [int(x) for x in m.group(1).split()] if m else None 317 return [int(x) for x in m.group(1).split()] if m else None
313 318
314 319
320def subgroup_pin_skip(msg: str, cs_env: dict | None) -> Skip | None:
321 """A Skip when the runner asked for a subgroup size (VKC_SUBGROUP_SIZE) and vk_compute_test says this device
322 cannot pin it, so the dispatched words are not the ones the fixture was written for. Only for the dumps in
323 WAVE32_PIN_DUMPS: everything else the runner judges at the device's own width, which is how cs_store and the
324 cs_w32_* fixtures keep being tested on a 64-only device (check.py is conservative and skips all of them)."""
325 if cs_env and "VKC_SUBGROUP_SIZE" in cs_env:
326 return unpinned_subgroup_skip(msg)
327 return None
328
329
330# Dumps whose expected words depend on the wave width but are not lane-mask dumps (those are WAVE32_LANE_DUMPS):
331# cs_barrier_loop's trip count is 4 waves of 32, so at 64 lanes it writes a different pattern and the words would
332# report a failure that is really an unpinnable wave size (GCN3/GCN4 expose 64..64 only).
333WAVE32_PIN_DUMPS = ("cs_barrier_loop",)
334
335
315def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial: bool, emulated: bool, 336def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial: bool, emulated: bool,
316 hexwords: bool = False) -> tuple[bool | None, str]: 337 hexwords: bool = False) -> tuple[bool | None, str]:
317 """Judge one vk_compute_test "dump" run: (True, words), (False, why), or (None, why) when the device can't run it. 338 """Judge one vk_compute_test "dump" run: (True, words), (False, why), or (None, why) when the device can't run it.
@@ -557,7 +578,8 @@ DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_textur
557 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", 578 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm",
558 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", 579 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm",
559 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", 580 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm",
560 SIGNED_MIP_TEST: "vs_ids.asm"} 581 SIGNED_MIP_TEST: "vs_ids.asm",
582 "vs_base_ids": "ps_flat.asm"}
561DRAWN_WITH.update({name: "vs_ids.asm" for name in GET_LOD_TESTS}) 583DRAWN_WITH.update({name: "vs_ids.asm" for name in GET_LOD_TESTS})
562 584
563 585
@@ -721,6 +743,8 @@ def run_suite(a, work: str) -> int:
721 cmd.append("--texel-offset-fallback") 743 cmd.append("--texel-offset-fallback")
722 if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py 744 if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py
723 cmd.append("--mesh-compute") 745 cmd.append("--mesh-compute")
746 if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1
747 cmd.append("--pc-tail-ubo")
724 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr"): # fused multiply-add: GLSL Fma or OpFmaKHR (docs/design.md) 748 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr"): # fused multiply-add: GLSL Fma or OpFmaKHR (docs/design.md)
725 cmd += ["--fma", os.environ["LEONIDA_FMA"]] 749 cmd += ["--fma", os.environ["LEONIDA_FMA"]]
726 rc, out = run_cmd(cmd, gpu=False) 750 rc, out = run_cmd(cmd, gpu=False)
@@ -809,7 +833,7 @@ def run_suite(a, work: str) -> int:
809 results.append((name, ok, problem or f"4096 pixels in each of {len(GET_LOD_TESTS[name])} draw(s): the " 833 results.append((name, ok, problem or f"4096 pixels in each of {len(GET_LOD_TESTS[name])} draw(s): the "
810 "clamped and the calculated LOD within 1/16")) 834 "clamped and the calculated LOD within 1/16"))
811 elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", "cs_oob_select", "cs_oob_tail", 835 elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", "cs_oob_select", "cs_oob_tail",
812 "cs_buf_swizzle", "cs_cmpx_class_f32", "cs_cvt_pk_u8"): 836 "cs_buf_swizzle", "cs_cmpx_class_f32", "cs_cvt_pk_u8", "cs_buf_load_sub", "cs_buf_fmt8"):
813 # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds 837 # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds
814 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. 838 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement.
815 # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either. 839 # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either.
@@ -831,6 +855,9 @@ def run_suite(a, work: str) -> int:
831 0xBEEF0001], 855 0xBEEF0001],
832 "cs_cmpx_class_f32": CMPX_CLASS_WORDS, 856 "cs_cmpx_class_f32": CMPX_CLASS_WORDS,
833 "cs_cvt_pk_u8": CVT_PK_U8_WORDS, 857 "cs_cvt_pk_u8": CVT_PK_U8_WORDS,
858 # TEST-510: sub-dword MUBUF loads (RAW end check by element size) and GFX10_FORMAT_8_UINT
859 "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0],
860 "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1],
834 }[name] 861 }[name]
835 words = dump_words(msg) 862 words = dump_words(msg)
836 vals = words[:len(want)] if words else [] 863 vals = words[:len(want)] if words else []
@@ -867,6 +894,14 @@ def run_suite(a, work: str) -> int:
867 vals = words[:len(USER_SGPRS_WORDS)] if words else [] 894 vals = words[:len(USER_SGPRS_WORDS)] if words else []
868 results.append((name, rc == 0 and vals == USER_SGPRS_WORDS, 895 results.append((name, rc == 0 and vals == USER_SGPRS_WORDS,
869 " ".join(hex(x) for x in vals) if vals else msg)) 896 " ".join(hex(x) for x in vals) if vals else msg))
897 elif name == "cs_f64_add":
898 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env)
899 if rc == 77:
900 results.append((name, None, "SKIP (no shaderFloat64 on this device)"))
901 else:
902 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False,
903 hexwords=True)
904 results.append((name, ok, detail))
870 elif name == "cs_cvt_f32_sat": 905 elif name == "cs_cvt_f32_sat":
871 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). 906 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS).
872 wrong = [] 907 wrong = []
@@ -1003,6 +1038,10 @@ def run_suite(a, work: str) -> int:
1003 cs_env = dict(os.environ, **WAVE32_LANE_ENV) 1038 cs_env = dict(os.environ, **WAVE32_LANE_ENV)
1004 rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) 1039 rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env)
1005 skip = wave32_lane_skip(msg) if name in WAVE32_LANE_DUMPS else None 1040 skip = wave32_lane_skip(msg) if name in WAVE32_LANE_DUMPS else None
1041 if skip is None and name in WAVE32_PIN_DUMPS:
1042 # the device may not be able to run the wave size this fixture was written for (a 64-only device
1043 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too
1044 skip = subgroup_pin_skip(msg, cs_env)
1006 if skip: # e.g. Mesa llvmpipe's 8-wide subgroups: these 32-lane masks can't come out right 1045 if skip: # e.g. Mesa llvmpipe's 8-wide subgroups: these 32-lane masks can't come out right
1007 ok, detail = None, str(skip) 1046 ok, detail = None, str(skip)
1008 else: 1047 else:
@@ -1080,7 +1119,7 @@ def run_suite(a, work: str) -> int:
1080 problem = sampler_test(a.build, spirv_dir) 1119 problem = sampler_test(a.build, spirv_dir)
1081 results.append((name, None if isinstance(problem, Skip) else not problem, 1120 results.append((name, None if isinstance(problem, Skip) else not problem,
1082 problem or f"{len(SAMPLER_CASES)} S#/T# cases, 4096 pixels each exact")) 1121 problem or f"{len(SAMPLER_CASES)} S#/T# cases, 4096 pixels each exact"))
1083 elif name in ("ps_texoff", "ps_texoff_implicit"): 1122 elif name in ("ps_texoff", "ps_texoff_implicit", "ps_texoff_forms"):
1084 # Texel offsets: needs vk_texture_test's texture, sampler and descriptor table (vk_harness binds none), 1123 # Texel offsets: needs vk_texture_test's texture, sampler and descriptor table (vk_harness binds none),
1085 # and VK_KHR_maintenance8 for the non-constant Offset; the tool exits 77 without it. 1124 # and VK_KHR_maintenance8 for the non-constant Offset; the tool exits 77 without it.
1086 raw = os.path.join(raw_dir, f"{name}.raw") 1125 raw = os.path.join(raw_dir, f"{name}.raw")
@@ -1092,7 +1131,7 @@ def run_suite(a, work: str) -> int:
1092 results.append((name, False, msg)) 1131 results.append((name, False, msg))
1093 else: 1132 else:
1094 with open(raw, "rb") as f: 1133 with open(raw, "rb") as f:
1095 problem, covered = texoff_problem(f.read(), msg) 1134 problem, covered = texoff_problem(f.read(), msg, name=name)
1096 results.append((name, not problem, problem or f"4096/4096 pixels exact ({covered})")) 1135 results.append((name, not problem, problem or f"4096/4096 pixels exact ({covered})"))
1097 elif name in OTHER_HARNESS: 1136 elif name in OTHER_HARNESS:
1098 results.append((name, None, f"SKIP (run by {OTHER_HARNESS[name]})")) 1137 results.append((name, None, f"SKIP (run by {OTHER_HARNESS[name]})"))
@@ -1125,6 +1164,7 @@ def run_suite(a, work: str) -> int:
1125 "ps_ops4": (0x34000010, 0x00120800, 0xBEEF0000, 0x12343C00), 1164 "ps_ops4": (0x34000010, 0x00120800, 0xBEEF0000, 0x12343C00),
1126 "ps_scc": (1, 1, 3, 0x80000000), 1165 "ps_scc": (1, 1, 3, 0x80000000),
1127 "ps_sdwa": (0x000000F1, 0xBFFEFFF2, 0x3C003344, 0xBFF70000), 1166 "ps_sdwa": (0x000000F1, 0xBFFEFFF2, 0x3C003344, 0xBFF70000),
1167 "ps_sdwa_dword_hi": (0x00004000, 0x00000003, 0x00004700, 0x0000C000), # 16-bit SDWA, dst_sel:DWORD
1128 "ps_legacy_mul": (0, 0, 0, 0x40C00000), # same expectation as check.py 1168 "ps_legacy_mul": (0, 0, 0, 0x40C00000), # same expectation as check.py
1129 "ps_ops5": (0x12340010, 0xBEEF0800, 0xAAAAFFFF, 0xDEADBC00), # from the .asm headers 1169 "ps_ops5": (0x12340010, 0xBEEF0800, 0xAAAAFFFF, 0xDEADBC00), # from the .asm headers
1130 "ps_ops6": (0xF800FFFF, 0x01000010, 0x00800800, 0x8000FFF0), 1170 "ps_ops6": (0xF800FFFF, 0x01000010, 0x00800800, 0x8000FFF0),
@@ -1157,6 +1197,10 @@ def run_suite(a, work: str) -> int:
1157 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000), 1197 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000),
1158 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) 1198 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers)
1159 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), 1199 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000),
1200 "ps_vcmp_f16": (0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA), # 16-bit float v_cmp e32 (.asm header)
1201 "ps_vcmp_f16_e64": (0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9), # same, e64 with swapped operands
1202 "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header)
1203 "ps_vcmpx_f16_e64": (0x64C11100, 0x6CF171C1, 0x67C71D18, 0x6FF77DD9), # same, e64 with swapped operands
1160 "ps_cvt_off": (0xBF000000, 0x3EE00000, 0xBE800000, 0x3F800000), 1204 "ps_cvt_off": (0xBF000000, 0x3EE00000, 0xBE800000, 0x3F800000),
1161 "ps_fmac_f16_mods": (0xAAAA3C00, 0xAAAA3E00, 0xAAAA0000, 0xAAAA4000), 1205 "ps_fmac_f16_mods": (0xAAAA3C00, 0xAAAA3E00, 0xAAAA0000, 0xAAAA4000),
1162 "ps_vop3_const_mods": (0xC0000000, 0xBF800000, 0x3F800000, 0xAAAABC00), 1206 "ps_vop3_const_mods": (0xC0000000, 0xBF800000, 0x3F800000, 0xAAAABC00),
@@ -1268,6 +1312,19 @@ def run_suite(a, work: str) -> int:
1268 else: 1312 else:
1269 ok, detail = check_clip_half(raw, 0.5, 1.0) 1313 ok, detail = check_clip_half(raw, 0.5, 1.0)
1270 results.append((name, ok, detail)) 1314 results.append((name, ok, detail))
1315 elif name == "vs_base_ids":
1316 # Zero-based v0 / v3 (the hardware's VS input VGPRs): drawn with firstVertex 16 and firstInstance 7,
1317 # ps_flat must still see vertex 0 of instance 0 (0x101), as check.py checks.
1318 raw = os.path.join(raw_dir, f"{name}.raw")
1319 env = dict(gfx_env or os.environ, VKH_DRAW="16,7")
1320 rc, msg = run_cmd([vk_harness, spv, os.path.join(spirv_dir, "ps_flat.spv"), raw], env=env)
1321 if rc == UNSUPPORTED:
1322 results.append((name, None, unsupported_skip(msg)))
1323 elif rc != 0:
1324 results.append((name, False, msg))
1325 else:
1326 ok, detail = check_flat(raw)
1327 results.append((name, ok, detail))
1271 1328
1272 if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed" 1329 if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed"
1273 names = [os.path.splitext(f)[0] for f in asm_files] 1330 names = [os.path.splitext(f)[0] for f in asm_files]
@@ -1297,4 +1354,8 @@ def run_suite(a, work: str) -> int:
1297 1354
1298 1355
1299if __name__ == "__main__": 1356if __name__ == "__main__":
1357 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
1358 sys.stdout.reconfigure(errors="replace")
1359 except (AttributeError, ValueError, OSError):
1360 pass
1300 sys.exit(main()) 1361 sys.exit(main())
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index 28c7f2f63..9154dea48 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -215,10 +215,11 @@ def read_tests(path: str) -> list[dict] | None:
215 except (OSError, ValueError) as e: 215 except (OSError, ValueError) as e:
216 print(f"ERROR: cannot read {path}: {e}", file=sys.stderr) 216 print(f"ERROR: cannot read {path}: {e}", file=sys.stderr)
217 return None 217 return None
218 if not isinstance(doc, dict) or not isinstance(doc.get("tests", []), list): 218 tests = doc.get("tests") if isinstance(doc, dict) else None
219 if not isinstance(tests, list) or not all(isinstance(t, dict) for t in tests):
219 print(f"ERROR: {path} is not the output of ctest --show-only=json-v1", file=sys.stderr) 220 print(f"ERROR: {path} is not the output of ctest --show-only=json-v1", file=sys.stderr)
220 return None 221 return None
221 return doc.get("tests", []) 222 return tests
222 223
223 224
224def main() -> int: 225def main() -> int:
diff --git a/scripts/vs_input_survey.py b/scripts/vs_input_survey.py
new file mode 100644
index 000000000..89e648364
--- /dev/null
+++ b/scripts/vs_input_survey.py
@@ -0,0 +1,138 @@
1"""SHADER-33: which hardware vertex-shader layout the corpus uses (legacy VS or NGG), and which input VGPRs it reads.
2
3 python -I scripts/vs_input_survey.py <work>/shaders/dxbc [--json OUT]
4
5Reads <dxbc>/index.json (stage per shader) and <dxbc>/disasm/<name>.s (shader_disasm.py) for every vertex shader and
6prints counts only:
7
8- NGG markers: `exp prim` (primitive export), `s_sendmsg` (NGG needs GS_ALLOC_REQ) and `v_mbcnt` (NGG thread ids).
9 A legacy (non-NGG) hardware VS has none of them and exports `pos0` / `param` only.
10- Registers read before written, straight-line, from the start of the program: the same rule as #240's
11 scripts/audit_shader4_regs.py (by @eIBart0) uses for CS/MS/GS. In the legacy GFX10 VS layout (Mesa
12 radv_shader_args.c, declare_vs_input_vgprs, not is_ngg) v0 = vertex id, v1 unused, v2 = primitive id,
13 v3 = instance id; in an NGG VS merged with GS the VS inputs start at v5 (vertex id) / v8 (instance id).
14- The fetch call: `s_swappc_b64 s[4:5], s[4:5]` at the start of a VS calls the driver's fetch program, which reads
15 v0 itself and leaves the attributes in v4 and up.
16
17Standard library only. Nothing from the game is printed or written beyond counts.
18"""
19import argparse
20import json
21import os
22import re
23import sys
24from collections import Counter
25
26ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27sys.path.insert(0, os.path.join(ROOT, "tools"))
28import shader_ir # noqa: E402
29
30NO_DEST_OPS = ("s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", "s_branch", "s_cbranch", "s_waitcnt", "s_barrier",
31 "s_nop", "s_endpgm", "s_sendmsg", "s_sleep", "exp", "buffer_store", "global_store", "flat_store",
32 "scratch_store", "image_store", "ds_write")
33PRIM_EXPORT = re.compile(r"^\s*exp\s+prim\b", re.M)
34POS0_EXPORT = re.compile(r"^\s*exp\s+pos0\b", re.M)
35PARAM_EXPORT = re.compile(r"^\s*exp\s+param\d+\b", re.M)
36SENDMSG = re.compile(r"^\s*s_sendmsg\b", re.M)
37MBCNT = re.compile(r"\bv_mbcnt_(lo|hi)_u32_b32\b")
38FETCH_CALL = re.compile(r"^\s*s_swappc_b64\s+s\[4:5\],\s*s\[4:5\]", re.M)
39
40
41def base_op(op):
42 for sfx in ("_e32", "_e64", "_sdwa", "_dpp"):
43 if op.endswith(sfx):
44 return op[:-len(sfx)]
45 return op
46
47
48def read_before_write(insns):
49 """(SGPRs, VGPRs) read before any write, straight-line from the first instruction."""
50 written_s, written_v, read_s, read_v = set(), set(), set(), set()
51 for ins in insns:
52 op, args = base_op(ins["op"]), ins["args"]
53 if not args:
54 continue
55 no_dest = op.startswith(NO_DEST_OPS)
56 dst_read = "fmac" in op or "mac_" in op or op in ("v_writelane_b32", "v_swap_b32") or "_atomic_" in op
57 if not no_dest and op.startswith("v_") and "_co_" in op and "_ci_" not in op and len(args) >= 2:
58 dsts, srcs = args[:2], args[2:] # v_add_co_u32 writes a VGPR and a carry
59 elif no_dest:
60 dsts, srcs = [], args
61 else:
62 dsts, srcs = args[:1], (args[:1] if dst_read else []) + args[1:]
63 for a in srcs:
64 regs = range(a["r"], a["r"] + a.get("n", 1)) if a["k"] in ("sgpr", "vgpr") else ()
65 for r in regs:
66 if a["k"] == "sgpr" and r not in written_s:
67 read_s.add(r)
68 elif a["k"] == "vgpr" and r not in written_v:
69 read_v.add(r)
70 for a in dsts:
71 if a["k"] == "sgpr":
72 written_s.update(range(a["r"], a["r"] + a.get("n", 1)))
73 elif a["k"] == "vgpr":
74 written_v.update(range(a["r"], a["r"] + a.get("n", 1)))
75 return read_s, read_v
76
77
78def survey(dxbc_dir):
79 with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f:
80 index = json.load(f)
81 names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"]
82 markers, vgprs, families = Counter(), Counter(), Counter()
83 missing = 0
84 for n in names:
85 path = os.path.join(dxbc_dir, "disasm", n + ".s")
86 if not os.path.isfile(path):
87 missing += 1
88 continue
89 with open(path, encoding="utf-8", errors="replace") as f:
90 text = f.read()
91 _, read_v = read_before_write(shader_ir.parse_file(path)["insns"])
92 for r in read_v:
93 if r < 16:
94 vgprs[f"v{r}"] += 1
95 fetch = bool(FETCH_CALL.search(text))
96 markers["exp prim"] += bool(PRIM_EXPORT.search(text))
97 markers["s_sendmsg"] += bool(SENDMSG.search(text))
98 markers["v_mbcnt"] += bool(MBCNT.search(text))
99 markers["exp pos0"] += bool(POS0_EXPORT.search(text))
100 markers["exp param"] += bool(PARAM_EXPORT.search(text))
101 markers["fetch call"] += fetch
102 if fetch:
103 families["fetch call, attributes from v4 up"] += 1
104 elif 0 in read_v:
105 families["reads v0 (vertex id)" + (" and v3 (instance id)" if 3 in read_v else "")] += 1
106 else:
107 families["reads neither v0 nor a fetch call"] += 1
108 return {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers),
109 "input_vgprs_read": dict(sorted(vgprs.items(), key=lambda kv: int(kv[0][1:]))),
110 "families": dict(families)}
111
112
113def main():
114 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
115 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py")
116 ap.add_argument("--json", help="also write the counts as JSON")
117 a = ap.parse_args()
118 r = survey(a.dxbc)
119 m = r["markers"]
120 print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)")
121 print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}")
122 print(f"exports: pos0 {m.get('exp pos0', 0)}, param {m.get('exp param', 0)}; fetch call {m.get('fetch call', 0)}")
123 print("input VGPRs read before written (v0..v15):", r["input_vgprs_read"])
124 print("families:", r["families"])
125 legacy = not (m.get("exp prim") or m.get("s_sendmsg") or m.get("v_mbcnt"))
126 print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout")
127 if a.json:
128 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
129 json.dump(r, f, indent=1)
130 return 0
131
132
133if __name__ == "__main__":
134 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
135 sys.stdout.reconfigure(errors="replace")
136 except (AttributeError, ValueError, OSError):
137 pass
138 sys.exit(main())