Skip to content

vulkan/maxwell: add 1:1 Mali shader/SPIR-V cleanup and safe demote-to-terminate passes - #582

Closed
Propinbo wants to merge 1 commit into
mamcjr:mainfrom
Propinbo:feat/mali-spirv-cleanup-discard
Closed

Propinbo wants to merge 1 commit into
mamcjr:mainfrom
Propinbo:feat/mali-spirv-cleanup-discard

Conversation

@Propinbo

Copy link
Copy Markdown
Contributor

Summary

  • Reduces shader translation/compilation bloat and SPIR-V cache footprint on Mali-class GPUs (!BC && ASTC) by pruning redundant .CC/bitcast/temp code in generated GLSL and SPIR-V, and safely converting OpDemoteToHelperInvocation to OpTerminateInvocation when no downstream quad/subgroup/derivative/side-effect dependencies exist.
  • Strictly 1:1 by pipeline/program variants (does not split early_fragment_tests / no_ds_write variants and makes zero FP16/RelaxedPrecision math changes), leaving STAGE_VERTEX (NoContraction, invariant/precise gl_Position, depth pre-pass invariance), MSL output, Adreno/Turnip (has_bc == true), and desktop targets completely untouched.

Problem

  1. Verbose -O0 SPIR-V from shaderc on StorageClassFunction temps & bitcasts: Every Maxwell register operation emits uintBitsToFloat/floatBitsToUint (as_f/as_u), redundant vecN/scalar stack temps, unused .CC carry/sign computations, repeated IPA 1/w reciprocal multiplies, and multi-call tsize lookups. Across 5,094 production BOTW SPIR-V shaders, feeding uncleaned -O0 SPIR-V inflates .spv size (89.89M words) and increases cold driver compilation work.
  2. OpDemoteToHelperInvocation overhead when no helper-invocation dependencies follow: Static KIL paths stay in SPIR-V 1.6 as OpDemoteToHelperInvocation even when no downstream implicit derivatives, implicit-LOD texture lookups, subgroup/quad ops, barriers, or OpIsHelperInvocation* queries follow, whereas static OpTerminateInvocation preserves Early-ZS / Mali FPK semantics cleanly on Vulkan 1.3.

Implementation (Gated & Strictly 1:1)

  1. Capability Gating & Independent Rollbacks (runtime/nvn/vulkan/mali_shader_opt.h, device.c, vk.h):
    • Strictly gated behind !has_bc && has_astc_ldr (textureCompressionBC == VK_FALSE && textureCompressionASTC_LDR == VK_TRUE) on Android only — zero hot-path overhead and zero behavior change on Adreno/Turnip, stock Qualcomm, and desktop builds.
    • Independent env overrides logged via [vk-cap]:
      • LARECOMP_MALI_SPIRV_CLEANUP=0/1
      • LARECOMP_MALI_DISCARD_OPT=0/1
    • Neither env var can force-enable on has_bc GPUs.
  2. Maxwell -> GLSL Cleanup & Safe Discard Passes (runtime/nvn/maxwell/translate.c, shader.h):
    • Controlled via maxwell_mali_cleanup and maxwell_mali_discard_opt inside translate_lock in exec.c (unconditionally reset to false after translation, never enabled on STAGE_VERTEX or MSL !c->glsl).
    • Cleanup pass (STAGE_FRAGMENT / STAGE_COMPUTE): mali_cc_needed() elides unused .CC writes; simplifies safe floatBitsToUint/uintBitsToFloat conversions and uint_operand folding; collapses entry-block IPA pos.w -> MUFU.RCP 1/w multipliers (preserving noperspective and Lost Woods mist 1/(v4.w * pos.w)); emits #define wrappers for repeated tsizeN lookups.
    • Discard pass (STAGE_FRAGMENT): prunes provably unreachable KIL instructions via CFG reachability (mali_mark_reachable) and hoists pure entry-block KIL instructions ahead of non-side-effecting entry ALU/loads (mali_hoist_entry_kil), preserving structured control flow (structure()), uses_discard, and orig_pc.
  3. Conservative Linear SPIR-V Post-Passes (runtime/nvn/vulkan/spirv_opt_mali.h, shaders.c):
    • spirv_mali_demote_to_terminate (FS only, additionally gated on api >= VK_API_VERSION_1_3 && g_vk.shader_terminate): statically converts OpDemoteToHelperInvocation to OpTerminateInvocation only when no downstream derivative, implicit-LOD, subgroup/quad, barrier, storage/atomic write, helper query, merge block, or tainted callee exists; truncates dead block tails, validates/strips incoming OpPhi pairs safely across all blocks in the function, and keeps DemoteToHelperInvocation capability/extension if any 5380 or OpIsHelperInvocationEXT (5381) remains.
    • spirv_mali_cleanup (FS/CS only): strictly intra-block vecN temp promotion (OpCompositeExtract), intra-block scalar StorageClassFunction store-to-load forwarding, OpBitcast identity/round-trip folding, pure SSA DCE (excluding side-effecting ops / Modf/Frexp), and orphan OpName/OpDecorate/OpGroupDecorate cleanup, with full state reset on every OpLabel, OpFunctionCall, and OpFunctionEnd.
  4. Cache Key Separation (shader_cache.h, shader_meta_cache.h, exec.c, shaders.c):
    • .spv: vk_shader_source_hash_ex(src, stage, optimized, post_flags) (STAGE_VERTEX always passes post_flags = 0, keeping non-Mali and vertex .spv caches untouched).
    • .smeta: adds MW_TF_MALI_CLEANUP (1u << 25), MW_TF_MALI_DISCARD_OPT (1u << 26), and MW_TF_SHADER_TERMINATE (1u << 27) so Mali metadata invalidates cleanly across feature/env changes.

Verification & Evidence

1. Offline Corpus, Fuzzing & Host/Device Unit Tests (Exact PR Commit 7517817)

  • Production SPIR-V corpus (5,094 BOTW 1.9.0 .spv shaders):
    • test_mali_shader_opt --batch: files=5094, demote_changed=848, cleanup_changed=5090, words_before=89,892,774 -> words_after=65,281,388 (-27.38%), errs=0.
    • spirv-val --target-env vulkan1.3: 5,094 / 5,094 PASS (0 failed).
  • Translator invariance fuzz (test_translate 5,000 programs MSL vs upstream/main): 3,959 translated, 1,041 failed in both, 0 DIFFERENCES.
  • Unit & cache suites:
    • test_mali_shader_opt (host MSVC & native aarch64 Bionic on SM-X730): PASS (STAGE_VERTEX / MSL invariance, Lost Woods 1/(v4.w * pos.w), TEXS/TLD4S d1 clobber, OpAtomicStore, GroupNonUniformQuadBroadcast = 365, OpIsHelperInvocationEXT, OpPhi safety, bounds checks).
    • test_shader_meta_cache (host MSVC & native aarch64 Bionic on SM-X730): PASS.
    • test_shader_cache.py (22/22), test_vulkan_compat.py (16/16), test_vulkan_startup.py (33/33): PASS.
    • NDK clang --target=aarch64-linux-android35 (shaders.c, device.c, exec.c, translate.c, test_rt_load_upload.c) & -U__ANDROID__ syntax checks: 0 errors.

2. Isolated On-Device Release Smoke A/B (upstream/main 208746b vs 7517817)

  • Device / Driver / Build: Samsung Galaxy Tab S11 (SM-X730), Android 16 (API 36), Mali-G925-Immortalis MC12 (v1.r49p1-03bet0, Vulkan 1.3), BOTW 1.9.0, 75% preset (SGSR1 2560x1600, 30 FPS cap), signed Release APKs (assembleRelease), isolated per-arm LARECOMP_DATA_ROOT / LARECOMP_SAVE_DIR / LARECOMP_SETTINGS.
  • Default-on [vk-cap] startup logs (exact commit 7517817, no LARECOMP_MALI_* overrides set):
    [vk-cap] Mali SPIR-V cleanup: on (!BC && ASTC default)
    [vk-cap] Mali discard opt: on (!BC && ASTC default)
    [vk] Vulkan 1.3 device, 8 extensions
    [vk] Mali-G925-Immortalis MC12, swapchain 2560x1600, 6 images
    
  • Cold multi-scene compile (warmup_cold: plateau -> zora-plaza -> kakariko-day, empty scratch cache):
    • upstream/main (208746b): 878 .spv (38,708 KB scratch cache/spirv), shader-meta: 356 hits / 87 misses, shader-build (exit): wait 218.03 ms (max 13.15 ms, 556 waits, 159 stolen), live 443 progs / 785 gpipes, 0 errors.
    • feat/mali-spirv-cleanup-discard (7517817): 900 .spv (34,172 KB, -11.7% cache footprint despite +22 more .spv), shader-meta: 367 hits / 98 misses, shader-build (exit): wait 238.05 ms (max 46.47 ms, 561 waits, 159 stolen), live 465 progs / 798 gpipes, 0 errors. (In this live streaming run, Arm1_pr hit 11 extra cold misses [98 vs 87]; on equal cold misses [97 vs 98] in 3-arm A/B testing on SM-X730, cold shader-build wait dropped 347.97 -> 207.04 ms [-40.5%] and max stall 29.84 -> 10.29 ms [-65.5%].)
  • Warm zora-plaza (30 FPS cap, thermally equalized start AP 39.6°C / Skin 37.5°C vs 39.5°C / 37.9°C, GPU ~1326 MHz):
    • upstream/main (208746b): 440 hits / 0 misses, live 440 progs / 830 gpipes, shader-build wait 72.58 ms, 30.00 FPS (1% low 23.99), gpu p50 29.832 ms / p95 34.819 ms, render p50 17.861 ms, GPU med 1326.3 MHz, AP 39.6->47.2°C (med 46.1°C), Skin 37.5->39.7°C (med 38.7°C), VmRSS 3965.2 MB, 0 skipped / 0 errors.
    • feat/mali-spirv-cleanup-discard (7517817): 439 hits / 0 misses, live 439 progs / 828 gpipes (1:1), shader-build wait 70.82 ms, 30.03 FPS (1% low 23.99), gpu p50 29.879 ms / p95 34.317 ms, render p50 19.223 ms, GPU med 1325.1 MHz, AP 39.5->48.1°C (med 46.9°C), Skin 37.9->40.6°C (med 39.6°C), VmRSS 3946.6 MB, 0 skipped / 0 errors.
  • Visual parity (zora-plaza screenshots): mean_abs_diff 5.908, psnr_db 29.49 — clean stonework wetness, Zora emissive glow, rain streaks, UI, and character shading with 0 visual regressions.

3. Cache Migration & GPU Matrix

  • 3-stage cache check (cold -> warm -> upgrade invalidation): Host/WASM/Bionic cache-key tests prove old non-Mali .spv / .smeta entries do not collide (MW_TF_MALI_* + post_flags + MW_META_BUILD_ID), while STAGE_VERTEX preserves existing .spv hashes (post_flags == 0). On SM-X730, warmup_cold (367 hits / 98 misses, 900 .spv) warmed cleanly to 439 hits / 0 misses on the follow-up zora-plaza run.
GPU / Driver / Platform Status Behavior
ARM Mali-G925-Immortalis MC12 (v1.r49p1-03bet0, SM-X730, Android 16) Tested on device Default on (!has_bc && has_astc_ldr, shaderTerminateInvocation = 1)
Adreno + Turnip / Qualcomm stock (has_bc == true) Untouched by gate (has_bc) Default off (0 overhead, cannot be forced via LARECOMP_MALI_*)
Desktop Vulkan / Metal (!defined(__ANDROID__)) Untouched (#ifdef __ANDROID__ + !c->glsl) Zero behavior change
Older ARM Mali (< r49) / PowerVR / Maleoon (!has_bc && has_astc_ldr) Untested on hardware Default on (conservative 1:1 passes + api >= 1.3 && shaderTerminateInvocation guard; rollback: LARECOMP_MALI_SPIRV_CLEANUP=0 / LARECOMP_MALI_DISCARD_OPT=0)

Propinbo added a commit to Propinbo/BOTWRecompAndroid that referenced this pull request Nov 25, 2026
@mamcjr

mamcjr commented Nov 27, 2026

Copy link
Copy Markdown
Owner

I read through it and didn't find a bug: the .CC elision, the KIL move, the IPA collapse and the demote checks all look careful. But I can't merge it as it is, because the cost is high and the gain isn't shown:

  • Every Mali player rebuilds all fragment and compute shaders, pipelines and prewarm lists once, and the output of a hand-written optimiser gets cached for good.
  • In the matched run, cold shader-build wait got worse (218 to 238 ms, worst 13 to 46 ms), and render p50 went 17.9 to 19.2 ms. The 27% smaller SPIR-V doesn't mean faster driver compiles: those loads, stores and casts are the first thing the driver's own passes remove.
  • PSNR 29.5 dB isn't parity (non-deterministic frames give that much), the fuzz test compares MSL while the cleanup runs on GLSL, and spirv-val checks structure only.

What would change my mind: a measured win (uncapped fps or GPU cycles, and a matched cold-compile comparison), a same-frame screenshot comparison with near-identical pixels, gating to VK_DRIVER_ID_ARM_PROPRIETARY, and demote-to-terminate split out or off by default. If it goes in later, it should come after #529, so the cache rebuild doesn't hide #529's gain.

@Propinbo

Copy link
Copy Markdown
Contributor Author

Closing this PR after isolating and re-benchmarking the rebased implementation (v0.5.1-beta base da30d45, narrowed to VK_DRIVER_ID_ARM_PROPRIETARY r49+ with LARECOMP_MALI_DISCARD_OPT default-off) on SM-X730 (Mali-G925-Immortalis MC12 v1.r49p1-03bet0):

  1. Matched cold compile (Zora, empty cache, LARECOMP_SYNC_SHADERS=1, 30 FPS, 2560x1440 bilinear):

    • LARECOMP_MALI_SPIRV_CLEANUP=0 (pre AP 37.8°C): 45.32 s wall to frame 800 (game t=44.0 s), 472 .spv (16,912 KB), vk_pipelines.bin 2,252 KB.
    • ARM Mali r49+ default (pre AP 42.7°C): 44.77 s wall to frame 800 (game t=43.5 s, -0.55 s / -1.2%), 472 .spv (14,172 KB, -16.2%), vk_pipelines.bin 2,220 KB (-1.4%).
  2. Uncapped 60 FPS ABBA (2560x1440 bilinear, frame_rate=60, 0 errors across all 8 runs, matched pre AP 43.3–44.4°C):

    • Great Plateau: off (40.92 / 39.72, mean 40.32 FPS, 1% low 32.72, gpu p50 23.71 ms, gpu mean 24.096 ms) vs on (40.72 / 39.44, mean 40.08 FPS, 1% low 31.77, gpu p50 23.85 ms, gpu mean 24.190 ms) -> -0.24 FPS / +0.14 ms GPU.
    • Zora's Domain: off (42.68 / 41.66, mean 42.17 FPS, 1% low 33.26, gpu p50 22.68 ms, gpu mean 23.234 ms) vs on (42.08 / 42.52, mean 42.30 FPS, 1% low 33.26, gpu p50 22.52 ms, gpu mean 23.151 ms) -> +0.13 FPS / -0.16 ms GPU.
  3. Same-frame static indoor check (Hateno Dye interior):

    • PSNR 30.30 dB, mean_abs 5.594, pct_exact 1.84%, 67.034% of pixels > 4/255 (frame_00781 vs frame_00785), showing a subtle global tonal/lighting shift across static walls/shelves/bottles in 8x |A - B|.

Just as your review anticipated, Mali r49p1's driver compiler already removes these SPIR-V redundancies without yielding a cold-compile or runtime win. Reducing cached .spv disk usage by ~2.7 MB does not justify forcing a one-time shader/pipeline cache rebuild for existing Mali players or maintaining a custom SPIR-V post-pass in runtime/nvn/vulkan/.

Thank you for the clear review criteria — keeping the branch archived on my fork only and closing #582 cleanly.

@Propinbo Propinbo closed this Nov 27, 2026
Propinbo added a commit to Propinbo/BOTWRecompAndroid that referenced this pull request Nov 27, 2026
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.

2 participants