perf(shader): take the f32 mul, fma and add result fixups only when needed #4322

Closed
karanvora2599 wants to merge 1 commit from upstream-pr/4322 into main
karanvora2599 commented 2026-10-12 06:04:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by karanvora2599 on 2026-10-12T06:04:49Z.


What

v_mul_f32, v_fma_f32/v_fmac_f32, v_add_f32 and v_sub_f32 compute their AMD result fixups only when the host result needs them: a NaN, or for products a magnitude of at most 2^-126. Results are unchanged.

This is stacked on #4287, which shrinks the NaN result selection itself. Only the last commit is new.

Background. Every f32 multiply, fma and add computes two fixups on its host result:

  • the NaN result AMD returns: the first NaN operand, quieted in IEEE mode, or the default NaN (nanResultF32);
  • for products in FLOAT_MODEs that flush f32 denormals, the flush of products that are tiny after rounding to 24 bits (flushTinyProduct, #2839).

Both are straight-line selects that run on every instruction. On an RTX 4060, v_mul_f32 is 16.5 SASS instructions, where the multiply is one. In fma-rc's census of eleven titles (316,352 instructions, linked in #4061), v_mul_f32 is 13.4% of all instructions and v_add_f32/v_sub_f32/v_subrev_f32 6.6%.

How.

  • Translator (rareFixupF32): when a fixup was emitted, the result becomes select(special, fixed, plain), where plain is the host result.
    • special is isnan(plain) for add and sub.
    • For mul and fma with the tiny-product flush, special is ((bits(plain) + 0x7fffff) & 0x7fffffff) < 0x1000000: the result is a NaN, or its magnitude is at most 2^-126. That's three integer instructions. This form is used only with round to nearest even; directed f32 rounding keeps the plain selects.
    • The select carries a new SelectFlags::rarelyTrue flag. Optimizer passes see an ordinary SelectF32, and dropping the flag only loses the branch.
  • Backend (SpirvFlowEmitter): for each flagged select, the instructions used only by its rare arm are found, latest first, so the search stops at the first value with another use. They're emitted inside a selection (EmitValueOrDefaultIfCondition), and the select becomes the phi.
  • Kept as plain selects:
    • loop headers and continue targets, whose OpLoopMerge must stay in the header's first block;
    • values shared between the two lane halves of a wave64 program;
    • terminator conditions.

Before / after on an RTX 4060 Laptop (Ada, driver 591.86), FLOAT_MODE 0xc0.

Run time: dependent chains of 2,048 instructions over 16,384 groups of 32 lanes, median of 15 interleaved dispatches in one process. A temporary switch, not part of the PR, selected the plain selects for the comparison.

Chain plain selects this PR
v_mul_f32 5.90 ms 2.74 ms
v_fma_f32 7.17 ms 3.87 ms
v_add_f32 4.29 ms 3.78 ms
v_mul_f32, every input a NaN 5.95 ms 6.34 ms
v_add_f32, every input a NaN 4.44 ms 3.94 ms
v_mac_f32 (legacy mad, unchanged, control) 0.56 ms 0.59 ms

Both variants wrote the same results.

Static SASS per instruction (APS5_PIPELINE_STATS, chain of 16) grows, since both paths are compiled:

  • v_mul_f32: 16.5 → 23.5;
  • v_fma_f32: 22.5 → 34 (VOP3) and 28 → 34;
  • v_fmac_f32: 20.5 → 29.5;
  • v_sub_f32: 11 → 12.5;
  • v_add_f32: 10.5 → 10.5.

Registers are within ±5.

Tested

Windows 11, MinGW-w64 GCC 15.2.0, Release, main at d146ec1b plus #4287. RTX 4060 Laptop (driver 591.86), Intel UHD Graphics (Raptor Lake, driver 101.6790), lavapipe from Mesa 25.2.8 (the version CI installs; Windows build, GALLIUM_OVERRIDE_CPU_CAPS=avx).

  • The 41 f32 and modifier execution tests (agc_driver_f32_*, agc_driver_fma_*, agc_driver_vop*, agc_denormal*, agc_driver_division_* and others) pass on the RTX 4060, including agc_driver_f32_arithmetic_nan, which caught #2279's NaN quieting bug. This change reuses nanResultF32 unchanged, so the IEEE-mode quieting can't drift.
  • Negative check: using the NaN-only fast check for products too, so tiny products skip the flush, makes lavapipe fail agc_driver_f32_constant_factor_tininess and agc_driver_f32_denormal_flush: v_mul_f32 v12, v4, v5 is 0x00800000, expected 0x00000000 (2^-126 × (1 − 2^-24), tiny after rounding). The RTX 4060 and the Intel UHD pass that build, because their multiply already returns 0 for these products. lavapipe keeps f32 denormals and returns 2^-126.
  • Shader tests (agc_driver_*, agc_shader_*, agc_spirv_*, vector_*, agc_masked_select, agc_validate_program, agc_denormal*, agc_float16_*; 338 tests). The BDA tests that hang on driver 591.86 until #3291 lands are left out.
    • RTX 4060: all pass.
    • Intel UHD: all pass or skip for missing features, except:
      • agc_driver_ds_swizzle and agc_driver_f32_dot2_rounding (no Float64), which fail the same way without this change;
      • agc_driver_compute_user_data_calls_registered, which exited once with 0xc0000374 during the suite and passed 3 of 3 runs on its own.
    • lavapipe 25.2.8: all pass or skip for missing features.

Why results don't change. The fixed value differs from the host result in two cases only:

  • NaN: the host result is a NaN. Any NaN operand or invalid operation gives one.
  • Tiny product: the product is tiny after rounding to 24 bits, and the flush returns a signed zero. A product that is tiny after rounding has an exact magnitude below 2^-126. The host rounds it to at most 2^-126, or to 0 if it flushes denormal results. Either way special is true.

So when special is false, the fixed value equals the host result, and selecting plain there gives exactly what the select chain gave before. The rare arm is the same IR as before, only emitted inside a branch.

Limits.

  • I haven't run it on AMD hardware.
  • Static code size grows. The run time win is per instruction executed; programs that are mostly f32 multiplies get larger SPIR-V and SASS.
  • On data that is mostly NaN, v_mul_f32 is about 6% slower.
  • Directed f32 rounding modes keep the plain selects for products.
  • A wave64 compute program kept at two lanes per invocation still selects inline for values the halves share.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: #4287
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4825561930 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4322). Originally posted by [karanvora2599](https://github.com/karanvora2599) on 2026-10-12T06:04:49Z. --- ### What `v_mul_f32`, `v_fma_f32`/`v_fmac_f32`, `v_add_f32` and `v_sub_f32` compute their AMD result fixups only when the host result needs them: a NaN, or for products a magnitude of at most 2^-126. Results are unchanged. This is stacked on #4287, which shrinks the NaN result selection itself. Only the last commit is new. **Background.** Every f32 multiply, fma and add computes two fixups on its host result: - the NaN result AMD returns: the first NaN operand, quieted in IEEE mode, or the default NaN (`nanResultF32`); - for products in `FLOAT_MODE`s that flush f32 denormals, the flush of products that are tiny after rounding to 24 bits (`flushTinyProduct`, #2839). Both are straight-line selects that run on every instruction. On an RTX 4060, `v_mul_f32` is 16.5 SASS instructions, where the multiply is one. In fma-rc's census of eleven titles (316,352 instructions, linked in #4061), `v_mul_f32` is 13.4% of all instructions and `v_add_f32`/`v_sub_f32`/`v_subrev_f32` 6.6%. **How.** - **Translator** (`rareFixupF32`): when a fixup was emitted, the result becomes `select(special, fixed, plain)`, where `plain` is the host result. - `special` is `isnan(plain)` for add and sub. - For mul and fma with the tiny-product flush, `special` is `((bits(plain) + 0x7fffff) & 0x7fffffff) < 0x1000000`: the result is a NaN, or its magnitude is at most 2^-126. That's three integer instructions. This form is used only with round to nearest even; directed f32 rounding keeps the plain selects. - The select carries a new `SelectFlags::rarelyTrue` flag. Optimizer passes see an ordinary `SelectF32`, and dropping the flag only loses the branch. - **Backend** (`SpirvFlowEmitter`): for each flagged select, the instructions used only by its rare arm are found, latest first, so the search stops at the first value with another use. They're emitted inside a selection (`EmitValueOrDefaultIfCondition`), and the select becomes the phi. - **Kept as plain selects:** - loop headers and continue targets, whose `OpLoopMerge` must stay in the header's first block; - values shared between the two lane halves of a wave64 program; - terminator conditions. **Before / after** on an RTX 4060 Laptop (Ada, driver 591.86), `FLOAT_MODE` 0xc0. Run time: dependent chains of 2,048 instructions over 16,384 groups of 32 lanes, median of 15 interleaved dispatches in one process. A temporary switch, not part of the PR, selected the plain selects for the comparison. | Chain | plain selects | this PR | |---|---|---| | `v_mul_f32` | 5.90 ms | 2.74 ms | | `v_fma_f32` | 7.17 ms | 3.87 ms | | `v_add_f32` | 4.29 ms | 3.78 ms | | `v_mul_f32`, every input a NaN | 5.95 ms | 6.34 ms | | `v_add_f32`, every input a NaN | 4.44 ms | 3.94 ms | | `v_mac_f32` (legacy mad, unchanged, control) | 0.56 ms | 0.59 ms | Both variants wrote the same results. Static SASS per instruction (`APS5_PIPELINE_STATS`, chain of 16) grows, since both paths are compiled: - `v_mul_f32`: 16.5 → 23.5; - `v_fma_f32`: 22.5 → 34 (VOP3) and 28 → 34; - `v_fmac_f32`: 20.5 → 29.5; - `v_sub_f32`: 11 → 12.5; - `v_add_f32`: 10.5 → 10.5. Registers are within ±5. ### Tested Windows 11, MinGW-w64 GCC 15.2.0, Release, `main` at d146ec1b plus #4287. RTX 4060 Laptop (driver 591.86), Intel UHD Graphics (Raptor Lake, driver 101.6790), lavapipe from Mesa 25.2.8 (the version CI installs; Windows build, `GALLIUM_OVERRIDE_CPU_CAPS=avx`). - The 41 f32 and modifier execution tests (`agc_driver_f32_*`, `agc_driver_fma_*`, `agc_driver_vop*`, `agc_denormal*`, `agc_driver_division_*` and others) pass on the RTX 4060, including `agc_driver_f32_arithmetic_nan`, which caught #2279's NaN quieting bug. This change reuses `nanResultF32` unchanged, so the IEEE-mode quieting can't drift. - Negative check: using the NaN-only fast check for products too, so tiny products skip the flush, makes lavapipe fail `agc_driver_f32_constant_factor_tininess` and `agc_driver_f32_denormal_flush`: `v_mul_f32 v12, v4, v5 is 0x00800000, expected 0x00000000` (2^-126 × (1 − 2^-24), tiny after rounding). The RTX 4060 and the Intel UHD pass that build, because their multiply already returns 0 for these products. lavapipe keeps f32 denormals and returns 2^-126. - Shader tests (`agc_driver_*`, `agc_shader_*`, `agc_spirv_*`, `vector_*`, `agc_masked_select`, `agc_validate_program`, `agc_denormal*`, `agc_float16_*`; 338 tests). The BDA tests that hang on driver 591.86 until #3291 lands are left out. - RTX 4060: all pass. - Intel UHD: all pass or skip for missing features, except: - `agc_driver_ds_swizzle` and `agc_driver_f32_dot2_rounding` (no `Float64`), which fail the same way without this change; - `agc_driver_compute_user_data_calls_registered`, which exited once with `0xc0000374` during the suite and passed 3 of 3 runs on its own. - lavapipe 25.2.8: all pass or skip for missing features. **Why results don't change.** The fixed value differs from the host result in two cases only: - **NaN:** the host result is a NaN. Any NaN operand or invalid operation gives one. - **Tiny product:** the product is tiny after rounding to 24 bits, and the flush returns a signed zero. A product that is tiny after rounding has an exact magnitude below 2^-126. The host rounds it to at most 2^-126, or to 0 if it flushes denormal results. Either way `special` is true. So when `special` is false, the fixed value equals the host result, and selecting `plain` there gives exactly what the select chain gave before. The rare arm is the same IR as before, only emitted inside a branch. **Limits.** - I haven't run it on AMD hardware. - Static code size grows. The run time win is per instruction executed; programs that are mostly f32 multiplies get larger SPIR-V and SASS. - On data that is mostly NaN, `v_mul_f32` is about 6% slower. - Directed f32 rounding modes keep the plain selects for products. - A wave64 compute program kept at two lanes per invocation still selects inline for values the halves share. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: #4287 - [x] AI-assisted: yes
MarcZX10 commented 2026-10-12 06:47:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-12T06:47:51Z.

Code review location: core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp; line 366

@@ -342,17 +342,32 @@ IrU32 TranslationContext::quietNan32(IrU32 bits) {
 }
 
 IrValue* TranslationContext::nanResultF32(std::initializer_list<IrValue*> sources, IrValue* result, IrValue* invalidProduct) {
-    const auto isNan = [&](IrValue& bits) -> IrValue& { return ir.UGreaterThan(ir.BitwiseAnd(bits, ir.Constant(0x7fffffffu)), ir.Constant(0x7f800000u)); };
-    IrValue* bits = &ir.BitCastU32(*result);
-    bits = &ir.Select(isNan(*bits), ir.Constant(0xffc00000u), *bits);
+    const auto isNan = [&](IrValue& value) -> IrValue& { return ir.Emit(IrOpcode::FPIsNan32, IrType::U1, {&value}); };
+    IrValue* candidate = nullptr;
     for (auto source = sources.end(); source != sources.begin();) {
         --source;
         IrValue& sourceBits = ir.BitCastU32(**source);
-        IrValue* selected = &isNan(sourceBits);
-        if (invalidProduct != nullptr && source + 1 == sources.end() && sources.size() == 3u) selected = &ir.LogicalAnd(*selected, ir.LogicalNot(*invalidProduct));
-        bits = &ir.Select(*selected, quietNan32(IrU32(sourceBits)).Value(), *bits);
+        if (candidate == nullptr) {
+            candidate = invalidProduct != nullptr && sources.size() == 3u ? &ir.Select(*invalidProduct, ir.Constant(0u), sourceBits) : &sourceBits;
+            continue;
+        }
+        candidate = &ir.Select(isNan(**source), sourceBits, *candidate);
+    }
+    IrValue& fallback = ir.Select(isNan(*result), ir.Constant(0xffc00000u), ir.BitCastU32(*result));
+    return &ir.BitCastF32(ir.Select(isNan(ir.BitCastF32(*candidate)), quietNan32(IrU32(*candidate)).Value(), fallback));
+}
+
+IrValue* TranslationContext::rareFixupF32(IrValue* plain, IrValue* fixed, bool tinyFlushed) {
+    if (fixed == plain) return fixed;
+    const std::uint32_t roundMode = floatMode.has_value() ? floatMode->floatMode & 3u : 0u;
+    if (tinyFlushed && roundMode != 0u) return fixed;
+    IrValue* special = nullptr;
+    if (tinyFlushed) {
+        special = &ir.ULessThan(ir.BitwiseAnd(ir.IAdd(ir.BitCastU32(*plain), ir.Constant(0x007fffffu)), ir.Constant(0x7fffffffu)), ir.Constant(0x01000000u));

This condition misses positive NaNs. For example, plain = 0x7fc00001 gives (bits + 0x007fffff) & 0x7fffffff == 0x7fffffff, so special is false and this bypasses fixed/nanResultF32. That can return the host NaN payload instead of AMD’s selected/quieted NaN. Could this predicate explicitly OR in FPIsNan32(plain) (or otherwise cover positive NaNs)?

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4245313804 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4322#discussion_r4245313804). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-12T06:47:51Z. **Code review location:** `core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp`; line 366 ~~~~diff @@ -342,17 +342,32 @@ IrU32 TranslationContext::quietNan32(IrU32 bits) { } IrValue* TranslationContext::nanResultF32(std::initializer_list<IrValue*> sources, IrValue* result, IrValue* invalidProduct) { - const auto isNan = [&](IrValue& bits) -> IrValue& { return ir.UGreaterThan(ir.BitwiseAnd(bits, ir.Constant(0x7fffffffu)), ir.Constant(0x7f800000u)); }; - IrValue* bits = &ir.BitCastU32(*result); - bits = &ir.Select(isNan(*bits), ir.Constant(0xffc00000u), *bits); + const auto isNan = [&](IrValue& value) -> IrValue& { return ir.Emit(IrOpcode::FPIsNan32, IrType::U1, {&value}); }; + IrValue* candidate = nullptr; for (auto source = sources.end(); source != sources.begin();) { --source; IrValue& sourceBits = ir.BitCastU32(**source); - IrValue* selected = &isNan(sourceBits); - if (invalidProduct != nullptr && source + 1 == sources.end() && sources.size() == 3u) selected = &ir.LogicalAnd(*selected, ir.LogicalNot(*invalidProduct)); - bits = &ir.Select(*selected, quietNan32(IrU32(sourceBits)).Value(), *bits); + if (candidate == nullptr) { + candidate = invalidProduct != nullptr && sources.size() == 3u ? &ir.Select(*invalidProduct, ir.Constant(0u), sourceBits) : &sourceBits; + continue; + } + candidate = &ir.Select(isNan(**source), sourceBits, *candidate); + } + IrValue& fallback = ir.Select(isNan(*result), ir.Constant(0xffc00000u), ir.BitCastU32(*result)); + return &ir.BitCastF32(ir.Select(isNan(ir.BitCastF32(*candidate)), quietNan32(IrU32(*candidate)).Value(), fallback)); +} + +IrValue* TranslationContext::rareFixupF32(IrValue* plain, IrValue* fixed, bool tinyFlushed) { + if (fixed == plain) return fixed; + const std::uint32_t roundMode = floatMode.has_value() ? floatMode->floatMode & 3u : 0u; + if (tinyFlushed && roundMode != 0u) return fixed; + IrValue* special = nullptr; + if (tinyFlushed) { + special = &ir.ULessThan(ir.BitwiseAnd(ir.IAdd(ir.BitCastU32(*plain), ir.Constant(0x007fffffu)), ir.Constant(0x7fffffffu)), ir.Constant(0x01000000u)); ~~~~ --- This condition misses positive NaNs. For example, `plain` = `0x7fc00001` gives `(bits + 0x007fffff) & 0x7fffffff == 0x7fffffff`, so `special` is false and this bypasses `fixed`/`nanResultF32`. That can return the host NaN payload instead of AMD’s selected/quieted NaN. Could this predicate explicitly OR in `FPIsNan32(plain)` (or otherwise cover positive NaNs)?
MarcZX10 commented 2026-10-12 06:48:15 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-12T06:48:15Z.

Code review location: core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp; line 366

@@ -342,17 +342,32 @@ IrU32 TranslationContext::quietNan32(IrU32 bits) {
 }
 
 IrValue* TranslationContext::nanResultF32(std::initializer_list<IrValue*> sources, IrValue* result, IrValue* invalidProduct) {
-    const auto isNan = [&](IrValue& bits) -> IrValue& { return ir.UGreaterThan(ir.BitwiseAnd(bits, ir.Constant(0x7fffffffu)), ir.Constant(0x7f800000u)); };
-    IrValue* bits = &ir.BitCastU32(*result);
-    bits = &ir.Select(isNan(*bits), ir.Constant(0xffc00000u), *bits);
+    const auto isNan = [&](IrValue& value) -> IrValue& { return ir.Emit(IrOpcode::FPIsNan32, IrType::U1, {&value}); };
+    IrValue* candidate = nullptr;
     for (auto source = sources.end(); source != sources.begin();) {
         --source;
         IrValue& sourceBits = ir.BitCastU32(**source);
-        IrValue* selected = &isNan(sourceBits);
-        if (invalidProduct != nullptr && source + 1 == sources.end() && sources.size() == 3u) selected = &ir.LogicalAnd(*selected, ir.LogicalNot(*invalidProduct));
-        bits = &ir.Select(*selected, quietNan32(IrU32(sourceBits)).Value(), *bits);
+        if (candidate == nullptr) {
+            candidate = invalidProduct != nullptr && sources.size() == 3u ? &ir.Select(*invalidProduct, ir.Constant(0u), sourceBits) : &sourceBits;
+            continue;
+        }
+        candidate = &ir.Select(isNan(**source), sourceBits, *candidate);
+    }
+    IrValue& fallback = ir.Select(isNan(*result), ir.Constant(0xffc00000u), ir.BitCastU32(*result));
+    return &ir.BitCastF32(ir.Select(isNan(ir.BitCastF32(*candidate)), quietNan32(IrU32(*candidate)).Value(), fallback));
+}
+
+IrValue* TranslationContext::rareFixupF32(IrValue* plain, IrValue* fixed, bool tinyFlushed) {
+    if (fixed == plain) return fixed;
+    const std::uint32_t roundMode = floatMode.has_value() ? floatMode->floatMode & 3u : 0u;
+    if (tinyFlushed && roundMode != 0u) return fixed;
+    IrValue* special = nullptr;
+    if (tinyFlushed) {
+        special = &ir.ULessThan(ir.BitwiseAnd(ir.IAdd(ir.BitCastU32(*plain), ir.Constant(0x007fffffu)), ir.Constant(0x7fffffffu)), ir.Constant(0x01000000u));

Correction: I recalculated this example, and my comment is wrong. 0x7fc00001 + 0x007fffff is 0x80400000; masking with 0x7fffffff gives 0x00400000, which is below 0x01000000, so the predicate does take the special path. Sorry for the false alarm; please disregard my suggestion to add an explicit NaN check.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4245315927 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4322#discussion_r4245315927). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-12T06:48:15Z. **Code review location:** `core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp`; line 366 ~~~~diff @@ -342,17 +342,32 @@ IrU32 TranslationContext::quietNan32(IrU32 bits) { } IrValue* TranslationContext::nanResultF32(std::initializer_list<IrValue*> sources, IrValue* result, IrValue* invalidProduct) { - const auto isNan = [&](IrValue& bits) -> IrValue& { return ir.UGreaterThan(ir.BitwiseAnd(bits, ir.Constant(0x7fffffffu)), ir.Constant(0x7f800000u)); }; - IrValue* bits = &ir.BitCastU32(*result); - bits = &ir.Select(isNan(*bits), ir.Constant(0xffc00000u), *bits); + const auto isNan = [&](IrValue& value) -> IrValue& { return ir.Emit(IrOpcode::FPIsNan32, IrType::U1, {&value}); }; + IrValue* candidate = nullptr; for (auto source = sources.end(); source != sources.begin();) { --source; IrValue& sourceBits = ir.BitCastU32(**source); - IrValue* selected = &isNan(sourceBits); - if (invalidProduct != nullptr && source + 1 == sources.end() && sources.size() == 3u) selected = &ir.LogicalAnd(*selected, ir.LogicalNot(*invalidProduct)); - bits = &ir.Select(*selected, quietNan32(IrU32(sourceBits)).Value(), *bits); + if (candidate == nullptr) { + candidate = invalidProduct != nullptr && sources.size() == 3u ? &ir.Select(*invalidProduct, ir.Constant(0u), sourceBits) : &sourceBits; + continue; + } + candidate = &ir.Select(isNan(**source), sourceBits, *candidate); + } + IrValue& fallback = ir.Select(isNan(*result), ir.Constant(0xffc00000u), ir.BitCastU32(*result)); + return &ir.BitCastF32(ir.Select(isNan(ir.BitCastF32(*candidate)), quietNan32(IrU32(*candidate)).Value(), fallback)); +} + +IrValue* TranslationContext::rareFixupF32(IrValue* plain, IrValue* fixed, bool tinyFlushed) { + if (fixed == plain) return fixed; + const std::uint32_t roundMode = floatMode.has_value() ? floatMode->floatMode & 3u : 0u; + if (tinyFlushed && roundMode != 0u) return fixed; + IrValue* special = nullptr; + if (tinyFlushed) { + special = &ir.ULessThan(ir.BitwiseAnd(ir.IAdd(ir.BitCastU32(*plain), ir.Constant(0x007fffffu)), ir.Constant(0x7fffffffu)), ir.Constant(0x01000000u)); ~~~~ --- Correction: I recalculated this example, and my comment is wrong. `0x7fc00001 + 0x007fffff` is `0x80400000`; masking with `0x7fffffff` gives `0x00400000`, which is below `0x01000000`, so the predicate does take the special path. Sorry for the false alarm; please disregard my suggestion to add an explicit NaN check.
karanvora2599 commented 2026-10-12 13:23:14 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by karanvora2599 on 2026-10-12T13:23:14Z.

Code review location: core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp; line 366

@@ -342,17 +342,32 @@ IrU32 TranslationContext::quietNan32(IrU32 bits) {
 }
 
 IrValue* TranslationContext::nanResultF32(std::initializer_list<IrValue*> sources, IrValue* result, IrValue* invalidProduct) {
-    const auto isNan = [&](IrValue& bits) -> IrValue& { return ir.UGreaterThan(ir.BitwiseAnd(bits, ir.Constant(0x7fffffffu)), ir.Constant(0x7f800000u)); };
-    IrValue* bits = &ir.BitCastU32(*result);
-    bits = &ir.Select(isNan(*bits), ir.Constant(0xffc00000u), *bits);
+    const auto isNan = [&](IrValue& value) -> IrValue& { return ir.Emit(IrOpcode::FPIsNan32, IrType::U1, {&value}); };
+    IrValue* candidate = nullptr;
     for (auto source = sources.end(); source != sources.begin();) {
         --source;
         IrValue& sourceBits = ir.BitCastU32(**source);
-        IrValue* selected = &isNan(sourceBits);
-        if (invalidProduct != nullptr && source + 1 == sources.end() && sources.size() == 3u) selected = &ir.LogicalAnd(*selected, ir.LogicalNot(*invalidProduct));
-        bits = &ir.Select(*selected, quietNan32(IrU32(sourceBits)).Value(), *bits);
+        if (candidate == nullptr) {
+            candidate = invalidProduct != nullptr && sources.size() == 3u ? &ir.Select(*invalidProduct, ir.Constant(0u), sourceBits) : &sourceBits;
+            continue;
+        }
+        candidate = &ir.Select(isNan(**source), sourceBits, *candidate);
+    }
+    IrValue& fallback = ir.Select(isNan(*result), ir.Constant(0xffc00000u), ir.BitCastU32(*result));
+    return &ir.BitCastF32(ir.Select(isNan(ir.BitCastF32(*candidate)), quietNan32(IrU32(*candidate)).Value(), fallback));
+}
+
+IrValue* TranslationContext::rareFixupF32(IrValue* plain, IrValue* fixed, bool tinyFlushed) {
+    if (fixed == plain) return fixed;
+    const std::uint32_t roundMode = floatMode.has_value() ? floatMode->floatMode & 3u : 0u;
+    if (tinyFlushed && roundMode != 0u) return fixed;
+    IrValue* special = nullptr;
+    if (tinyFlushed) {
+        special = &ir.ULessThan(ir.BitwiseAnd(ir.IAdd(ir.BitCastU32(*plain), ir.Constant(0x007fffffu)), ir.Constant(0x7fffffffu)), ir.Constant(0x01000000u));

Thanks for checking it either way. The check covers every NaN, of either sign: bits from 0x7f800001 to 0x7fffffff (or the same with the sign bit set, where the add wraps) map to 0 through 0x7ffffe after the add and mask, all below 0x1000000. Infinity maps to 0x7fffffff and stays on the fast path, which is right since neither fixup changes an infinite result.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4248505000 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4322#discussion_r4248505000). Originally posted by [karanvora2599](https://github.com/karanvora2599) on 2026-10-12T13:23:14Z. **Code review location:** `core/shader/recompiler/Translation/src/TranslationContext/OperandAccess.cpp`; line 366 ~~~~diff @@ -342,17 +342,32 @@ IrU32 TranslationContext::quietNan32(IrU32 bits) { } IrValue* TranslationContext::nanResultF32(std::initializer_list<IrValue*> sources, IrValue* result, IrValue* invalidProduct) { - const auto isNan = [&](IrValue& bits) -> IrValue& { return ir.UGreaterThan(ir.BitwiseAnd(bits, ir.Constant(0x7fffffffu)), ir.Constant(0x7f800000u)); }; - IrValue* bits = &ir.BitCastU32(*result); - bits = &ir.Select(isNan(*bits), ir.Constant(0xffc00000u), *bits); + const auto isNan = [&](IrValue& value) -> IrValue& { return ir.Emit(IrOpcode::FPIsNan32, IrType::U1, {&value}); }; + IrValue* candidate = nullptr; for (auto source = sources.end(); source != sources.begin();) { --source; IrValue& sourceBits = ir.BitCastU32(**source); - IrValue* selected = &isNan(sourceBits); - if (invalidProduct != nullptr && source + 1 == sources.end() && sources.size() == 3u) selected = &ir.LogicalAnd(*selected, ir.LogicalNot(*invalidProduct)); - bits = &ir.Select(*selected, quietNan32(IrU32(sourceBits)).Value(), *bits); + if (candidate == nullptr) { + candidate = invalidProduct != nullptr && sources.size() == 3u ? &ir.Select(*invalidProduct, ir.Constant(0u), sourceBits) : &sourceBits; + continue; + } + candidate = &ir.Select(isNan(**source), sourceBits, *candidate); + } + IrValue& fallback = ir.Select(isNan(*result), ir.Constant(0xffc00000u), ir.BitCastU32(*result)); + return &ir.BitCastF32(ir.Select(isNan(ir.BitCastF32(*candidate)), quietNan32(IrU32(*candidate)).Value(), fallback)); +} + +IrValue* TranslationContext::rareFixupF32(IrValue* plain, IrValue* fixed, bool tinyFlushed) { + if (fixed == plain) return fixed; + const std::uint32_t roundMode = floatMode.has_value() ? floatMode->floatMode & 3u : 0u; + if (tinyFlushed && roundMode != 0u) return fixed; + IrValue* special = nullptr; + if (tinyFlushed) { + special = &ir.ULessThan(ir.BitwiseAnd(ir.IAdd(ir.BitCastU32(*plain), ir.Constant(0x007fffffu)), ir.Constant(0x7fffffffu)), ir.Constant(0x01000000u)); ~~~~ --- Thanks for checking it either way. The check covers every NaN, of either sign: bits from `0x7f800001` to `0x7fffffff` (or the same with the sign bit set, where the add wraps) map to `0` through `0x7ffffe` after the add and mask, all below `0x1000000`. Infinity maps to `0x7fffffff` and stays on the fast path, which is right since neither fixup changes an infinite result.
simonbbby commented 2026-10-12 19:21:27 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by simonbbby on 2026-10-12T19:21:27Z.


A title-level cost worth considering alongside the focused arithmetic tests: in the saved Linux verification batch, head 85e88e527 merged onto main 2a5eca11 makes Surround Sound Studio (PPSA99051 01.000.003, open-source homebrew) hit the submission timeout on RADV where base passes. This is the large f8d1fab9 pixel shader from #4399.

Release, ANYPS5_ENABLE_SPIRV_TOOLS=ON; alternating runs against base with fresh shader caches:

Base + this PR
Fragment SPIR-V at draw, RADV 449,101 words 601,261 words (+34%)
RADV pipeline build 383–390 ms 528–549 ms
NVIDIA RTX 3090 pipeline build 2150–2184 ms 3800–3862 ms
Draw-time SPIRV-Tools pass 437–449 ms 4731 ms RADV / 4889 ms NVIDIA
RADV cold run at normal title wait 3/3 pass 0/4 pass

Each failing RADV run exits roughly 2.17–2.19 s after registration recompilation ends, during draw-time optimization, before driver pipeline creation begins. NVIDIA already fails at base and still fails with this PR.

Timings use a local instrumented build with sceKernelUsleep extended 20× to let the work finish; the pass/fail rows use the normal budget. No timer or wait-budget changes are proposed for merging. The recorded runs used gfx1036/RADV Mesa 25.2.8 and RTX 3090/NVIDIA 595.99.02, Ryzen 9 9950X, Ubuntu 24.04, GCC 13.3. This batch predates newer main; the PR head remains unchanged. SPIRV-Tools OFF and #4287 alone were not tested for this workload.

Could the performance evaluation include this large shader and the draw-time optimization cost? Arithmetic correctness checks alone do not capture this regression.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6131041884 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4322#issuecomment-6131041884). Originally posted by [simonbbby](https://github.com/simonbbby) on 2026-10-12T19:21:27Z. --- A title-level cost worth considering alongside the focused arithmetic tests: in the saved Linux verification batch, head `85e88e527` merged onto `main` `2a5eca11` makes Surround Sound Studio (PPSA99051 01.000.003, open-source homebrew) hit the submission timeout on RADV where base passes. This is the large `f8d1fab9` pixel shader from #4399. Release, `ANYPS5_ENABLE_SPIRV_TOOLS=ON`; alternating runs against base with fresh shader caches: | | Base | + this PR | |---|---|---| | Fragment SPIR-V at draw, RADV | 449,101 words | 601,261 words (+34%) | | RADV pipeline build | 383–390 ms | 528–549 ms | | NVIDIA RTX 3090 pipeline build | 2150–2184 ms | 3800–3862 ms | | Draw-time SPIRV-Tools pass | 437–449 ms | 4731 ms RADV / 4889 ms NVIDIA | | RADV cold run at normal title wait | 3/3 pass | 0/4 pass | Each failing RADV run exits roughly 2.17–2.19 s after registration recompilation ends, during draw-time optimization, before driver pipeline creation begins. NVIDIA already fails at base and still fails with this PR. Timings use a local instrumented build with `sceKernelUsleep` extended 20× to let the work finish; the pass/fail rows use the normal budget. No timer or wait-budget changes are proposed for merging. The recorded runs used gfx1036/RADV Mesa 25.2.8 and RTX 3090/NVIDIA 595.99.02, Ryzen 9 9950X, Ubuntu 24.04, GCC 13.3. This batch predates newer main; the PR head remains unchanged. SPIRV-Tools OFF and #4287 alone were not tested for this workload. Could the performance evaluation include this large shader and the draw-time optimization cost? Arithmetic correctness checks alone do not capture this regression.
MarcZX10 commented 2026-10-12 20:31:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-12T20:31:47Z.


This title-level result is important for the stated performance goal: the shader grows about 34%, the draw-time optimizer rises from roughly 0.44 s to 4.7–4.9 s, and the normal-budget RADV run goes from 3/3 to 0/4. I would hold the optimization until its SPIR-V growth and this timeout are explained and a semantics-preserving candidate is measured on this workload; the arithmetic-focused tests alone do not cover it.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6132112038 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4322#issuecomment-6132112038). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-12T20:31:47Z. --- This title-level result is important for the stated performance goal: the shader grows about 34%, the draw-time optimizer rises from roughly 0.44 s to 4.7–4.9 s, and the normal-budget RADV run goes from 3/3 to 0/4. I would hold the optimization until its SPIR-V growth and this timeout are explained and a semantics-preserving candidate is measured on this workload; the arithmetic-focused tests alone do not cover it.
karanvora2599 commented 2026-10-12 20:41:53 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by karanvora2599 on 2026-10-12T20:41:53Z.


Thanks @simonbbby. You're right, and the cost turned out larger than the arithmetic tests could show, so I'm closing this.

I couldn't run the f8d1fab9 shader here, so I measured the same question on synthetic shaders: NVIDIA pipeline creation on an RTX 4060 (driver 591.86), for shaders the driver hadn't seen (a unique literal per run), with the SPIR-V a release build hands the driver (APS5_SPIRV_OPT=none). A temporary switch, not committed, compared this PR's per-instruction branches against the straight-line selects it replaces. Medians of 5 or 6 interleaved runs, which all landed within a few percent:

Shader Straight-line This PR Run time, this PR
8 interleaved f32 chains (mul, add, fma, sub), 1,024 ops 654 ms 964 ms (+47%) −16%
same, 4,096 ops 3.49 s 7.62 s (+119%) no change
one dependent chain, 2,048 v_mul_f32 3.44 s 3.56 s −54%
one dependent chain, 2,048 v_add_f32 1.33 s 2.24 s (+69%) −12%

A single dependent chain gives the driver nothing to schedule, which is why my earlier numbers missed this. With independent work, splitting every f32 instruction into its own branch costs far more to compile, and the cost grows faster than the shader. Your +77% on the RTX 3090 is in line with that. Branching only for products, so add and sub stay straight-line, still costs +18% at 1,024 ops and +77% at 4,096. The run-time gain shows up only in f32-dense code, and that doesn't justify doubling pipeline creation or failing cold runs on RADV.

#4539 doesn't need this PR. Its rules (the tiny-product flush, the NaN select and the constant factor) prove a multiply's result denormal-free on the straight-line code too. I'm rebasing it onto #4287 alone and will update it there.

The size of the fixups themselves, about 115 SPIR-V words per f32 instruction even straight-line, is the bigger compile-time lever. I'll look at shrinking that next.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6132259130 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4322#issuecomment-6132259130). Originally posted by [karanvora2599](https://github.com/karanvora2599) on 2026-10-12T20:41:53Z. --- Thanks @simonbbby. You're right, and the cost turned out larger than the arithmetic tests could show, so I'm closing this. I couldn't run the `f8d1fab9` shader here, so I measured the same question on synthetic shaders: NVIDIA pipeline creation on an RTX 4060 (driver 591.86), for shaders the driver hadn't seen (a unique literal per run), with the SPIR-V a release build hands the driver (`APS5_SPIRV_OPT=none`). A temporary switch, not committed, compared this PR's per-instruction branches against the straight-line selects it replaces. Medians of 5 or 6 interleaved runs, which all landed within a few percent: | Shader | Straight-line | This PR | Run time, this PR | |---|---|---|---| | 8 interleaved f32 chains (mul, add, fma, sub), 1,024 ops | 654 ms | 964 ms (+47%) | −16% | | same, 4,096 ops | 3.49 s | 7.62 s (+119%) | no change | | one dependent chain, 2,048 `v_mul_f32` | 3.44 s | 3.56 s | −54% | | one dependent chain, 2,048 `v_add_f32` | 1.33 s | 2.24 s (+69%) | −12% | A single dependent chain gives the driver nothing to schedule, which is why my earlier numbers missed this. With independent work, splitting every f32 instruction into its own branch costs far more to compile, and the cost grows faster than the shader. Your +77% on the RTX 3090 is in line with that. Branching only for products, so add and sub stay straight-line, still costs +18% at 1,024 ops and +77% at 4,096. The run-time gain shows up only in f32-dense code, and that doesn't justify doubling pipeline creation or failing cold runs on RADV. #4539 doesn't need this PR. Its rules (the tiny-product flush, the NaN select and the constant factor) prove a multiply's result denormal-free on the straight-line code too. I'm rebasing it onto #4287 alone and will update it there. The size of the fixups themselves, about 115 SPIR-V words per f32 instruction even straight-line, is the bigger compile-time lever. I'll look at shrinking that next.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!4322
No description provided.