From c8b88f7428b1e01997a9774c5092dd0d1390e173 Mon Sep 17 00:00:00 2001 From: Valiantsin Dzerakh Date: Tue, 24 Nov 2026 08:56:03 +0300 Subject: [PATCH] Demote a discard only where a derivative follows it, and read demote from the ini (#164, #1365) spirv_demote turned every OpKill inside a selection into OpDemoteToHelperInvocation on AMD's Windows driver. A demoted fragment runs the rest of the shader, so every alpha-tested draw (grass, foliage, hair) paid for its discarded pixels. The cloud fringe of #164 came from OpImageQueryLod after the discard. Now a discard is demoted only when an OpImageQueryLod, an explicit derivative or a function call follows it in its function; the rest keep the plain discard, as before 0.4.1. On the field save 1 of 128 shaders with a discard is demoted, and the picture keeps the fix. demote has a row in the settings table and a description in totk.ini.example, so demote = 0 or 1 in the ini no longer logs an unknown key. Co-Authored-By: Claude Opus 5.5 --- docs/maxwell.md | 2 +- runtime/cfg.c | 5 +-- runtime/vk_pipeline.c | 71 ++++++++++++++++++++++++++++++++----------- totk.ini.example | 5 +++ 4 files changed, 63 insertions(+), 20 deletions(-) diff --git a/docs/maxwell.md b/docs/maxwell.md index 4741f631..fc20f2b2 100644 --- a/docs/maxwell.md +++ b/docs/maxwell.md @@ -81,7 +81,7 @@ Source shorthands: | 3.2 | **FMZ multiply mode** (`FMUL/FFMA/...` field `Fmz`, `.FMZ`): 0 × anything = 0, including Inf/NaN (DX9 rule). | IEEE: 0 × Inf = NaN. | Ryujinx decodes `Fmz` (`Decoders/InstDecoders.cs:306-309, 1901`) but no emitter reads it. Ours: same. Census needed (check 13). | RYU-SH | | 3.3 | **Denormals**: per-instruction `.FTZ`. | AMD flushes fp32 denormals by default; `VK_KHR_shader_float_controls` sets it per shader. | Ryujinx ignores `.FTZ`. Low risk. | RYU-SH (no `Ftz` use in `Instructions/`) | | 3.4 | **Warp size 32**: `SHFL`, `VOTE`, `S2R LANEID`, ballots are 32-bit. | AMD RDNA runs wave32 or wave64 per shader (the driver chooses; RADV fragment default wave64); `VK_EXT_subgroup_size_control` `requiredSubgroupSize = 32` fixes it. | Ryujinx adapts lane masks to `QueryHostSubgroupSize()` (default 32, `IGpuAccessor.cs:218`; `Instructions/InstEmitWarp.cs:72, 106`, `InstEmitMove.cs:175-185`). Ours: not overridden, no required size (check 6). | (`RADV_PERFTEST=pswave32`) | -| 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). Ours: on AMD's own drivers (`vk_caps.amd` without `mesa`) `vk_pipeline.c` `spirv_demote` turns each `OpKill` that a selection header branches to into `OpDemoteToHelperInvocation` plus a branch to the selection's merge block; `TOTK_DEMOTE` overrides. TotK's cloud shader discards and then takes `OpImageQueryLod`: with `OpKill` AMD's Windows driver lost fog in the fragments sharing a quad with a discarded one (#164). | | +| 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). Ours: on AMD's own drivers (`vk_caps.amd` without `mesa`) `vk_pipeline.c` `spirv_demote` turns each `OpKill` that a selection header branches to, and that an `OpImageQueryLod`, an explicit derivative or a call follows in its function, into `OpDemoteToHelperInvocation` plus a branch to the selection's merge block; other kills stay `OpKill`, since a demoted fragment runs the rest of the shader and alpha-tested draws paid for every discarded pixel. `TOTK_DEMOTE` (ini `demote`) overrides. TotK's cloud shader discards and then takes `OpImageQueryLod`: with `OpKill` AMD's Windows driver lost fog in the fragments sharing a quad with a discarded one (#164). | | | 3.6 | **Implicit-LOD sampling in divergent control flow** works on Maxwell (TEX unit uses quad neighbours). | Undefined in non-uniform control flow; AMD whole-quad mode usually works. | — | VKSPEC (derivatives) | | 3.7 | **Integer division** does not exist (compiled to `XMAD`/`IMAD` sequences); MUFU.RCP(0) = +Inf, LG2(0) = -Inf. | Same IEEE edge cases through `1/x`, `Log2`. | Low risk. | — | | 3.8 | **FP64** in some TotK cutscene shaders. | No FP64 on some hosts. | yuzu FP64 → FP32 (YZ-2306, PR 10693); ours: `softfloat64` job flag (`tools/xlate/Program.cs` `QueryHostSupportsShaderFloat64`). | — | diff --git a/runtime/cfg.c b/runtime/cfg.c index e6722ae8..dc225676 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -41,7 +41,7 @@ static const char *const known[] = { "BIND_INC", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_ZL", "BIND_ZR", "BARRIER_MERGE", "BLOCK_VIEWS_3D", "CLIMB_FIX", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA", "COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT", - "DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR", + "DEMOTE", "DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "DYNAMIC_RES", "DYN_DELTA", "EXEFS", "FEEDBACK", "FG_DEBUG", "FG_OBJECTS", "FG_SHOT", "FG_SHOT_DIR", "FG_TEST", "FG_TIMES", "FIXED_RES_PATCH", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_GEN", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH", "FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR4_DEBUG", "FSR_SHARPNESS", @@ -111,7 +111,7 @@ static const struct { const char *key, *section; } sections[] = { {"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"}, {"BARRIER_MERGE", "performance"}, {"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "performance"}, {"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"}, - {"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_RELEASED_MIB", "performance"}, {"TEX_BLOCK_MIB", "performance"}, {"VMA_BLOCK_MIB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"}, + {"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_RELEASED_MIB", "performance"}, {"TEX_BLOCK_MIB", "performance"}, {"VMA_BLOCK_MIB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"}, {"DEMOTE", "performance"}, {"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"MEMX", "performance"}, {"BIND_INC", "performance"}, {"TEX_MEMO", "performance"}, {"VB_USED", "performance"}, {"DESC_TEMPLATE", "performance"}, {"SYNC_AHEAD", "performance"}, {"SHADOW_DEFER", "performance"}, {"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"}, {"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"}, @@ -232,6 +232,7 @@ static const CfgMeta metas[] = { {"OPTREF_GUARD", "1", "0|1", RESTART}, {"ABILITY_GUARD", "1", "0|1", RESTART}, {"REPORT_GUARD", "1", "0|1", RESTART}, // render fixes {"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART}, + {"DEMOTE", "", "0|1", RESTART}, // vk_pipeline.c spirv_demote: 1 on AMD's own driver, else 0 {"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"MEMX", "1", "0|1|check", RESTART}, {"BIND_INC", "0", "0|1|check", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART}, {"VB_USED", "1", "0|1", RESTART}, {"DESC_TEMPLATE", "1", "0|1", RESTART}, diff --git a/runtime/vk_pipeline.c b/runtime/vk_pipeline.c index 4e53487a..8d569908 100644 --- a/runtime/vk_pipeline.c +++ b/runtime/vk_pipeline.c @@ -879,37 +879,72 @@ out: // undefined. Mesa keeps computing after a discard; AMD's Windows compiler does not, and TotK's cloud shader, which // discards where the scene is in front and then takes OpImageQueryLod for its noise textures, lost fog in the pixels // sharing a quad with a discarded one: a light fringe round every silhouette against clouds (issue #164). -// Each OpKill whose block is a direct target of a selection header becomes OpDemoteToHelperInvocation plus a branch to -// that selection's merge block, so the fragment goes on computing and writes nothing. An OpKill anywhere else (the end -// of a function, a switch case) stays. NULL: nothing to change. +// Each OpKill whose block is a direct target of a selection header, and which an explicit derivative follows (below), +// becomes OpDemoteToHelperInvocation plus a branch to that selection's merge block, so the fragment goes on computing +// and writes nothing. An OpKill anywhere else (the end of a function, a switch case) stays. NULL: nothing to change. +// Only kills that an OpImageQueryLod, an OpDPdx..OpFwidthCoarse or an OpFunctionCall (whose callee may take one) +// follows later in the same function change: the cloud shader's fringe came from OpImageQueryLod. A demoted fragment +// runs the rest of the shader, so demoting every kill made each alpha-tested draw (grass, foliage, hair) pay for its +// discarded pixels; implicit-LOD samples after a kill, which nearly every alpha-tested shader takes, kept the OpKill +// they had before demote existed, without a report. Program order stands for "after": a derivative in the other arm +// of the kill's selection demotes too (harmless), one reached only by a loop's back edge does not (that kill keeps +// its OpKill, as before demote). // On by default on AMD's own drivers, where the fringe shows; other drivers keep the translator's OpKill, their output -// unchanged. TOTK_DEMOTE=1 or 0 overrides on any driver that enables shaderDemoteToHelperInvocation (vk_caps.demote, -// set in vk_device.c create_device); without the feature the module keeps OpKill, since the capability would be invalid. +// unchanged. TOTK_DEMOTE=1 or 0 (ini: demote) overrides on any driver that enables shaderDemoteToHelperInvocation +// (vk_caps.demote, set in vk_device.c create_device); without the feature the module keeps OpKill, since the +// capability would be invalid. +static uint64_t demote_mods, demote_kept; // modules with an OpKill: some kill demoted, every kill kept (atomics) + +// Logs the split of modules with an OpKill at each power of two of their count. +static void demote_note(int demoted) { + uint64_t d = demoted ? __atomic_add_fetch(&demote_mods, 1, __ATOMIC_RELAXED) : __atomic_load_n(&demote_mods, __ATOMIC_RELAXED); + uint64_t k = demoted ? __atomic_load_n(&demote_kept, __ATOMIC_RELAXED) : __atomic_add_fetch(&demote_kept, 1, __ATOMIC_RELAXED); + uint64_t t = d + k; + if (!(t & (t - 1))) + rt_log("vk_pipeline: discard as demote: %llu shaders with a discard demote it, %llu keep it (no derivative after)", + (unsigned long long)d, (unsigned long long)k); +} + static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) { - enum { OP_EXTENSION = 10, OP_CAPABILITY = 17, OP_SELECTION_MERGE = 247, OP_LABEL = 248, OP_BRANCH = 249, + enum { OP_EXTENSION = 10, OP_CAPABILITY = 17, OP_FUNCTION_END = 56, OP_FUNCTION_CALL = 57, OP_IMAGE_QUERY_LOD = 105, + OP_DPDX = 207, OP_FWIDTH_COARSE = 215, OP_SELECTION_MERGE = 247, OP_LABEL = 248, OP_BRANCH = 249, OP_BRANCH_CONDITIONAL = 250, OP_KILL = 252, OP_DEMOTE = 5380, CAP_DEMOTE = 5379 }; static const char ext_name[36] = "SPV_EXT_demote_to_helper_invocation"; // 35 characters and the terminator: 9 words static int on = -1; if (on < 0) { on = vk_caps.demote && rt_knob("DEMOTE", vk_caps.amd && !vk_caps.mesa ? "1" : "0"); - rt_log("vk_pipeline: discard as demote: %s (shaderDemoteToHelperInvocation %d, TOTK_DEMOTE)", on ? "on" : "off", - vk_caps.demote); + rt_log("vk_pipeline: discard as demote: %s, for discards a derivative follows (shaderDemoteToHelperInvocation " + "%d, TOTK_DEMOTE)", on ? "on" : "off", vk_caps.demote); } if (!on || n < 5) return NULL; - uint64_t kills = 0; + // Pass 1: check the words, count the kills, and note each function's last derivative (or call) by function order. + uint64_t kills = 0, nfn = 0, cap_fn = 8, last = 0; + uint64_t *fn_deriv = malloc(cap_fn * sizeof *fn_deriv); + if (!fn_deriv) return NULL; for (uint64_t i = 5; i < n;) { uint32_t op = w[i] & 0xffff, l = w[i] >> 16; - if (!l || i + l > n) return NULL; - if (op == OP_KILL) kills++; - if (op == OP_CAPABILITY && l >= 2 && w[i + 1] == CAP_DEMOTE) return NULL; // already demotes + if (!l || i + l > n || (op == OP_CAPABILITY && l >= 2 && w[i + 1] == CAP_DEMOTE)) { // malformed, or demotes already + free(fn_deriv); + return NULL; + } + kills += op == OP_KILL; + if (op == OP_IMAGE_QUERY_LOD || (op >= OP_DPDX && op <= OP_FWIDTH_COARSE) || op == OP_FUNCTION_CALL) last = i; + if (op == OP_FUNCTION_END) { + if (nfn == cap_fn) { + uint64_t *g = realloc(fn_deriv, 2 * cap_fn * sizeof *fn_deriv); + if (!g) { free(fn_deriv); return NULL; } + fn_deriv = g, cap_fn *= 2; + } + fn_deriv[nfn++] = last, last = 0; + } i += l; } - if (!kills) return NULL; + if (!kills) { free(fn_deriv); return NULL; } uint32_t bound = w[3] < (1u << 22) ? w[3] : (1u << 22); uint32_t *merge_of = calloc(bound ? bound : 1, sizeof *merge_of); // label -> merge block of the selection that branches to it uint32_t *o = malloc((n + 12 + 2 * kills) * 4); - if (!merge_of || !o) { free(merge_of), free(o); return NULL; } - uint64_t on_w = 5, changed = 0; + if (!merge_of || !o) { free(merge_of), free(o), free(fn_deriv); return NULL; } + uint64_t on_w = 5, changed = 0, fn = 0; uint32_t cur = 0, pending = 0; int declared = 0; memcpy(o, w, 5 * 4); @@ -929,7 +964,7 @@ static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) { if (a[k] < bound && a[k] != pending) merge_of[a[k]] = merge_of[a[k]] ? ~0u : pending; // two headers: leave it } pending = op == OP_SELECTION_MERGE && l >= 3 ? a[0] : 0; - uint32_t m = op == OP_KILL && cur < bound ? merge_of[cur] : 0; + uint32_t m = op == OP_KILL && cur < bound && fn < nfn && fn_deriv[fn] > i ? merge_of[cur] : 0; if (m && m != ~0u && m != cur) { o[on_w++] = 1u << 16 | OP_DEMOTE; o[on_w++] = 2u << 16 | OP_BRANCH, o[on_w++] = m; @@ -937,9 +972,11 @@ static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) { } else { memcpy(o + on_w, w + i, l * 4), on_w += l; } + fn += op == OP_FUNCTION_END; i += l; } - free(merge_of); + free(merge_of), free(fn_deriv); + demote_note(changed != 0); if (!changed) { free(o); return NULL; } *out_n = on_w; return o; diff --git a/totk.ini.example b/totk.ini.example index 3756bd4b..9859f57a 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -150,6 +150,11 @@ # fix_c0 = 1 # New GPU memory pools start zero-filled, as Switch memory does. # fix_zero = 1 +# Shaders that discard a pixel and then read how fast a value changes across neighbouring pixels (a texture's +# level of detail, a derivative) keep the discarded pixel running without output, as the Switch does: stops the light +# fringe round objects against clouds and fog on AMD. Default: 1 on AMD's own Windows driver, 0 elsewhere. 0 keeps +# the plain discard everywhere, 1 also uses it on other drivers. Read at start. +# demote = 1 # Optimisations, 0 turns each off: skip bindings that did not change, remember shader lookups, reuse the previous # draw's pipeline when its state repeats, remember texture descriptors between draws, update descriptors in bulk, # skip push constants that did not change, bind only the vertex buffers a draw reads, compare and copy each draw's