Commit graph

4,790 commits

Author SHA1 Message Date
LibretroAdmin
299fdcb451 core/gpu_sw: drop redundant uint16_t intermediates in 5551/565 fast paths
CopyOutRow16<RGBA5551> and CopyOutRow16<RGB565> use SSE2's
_mm_set1_epi16(int16_t) to build immediate AND/SLLI masks
(0x3E0 and 0x20). Each callsite went:

  static_cast<int16_t>(static_cast<uint16_t>(0x3E0))

The uint16_t intermediate was guarding against narrowing from
int (which is what an unadorned 0x3E0 is), but 0x3E0 (992)
and 0x20 (32) both fit comfortably in int16_t's positive range
(max 32767), so static_cast<int16_t>(0x3E0) is well-defined on
every supported compiler without the intermediate. Drop the
extra cast at all three sites.

Codegen-identical (verified by MD5 of the .so before and after
the change). 3 sites, 0 lines net.
2026-05-14 15:13:21 +02:00
LibretroAdmin
7537ee7a27 common/types: use stdint typedefs everywhere instead of custom u32/s32 aliases
The codebase carried custom aliases in src/common/types.h:

  using s8  = int8_t;
  using u8  = uint8_t;
  using s16 = int16_t;
  using u16 = uint16_t;
  using s32 = int32_t;
  using u32 = uint32_t;
  using s64 = int64_t;
  using u64 = uint64_t;

These are pure aliases - they alias the C99/C++11 fixed-width
exact types from <cstdint> verbatim - and the short form was
used throughout in ~8,400 places. The short form is a
convention common in emulator/game code, but it conflicts with
the convention used by every other piece of code anyone on this
project ever touches (kernel, libretro frontends and other
cores, stdlib code, etc.), and the savings are five characters
per use.

Mechanical rename across src/:

  s8 -> int8_t
  u8 -> uint8_t
  s16 -> int16_t
  u16 -> uint16_t
  s32 -> int32_t
  u32 -> uint32_t
  s64 -> int64_t
  u64 -> uint64_t

Word-boundary substitution via \b{name}\b. Verified no false
positives:
  - No string literal contains "u32" etc. (single-line scan
    of every .cpp/.h/.inl in src/).
  - No identifier contains the alias as a substring; \b prevents
    matching inside foo_u32 / u32_bar style names but a separate
    check confirmed there are no such identifiers in src/
    anyway.

The dep/ directory is left untouched - some third-party code
there (zstd, dr_libs, libchdr) has its own unrelated "u32"
struct fields and types that are local to those compilation units.

Aliases removed from src/common/types.h. The header keeps
<cstdint> (the BCD helpers there still use uint8_t) and stays
the same shape it was post-types-cleanup.

Build: Makefile.libretro platform=unix - clean.
Codegen identical: the produced swanstation_libretro.so is
byte-for-byte the same as the pre-rename build, MD5
453480b212f78f0e0cf56fc893972b24 in both cases. This is
expected: u32 and uint32_t are the same type to the compiler;
the rename is purely lexical.

retro_* exports: 25 (unchanged).

210 files changed, +7926 -7935 (the -9 net delta is the eight
'using' lines removed from types.h plus blank-line cleanup
around them).
2026-05-14 15:13:16 +02:00
LibretroAdmin
94920ff59c common/string: prune 22 unused methods, fold internals, fix dormant Replace bug
A long-running audit of the custom String class found 22 public
methods, all 8 of String's comparison operators, the
StaticString macro, and the EmptyString global with zero callers
anywhere in the tree. Several more methods were only called from
within string.cpp itself by methods that are themselves unused.
Plus the (also internal-only) Replace machinery had a real bug.

This change is mechanical with one exception: the Replace
rewrite, called out below.

Members dropped (no callers anywhere):

  AppendCharacter
  AppendFormattedString          (printflike overload)
  CompareInsensitive             (both overloads)
  Find                           (both overloads)
  GetWritableBufferSize
  NumericCompare                 (both overloads, only used by
                                  the unused operator</>)
  NumericCompareInsensitive      (both overloads)
  ToLower
  ToUpper
  LStrip
  RStrip
  Strip
  Erase                          (only used by L/R/Strip, gone
                                  with them)
  Shrink                         (only called by Resize's
                                  skrinkIfSmaller=true branch,
                                  which no caller ever takes)
  Replace(char, char)
  operator==(const String&)      (and char* overload)
  operator!=(const String&)      (and char* overload)
  operator<(const String&)       (and char* overload)
  operator>(const String&)       (and char* overload)

Plus:

  EmptyString                    global - 0 references
  StaticString(Text)             rodata-string macro - 0 references
  <limits> include               unused after Erase/AppendSubString
                                 are gone
  <cctype> include               unused after ToLower/ToUpper are
                                 gone
  CASE_COMPARE macro             unused after the *Insensitive
                                 methods are gone

Members folded inline into their one caller:

  Obliterate                     was used only by Clear() to wipe
                                 a shared/read-only buffer. The
                                 two-line body (StringDataRelease
                                 + reseat to &s_EmptyStringData)
                                 is inlined there.
  AppendFormattedStringVA        was used only by FormatVA. The
                                 stack-buffer/heap-fallback
                                 vsnprintf loop is now in FormatVA
                                 directly.

Members converted to file-local helpers in string.cpp:

  Reserve                        only caller was the internal Replace.
                                 Now a static
                                 'StringReserve(StringData*&, u32)'
                                 file-local helper. The Force flag
                                 wasn't exercised by Replace and
                                 has been dropped.

Resize signature simplified:

  Resize(u32, char, bool)        -> Resize(u32, char)
  The skrinkIfSmaller=true branch ran Shrink which ran Reserve;
  the only external caller (state_wrapper.cpp) passes only one
  argument, so the parameter and the entire dead branch are
  dropped.

Replace bug fix (dormant):

  String::Replace(const char* searchString, const char* replaceString)
  had broken offset arithmetic. The original code computed offsets
  with 's32(pStart - pCurrent)' but never updated pStart between
  iterations, then passed those negative offsets to AppendSubString
  whose negative-offset branch reinterprets them as
  'count-from-end' offsets. Concretely, '"x=%n".Replace("%n", "42")'
  produced '"%42"' instead of '"x=42"'.

  Verified by running the original and the rewrite side by side
  against a small test harness:
    '"x=%n".Replace("%n", "42")'        : orig '%42'   new 'x=42'
    '"%n".Replace("%n", "42")'          : orig '%42'   new '42'
    '"%n end".Replace("%n", "42")'      : orig '%n en42 end'  new '42 end'
    '"a%nb%nc".Replace("%n", "X")'      : orig 'cXb%Xc'  new 'aXbXc'
    '"hello".Replace("%n", "42")'       : orig 'hello'  new 'hello'

  The new implementation tracks pStart correctly (advancing it
  past each match's replacement) and copies the [pStart, pCurrent)
  prefix into tempString via InternalAppend rather than the
  confused AppendSubString negative-offset dance.

  Important: this bug is dormant. The only caller in the tree is
  HostInterface::TranslateString(context, str, disambiguation, n)
  in src/core/host_interface.cpp, and the 'if (n >= 0)' guard
  around the Replace calls means the broken path only runs when
  a caller passes n >= 0 for plural translation. No call site in
  the tree passes n, so the buggy code path has never run in any
  shipped build. The fix is included here because (a) leaving
  broken code in the tree is worse than fixing it while we're
  here cleaning up the class, and (b) the rewrite removes the
  last user of the dead AppendSubString and Swap members.

Header and cpp shrink:

  src/common/string.h:    376 -> 287 lines (-24%)
  src/common/string.cpp:  830 -> 541 lines (-35%)

Build: Makefile.libretro platform=unix - clean, no warnings.
swanstation_libretro.so size: 8025928 -> 8020440 bytes (-5488,
roughly the body sizes of the removed methods, the unused
StringDataIsShared invocations they performed, and the operator
dispatch).
retro_* exports: 25 (unchanged).
2026-05-14 14:50:13 +02:00
LibretroAdmin
e6dd5cf566 common/jit_code_buffer: drop two unused constructors
JitCodeBuffer had three constructors:

  JitCodeBuffer()
  JitCodeBuffer(u32 size, u32 far_code_size)
  JitCodeBuffer(void* buffer, u32 size, u32 far_code_size, u32 guard_size)

Only the default one is ever called. The single instance in the
tree is

  static JitCodeBuffer s_code_buffer;   // cpu_code_cache.cpp

which is default-constructed and then driven explicitly through
either Initialize(buffer, size, far_code_size, guard_size) or
Allocate(size, far_code_size) at boot in CodeCache::Initialize.

The two unused constructors are dead, and the four-argument one
had a latent bug to boot: its body called

  Initialize(buffer, size, far_code_size);

with three arguments rather than four, silently dropping the
guard_pages parameter on the floor. Because nothing called the
constructor, the bug never bit, but anyone trying to use the
non-default form would have ended up with an unguarded buffer
without warning.

Drop both. The header is now down to:

  JitCodeBuffer();
  ~JitCodeBuffer();

plus the existing Allocate / Initialize / Destroy / Reset and
the rest of the explicit lifecycle API.

Build: Makefile.libretro platform=unix - clean, no warnings.
swanstation_libretro.so size: 8026128 -> 8025928 (-200 bytes,
the two now-absent constructors and their epilogue code).
retro_* exports: 25 (unchanged).

12 lines deleted, 0 added, 2 files (jit_code_buffer.h and .cpp).
2026-05-14 14:50:09 +02:00
LibretroAdmin
778cb660d0 common/types: drop <cstring>, add explicit includes at the 41 callers
types.h carried <cstring> for transitive purposes only - the header
itself never references std::memcpy / std::memset / std::strlen
etc. 41 TUs across the tree used those C-string functions while
relying on types.h to supply the declaration.

Add an explicit '#include <cstring>' to each of those files and
drop it from types.h. The headers that also use cstring functions
(error.h, jit_code_buffer.h are not in the list because they
already include <cstring> directly, or use the C-namespace
<string.h> already in scope) are unaffected.

Files getting an explicit <cstring>:

  src/common:  cd_image.cpp, cd_image_ecm.cpp, cd_image_mds.cpp,
               cd_image_memory.cpp, cd_image_pbp.cpp,
               cd_image_ppf.cpp, cd_subchannel_replacement.cpp,
               cue_parser.cpp, d3d12/shader_cache.cpp,
               d3d12/staging_texture.cpp, d3d12/texture.cpp,
               d3d12/util.cpp, iso_reader.cpp, jit_code_buffer.cpp,
               md5_digest.cpp, vulkan/shader_cache.cpp,
               vulkan/staging_texture.cpp
  src/core:    bios.cpp, bios.h, bus.cpp, cdrom.cpp, cheats.cpp,
               cpu_code_cache.cpp, cpu_recompiler_code_generator.cpp,
               cpu_recompiler_register_cache.cpp, dma.cpp, gpu.cpp,
               gpu_hw.cpp, gpu_hw.h, gpu_hw_d3d11.cpp,
               gpu_hw_d3d12.cpp, gpu_hw_opengl.cpp,
               gpu_hw_vulkan.cpp, gpu_sw.cpp, gte.cpp, mdec.cpp,
               memory_card_image.cpp, pgxp.cpp, spu.cpp, system.cpp
  src/libretro: libretro_host_display.cpp

Most files get one '#include <cstring>' added into the existing
system-include block, sorted alphabetically. A handful of files
(system.cpp, memory_card_image.cpp, d3d12/shader_cache.cpp)
had pre-existing blank-line separations between the stdlib
include block and libretro third-party headers (<compat/strl.h>,
<file/file_path.h>); those separations are preserved.

Build: Makefile.libretro platform=unix - clean, no warnings.
swanstation_libretro.so size unchanged (8026128 bytes).
retro_* exports: 25 (unchanged).

types.h now only includes <cstddef>, <cstdint>, and <type_traits>
- the three headers it actually needs for its own contents.
2026-05-14 14:20:36 +02:00
LibretroAdmin
9e316bee3d common/types: drop <limits>, add explicit includes at the 7 callers
types.h carried <limits> for transitive purposes only - the header
itself never references std::numeric_limits. Seven TUs in the tree
used numeric_limits while relying on types.h to bring it in:

  src/common/cue_parser.cpp
  src/common/cd_image_memory.cpp
  src/common/vulkan/builders.cpp
  src/core/playstation_mouse.cpp
  src/core/timers.cpp
  src/core/settings.cpp
  src/core/spu.cpp

Add an explicit '#include <limits>' to each and drop it from
types.h. The three in-tree headers that also reference
numeric_limits (string.h, rectangle.h, memory_arena.h) already
included <limits> directly, so no change to them.

Build: Makefile.libretro platform=unix - clean, .so size and
retro_* exports unchanged. 8 files, +7 lines, -1 line.
2026-05-14 14:20:32 +02:00
LibretroAdmin
420a7b2b36 common: prune more unused includes from headers and one transitive caller
Three small header cleanups, plus one matching add in a .cpp that
was reaching <algorithm> via one of the cleaned headers.

  iso_reader.h        - drop <memory>. The header defines a class
                        with std::optional<u32>/<u64> members and
                        no smart-pointer / allocator usage at all.
                        The one transitive caller that used to
                        reach <memory> through here (system.cpp)
                        gets it from <file_system.h>, <byte_stream.h>,
                        and <host_interface.h> already.

  cd_subchannel_replacement.h - drop <cstdio>. The header has no
                        FILE*/printf/scanf usage. The one transitive
                        caller was cd_image_pbp.cpp, which only
                        contained a commented-out printf and no
                        real cstdio dependency.

  string.h            - drop <algorithm>. The String class doesn't
                        call any std:: algorithms.

  cd_image_pbp.cpp    - add <algorithm>. It calls std::reverse at
                        line 105 and was getting it transitively
                        through string.h; once string.h drops the
                        include, this file needs its own.

Build: Makefile.libretro platform=unix - clean, .so size and
retro_* export count unchanged.
2026-05-14 14:20:28 +02:00
LibretroAdmin
b20cffcc38 common: prune more unused includes in cd image and timer/filesystem sources
Six more files in src/common with includes that aren't doing
anything for them. None changes behaviour, all build clean.

  file_system.cpp     - drop <algorithm> and <cstdlib>.
                        No std:: algorithms; free() comes from
                        the platform <stdlib.h> the file already
                        includes line by line.
  timer.cpp           - drop <cstdio> and <cstdlib>.
                        File has zero std:: usage and zero C
                        stdio/stdlib calls; everything goes
                        through platform headers
                        (<sys/time.h>, <time.h>, <unistd.h>,
                        windows_headers.h on Win32).
  cd_image_memory.cpp - drop <algorithm>. Uses std::make_unique
                        and std::memcpy, none of std:: algos.
  cd_image_m3u.cpp    - drop <algorithm>. Uses std::istringstream
                        and std::getline (<sstream>) and string
                        manipulation, but no std:: algos.
  cd_image_mds.cpp    - drop <algorithm>. Uses memcpy/memcmp/
                        make_unique only.
  cd_image_pbp.cpp    - drop <cstdio>. No printf/fopen/sscanf
                        family used; the file just talks to
                        ByteStream wrappers and miniz.

Files I considered but kept the include:

  page_fault_handler.cpp - uses std::find_if (<algorithm>).
  cd_subchannel_replacement.cpp - uses std::copy_n (<algorithm>).
  cd_image_chd.cpp    - uses std::sscanf (<cstdio>) and a real
                        std::algorithm call elsewhere.

Build: Makefile.libretro platform=unix - clean, no warnings.
6 files, 9 deletions, 0 insertions.
2026-05-14 14:20:20 +02:00
LibretroAdmin
e18d502336 common: prune unused includes and forward-decls in widely-used headers
Four small IWYU cleanups in headers that are included from many
TUs across the tree. None changes behaviour, all build clean
under Makefile.libretro platform=unix.

common/log.h
  Drop <cinttypes>. log.h doesn't define or use any of the PRI*/
  SCN* format-string macros, and grep confirms no consumer relies
  on transitively getting them via log.h either - call sites that
  need PRI* include <cinttypes> directly. <mutex> is kept: several
  files (gpu_hw_d3d11.cpp, gpu_hw_d3d12.cpp, gpu_hw_vulkan.cpp,
  cdrom_async_reader.cpp) use std::mutex and reach it transitively
  through log.h. Pulling it out of log.h would require IWYU
  patches at each of those callsites.

common/image.h
  Drop the 'class ByteStream;' forward-declaration. ByteStream is
  never referenced anywhere in image.h or image.cpp. It looks
  like a leftover from a previous prototype that took a
  ByteStream* argument.

common/rectangle.h
  Drop <type_traits> and <cstring>. The Rectangle template uses
  std::min, std::max, std::tie, and std::numeric_limits (from
  <algorithm>, <tuple>, <limits>), but no type-traits and no
  memcpy/memset.

common/heap_array.h
  Drop <type_traits>, add <cstddef>. HeapArray doesn't use any
  type-traits, but it does use std::size_t and std::ptrdiff_t
  - both of which were arriving transitively via <algorithm>.
  Make the dependency explicit.

Combined: -6 lines, +1 line, four files.
2026-05-14 14:02:18 +02:00
LibretroAdmin
cf8ae118a7 common/error: prune unused includes
error.cpp pulled <cstdlib>, <type_traits>, and (on Windows)
windows_headers.h, none of which it actually uses:

  - <cstdlib>:           no std::malloc / abort / exit / etc.
  - <type_traits>:       no is_*, conditional, enable_if, etc.
  - windows_headers.h:   no HRESULT / HANDLE / Win32 API at all.

What it does use is std::va_list and the va_start/va_end macros
(in SetFormattedMessage). Those were getting in via a transitive
include - drop the dead headers, add <cstdarg> explicitly so the
TU's stated dependencies match the symbols it actually touches.

No behaviour change. Build clean on Makefile.libretro
platform=unix.
2026-05-14 14:02:15 +02:00
LibretroAdmin
4a5c91d212 common/types: include <cstddef> for offsetof, drop UB fallback macro
types.h carried a fallback definition of offsetof gated by
`#ifndef offsetof`:

  #ifndef offsetof
  #define offsetof(st, m) ((size_t)((char*)&((st*)(0))->m - (char*)0))
  #endif

The fallback evaluates a member access through a null `(st*)(0)`
pointer. That's undefined behaviour in C++ (lvalue access on a
null pointer, even when only the address is taken), and the only
reason it works in practice is that every real callsite includes
<cstddef> (or some standard header that pulls it in) before
types.h gets parsed, so the `#ifndef offsetof` keeps the
well-defined compiler builtin and the fallback never gets
expanded.

That's fragile: anyone who writes a TU whose only string-handling
include is types.h, then uses offsetof, silently picks up the UB
form.

Fix is mechanical: include <cstddef> from types.h directly and
drop the fallback. <cstddef> defines offsetof as the compiler's
__builtin_offsetof on GCC/Clang and the analogous intrinsic on
MSVC - all of which are well-defined.

All current offsetof users live in cpu_recompiler_code_generator_x64.cpp
(and the aarch32/aarch64 sources). They reach offsetof transitively
via cpu_core.h -> state_wrapper.h -> error.h -> <cstddef>, so they
were already getting the standard macro; this change makes that
guarantee explicit at the header that supplies the rest of the
type aliases.

Build:
  Makefile.libretro platform=unix - clean, no new warnings.
  swanstation_libretro.so size: unchanged (the standard offsetof
  inlines to the same compile-time constant on every caller).
  retro_* exports: 25 (unchanged).
2026-05-14 14:02:11 +02:00
LibretroAdmin
40b77e05ec common/log: drop the console-output sink, libretro frontend owns logging
This is a libretro core. The host process is RetroArch (or another
libretro frontend) and the host handles its own log routing: when
the frontend exposes RETRO_ENVIRONMENT_GET_LOG_INTERFACE the core
calls into retro_log_callback, and when it does not, there is
nowhere meaningful for the core to write log output that the host
isn't already aware of.

The Log:: subsystem nonetheless carried a full standalone-binary
console-output sink in common/log.cpp:

  - SetConsoleOutputParams(bool, channel filter, level filter)
  - ConsoleOutputLogCallback registered/unregistered into the
    callback list when console output is toggled
  - FormatLogMessageForDisplay (ANSI color codes, timestamps,
    level character, channel/function tagging)
  - FormatLogMessageAndPrint / FormatLogMessageAndPrintW
    (templated callback wrappers that build the formatted string
    in a stack buffer or fall back to malloc when the message is
    long)
  - On Windows: a SetConsoleOutputParams branch that calls
    AttachConsole / AllocConsole, redirects stdin/stdout/stderr via
    freopen_s, enables virtual-terminal ANSI processing on the
    handles, and tears all of that back down on disable.
  - On POSIX: a write(STDERR/STDOUT_FILENO, ...) sink.
  - On Android: an empty branch (no output - the codepath was
    explicitly gated out with !defined(__ANDROID__)).

The libretro frontend wiring (libretro_host_interface.cpp's
UpdateLogging) was the only caller and toggled console output
on/off based on whether the libretro log callback came back
valid from the environment query.

Everything in the console-output codepath is removed:

  - log.cpp shrinks from 377 lines to 104. Gone: the static
    console-state globals (s_console_output_enabled, the channel
    String filter, the level filter, the Windows console HANDLEs),
    s_startTimeStamp, s_log_level_characters,
    FormatLogMessageForDisplay, FormatLogMessageAndPrint{,W},
    EnableVirtualTerminalProcessing, ConsoleOutputLogCallback,
    SetConsoleOutputParams. Also gone: the windows_headers.h,
    android/log.h, unistd.h, string.h and timer.h includes that
    only the console sink needed.
  - log.h drops the SetConsoleOutputParams declaration.
  - libretro_host_interface.cpp's UpdateLogging() collapses to
    just Log::SetFilterLevel(g_settings.log_level) - the
    if/else over s_libretro_log_callback_valid goes away because
    both branches were toggling the now-removed console sink.

What stays: the callback registration API (RegisterCallback /
UnregisterCallback / ExecuteCallbacks), the global filter level,
and Write / Writef / Writev. That is everything the libretro
host_interface needs to route log messages to the frontend, and
everything any future in-tree callback sink would need.

Build:
  Makefile.libretro platform=unix - clean.
  swanstation_libretro.so size: 8031016 -> 8026128 bytes (-4.9KB).
  retro_* exports: 25 (unchanged).
  No references to SetConsoleOutputParams, FormatLogMessage*,
  EnableVirtualTerminalProcessing, ConsoleOutputLogCallback or
  the s_console_output_* state remain in the binary.

The behaviour change is observable only when running this core in
an environment where the libretro frontend did NOT supply a log
interface AND someone was reading the core's stdout/stderr. In
that narrow case log output now silently goes nowhere instead of
hitting the frontend's terminal. Every actual libretro frontend
(RetroArch, etc.) supplies the log interface, so in practice
nothing observable changes.
2026-05-14 13:45:39 +02:00
LibretroAdmin
daa5bd1def core: rename lambda parameters that shadow outer locals in two hot files
-Wshadow caught two real shadowing issues left after the
fold-cleanup work landed:

  cpu_code_cache.cpp:891, 906 (RemoveBlockFromList)
    `for (CodeBlock::LinkInfo& li : ...)` followed by a
    `std::find_if(..., [block](const CodeBlock::LinkInfo& li) { ... })`
    lambda whose parameter `li` shadowed the outer loop variable.
    The lambda only looks at its own parameter (no capture of the
    outer li), so the shadow was harmless but trips warnings on
    -Wshadow builds. Renamed the lambda parameters to `succ` and
    `pred` respectively to match what they actually mean - the
    outer list being scanned for predecessors/successors.

  gpu_hw_opengl.cpp:1163, 1188, 1205, 1223, 1253, 1275 (CompilePrograms)
    Same pattern: a `std::optional<GL::Program> prog` followed by
    a lambda whose own `GL::Program& prog` parameter shadowed the
    outer one. Renamed all six lambda parameters to `p`.

No behaviour change - the lambdas never captured the outer name,
they just shadowed it. -Wshadow on these files is silent on the
remaining warnings (those are all in third-party headers:
dep/xbyak's EvexModifierRounding and libchdr's chd_core_file).
2026-05-14 13:45:35 +02:00
LibretroAdmin
138af597ba core/gpu_hw_vulkan: drop dead aliases in CompilePipelines
CompilePipelines opens with two aliases:

  auto& batch_vertex_shaders = m_batch_vertex_shaders;
  auto& batch_fragment_shaders = m_batch_fragment_shaders;

The comment above them notes 'matching the previous structure',
which suggests they survived a prior refactor where the references
were more useful. In the current code, batch_fragment_shaders has
no callers at all (-Wunused-variable warns on it), and
batch_vertex_shaders has exactly one use a few lines down:

  batch_vertex_shaders[textured].store(shader, ...)

Drop both aliases and inline the one remaining call site to use
m_batch_vertex_shaders directly. That mirrors how the rest of the
function (and the rest of the file) already addresses these
members, and silences the -Wunused-variable warning that fires on
debug builds.

No behaviour change.
2026-05-14 13:45:31 +02:00
LibretroAdmin
2f59939fc8 core/mdec: fix C++<20 UB on signed left shifts in DecodeRLE_New
The DC coefficient (zigzag[0]) and subsequent AC coefficient
computations in MDEC::DecodeRLE_New use signed left shifts that
can overflow into the sign bit:

  (val << 5)                       // when val is negative
  (val * qt[0]) << 4               // when val * qt[0] is negative
  ((val * scq) >> 3) << 4          // when val * scq is negative

val comes from sign-extending the low 10 bits of an MDEC RLE
stream halfword to s32; its range is [-512, 511]. qt[i] is u8
[0, 255]. scq is the product m_current_q_scale * qt[i] which
also routinely lands negative or large depending on the input
block.

Signed left shift of a negative value (or a positive value whose
shifted result would not fit in the signed type) is C++<20
undefined behaviour. The C++20 standard redefined signed left
shift in terms of unsigned 2's-complement arithmetic, making it
well-defined.

Same idiom as the BitField::GetValue() and TruncateVertexPosition
fixes that just landed: do the shift in the unsigned domain, then
cast back to s32. The arithmetic right shifts inside the existing
sign-extension chain (val computed from 'static_cast<s32>(u32 << 22) >> 22')
stay unchanged - those are arithmetic right shifts of a signed
value, which is well-defined since C++11.

Codegen and observable behaviour: zero change.

A test harness running 1159 cases covering the full val range
[-512, 511], qt values {0, 1, 127, 255} and q_scale values
{0, 1, 63} plus various scq values reports zero differences
between the old and new forms. -O2 g++ x86_64 emits byte-
identical assembly for both: the testb-jne-sall pattern for the
q_scale-zero path, and the movzbl-imull-sall-leal pattern for
the non-zero path are unchanged.

The fix removes the UB so the code stays well-defined under
future compiler changes (and across compilers - GCC happens to
make the UB resolve to the same value as C++20 modular shift,
but that's not guaranteed).
2026-05-14 13:33:33 +02:00
LibretroAdmin
f7b22b0a5a core/pgxp: fix C++<20 UB on signed left shift in TruncateVertexPosition
TruncateVertexPosition emulates the GPU hardware behaviour of
truncating vertex positions to 11-bit signed (the same range as
the BitField<u32, s32, X, 11> declarations in gpu_types.h). The
implementation uses the classic sign-extend-via-shift idiom:

  static_cast<s16>(int_part << 5) >> 5

with shift = 5 to land the field's high bit at s16's sign bit
position (16 - 11 = 5). The arithmetic right shift then replicates
the sign bit. The integer-part of a vertex coordinate routinely
sits in the negative half of the 11-bit signed range
(int_part = -1024..-1 for any vertex with X or Y below zero),
which means int_part << 5 is a signed left shift of a negative
value: undefined behaviour in C++<20, well-defined two's-complement
since C++20.

Fix: perform the left shift in the unsigned domain, then cast to
s16 for the arithmetic right shift. Same idiom as the recently-
fixed BitField::GetValue() signed branch, the mdec.cpp MDEC
coefficient sign-extension, and TruncateGPUVertexPosition in
gpu_types.h.

  static_cast<s16>(static_cast<u32>(int_part) << 5) >> 5

Observable behaviour: zero change. The fix is codegen-byte-
identical at -O2 g++ x86_64 - both forms emit:

  sall $5 ; sarw $5 ; cwtl

GCC's UB choice for the old form happens to match the C++20-
defined behaviour, so all 11 boundary-test cases (zero, edges of
the 11-bit range, just-past-edges that wrap, large positive and
negative values that exit the field) give identical floats from
both forms.

The fix removes the UB so the source stays well-defined under
future compiler changes and across compilers.
2026-05-14 13:33:28 +02:00
LibretroAdmin
9ad63f04e0 common/bitfield: fix C++<20 UB on signed BitField sign-extension
BitField<BackingDataType, DataType, BitIndex, BitCount>::GetValue()
has a code path for signed DataType that sign-extends a BitCount-wide
field to a full-width DataType by left-shifting and arithmetic-
right-shifting:

  constexpr int shift = 8 * sizeof(DataType) - BitCount;
  return (static_cast<DataType>(data >> BitIndex) << shift) >> shift;

The static_cast<DataType>(...) produces a signed value. For any
BitCount < 8*sizeof(DataType), shifting a positive signed value left
by 'shift' bits can place a '1' in the sign position, which means the
result of the shift would not fit in DataType. Per C++<20 [expr.shift]
that's undefined behaviour; C++20 redefined signed left shift in
terms of unsigned arithmetic, making it well-defined as a 2's-
complement bit pattern.

The fix is the same idiom used in mdec.cpp's MDEC coefficient
sign-extension and in TruncateGPUVertexPosition: do the left shift
in the unsigned domain, then cast to signed only for the
arithmetic right shift.

  using UnsignedT = std::make_unsigned_t<DataType>;
  return static_cast<DataType>(static_cast<UnsignedT>(data >> BitIndex) << shift) >> shift;

Three signed BitField declarations exist in the tree, all of which
exercise the buggy path whenever the field's high bit is set:

  src/core/gpu_types.h:132  BitField<u32, s32,  0, 11> x;  // GPU vertex X
  src/core/gpu_types.h:133  BitField<u32, s32, 16, 11> y;  // GPU vertex Y
  src/core/spu.h:136        BitField<u16, s16,  0, 15> fixed_volume_shr1;

Observable behaviour today: zero change.

  - GPU vertex positions: GCC -O2 emits 'sall $21 ; sarl $21' for
    both the old and new forms; the optimizer recognises the
    arithmetic-shift idiom regardless of whether the intermediate
    cast is signed or unsigned. Byte-identical assembly.

  - SPU fixed_volume_shr1: the only caller is
    'current_level = reg.fixed_volume_shr1 * 2'. The post-multiply
    by 2 happens to cancel the sign-extension stage entirely - the
    compiler reduces both forms to a single 'addl %esi, %esi'
    followed by the low-16-bit store into current_level (s16). The
    full VolumeSweep::Reset routine is bit-identical before and
    after the bitfield.h change.

But the test harness (verify_bf, attached in private notes) shows
the standalone return values diverge at the 15-bit BitField:

  data=0x4000  old=16384      new=-16384  (15-bit signed: -16384)
  data=0x7FFF  old=32767      new=-1      (15-bit signed: -1)
  data=0x4001  old=16385      new=-16383  (15-bit signed: -16383)

The OLD output is wrong - GCC's -O2 elides the UB shifts on the
s16 form entirely (the noinline test compiles old_get15 to a
single 'movl %edi, %eax ; ret', i.e. just zero-extends the input).
The fact that fixed_volume_shr1's only caller masks the bug via
a post-multiply is luck, not design. Any future caller that uses
the field's standalone value, or any compiler change that lays
out the shift differently, would surface the underlying bug.

For the 11-bit s32 cases the harness shows old=new on every input
because the s32 representation has enough headroom for the UB
shift to coincidentally produce the right bit pattern on GCC.
That's still UB on the standard, and a fix is still warranted.

Build:
  Makefile.libretro platform=unix - clean, no new warnings,
  -Wshift-overflow=2 silent across spu.cpp and gpu_commands.cpp.
  VolumeSweep::Reset assembly byte-identical to the old build.
2026-05-14 06:18:52 +02:00
LibretroAdmin
a65117100e core: drop two more redundant u32 intermediate casts post-BoolToUInt fold
After the BoolToUInt removal, two more sites surfaced where an
explicit `static_cast<u32>` widening intermediate sits in front of
a value-preserving cast to a wider type.

gpu_commands.cpp:307 (HandleRenderPolygonCommand)
  Was: static_cast<TickCount>(static_cast<u32>(s_setup_time[a][b][c]))
  s_setup_time is constexpr u16[2][2][2]; widens to s32 (TickCount)
  value-preservingly. The u32 step is a no-op leftover from the
  ZeroExtend32(u16) fold.

pad.h:99 (GetTransferTicks)
  Was: static_cast<TickCount>(static_cast<u32>(m_JOY_BAUD) * 8)
  m_JOY_BAUD is u16; `u16 * 8` integer-promotes to int (= s32),
  fits trivially (max 0x7FFF8). The u32 step adds nothing.

Codegen verified byte-identical at -O2 (single movzwl on x86-64
in both cases, with and without the cast).
2026-05-14 06:08:22 +02:00
LibretroAdmin
00c79ee722 common/types: remove unused ConvertToBool, fix BCD predicate return types
Two small types.h tidy-ups that became apparent after the recent
helper-removal commits.

1. ConvertToBool was the 'safe' counterpart to ConvertToBoolUnchecked,
   defined as static_cast<bool>(value) on its argument. With
   ConvertToBoolUnchecked gone (replaced by static_cast<bool>
   directly at the callsites), grepping shows ConvertToBool has
   zero callers anywhere in src/ or dep/. Drop the dead definition.

2. IsValidBCDDigit and IsValidPackedBCD are predicates - they
   compare an input against a constant range and return a yes/no
   answer. Both were declared as returning u8 even though their
   bodies return a bool expression (digit <= 9 and a logical &&).
   The u8 return was getting an implicit bool->u8 conversion on
   the way out. The two callers in cd_subchannel_replacement.cpp
   only ever use the result in a boolean context (!IsValidPackedBCD)
   so the wrong return type wasn't a functional bug, but it's a
   type signature error. Change both to return bool.

No behaviour change for the BCD validators (the conversion goes
the other direction now: caller still sees a bool either way).
common/types.h shrinks by another 7 lines.
2026-05-14 06:08:18 +02:00
LibretroAdmin
67051a0828 common: remove BoolToUInt8/16/32/64 helpers in favour of explicit casts
The BoolToUInt8/16/32/64 helpers in common/types.h are one-line
wrappers around `static_cast<uN>(bool)`. C++ already guarantees
that converting a bool to an unsigned integer yields exactly 0
(for false) or 1 (for true), so the helpers add nothing beyond a
shorter name - and a less obvious one, since 'BoolToUInt32(x)'
doesn't immediately read as 'cast to u32' the way the static_cast
spelling does.

Mechanical fold across 16 files:

  BoolToUInt8(x)   -> static_cast<u8>(x)
  BoolToUInt32(x)  -> static_cast<u32>(x)

(BoolToUInt16 and BoolToUInt64 had no callers in the tree.)

103 callsites rewritten: 82 BoolToUInt8 and 21 BoolToUInt32, spread
across gpu_commands.cpp, pgxp.cpp, gpu.cpp, gpu_hw_d3d11/d3d12/
vulkan/opengl.cpp, gpu_sw.cpp, gpu_hw.cpp, gpu.h, shadergen.cpp,
spu.cpp, analog_controller.cpp, negcon_rumble.cpp,
cpu_recompiler_code_generator.cpp, cpu_core.cpp. Most are array
indices (s_setup_time[BoolToUInt8(...)][...]), bit-packing in
shader-cache lookups, and arithmetic with vertex-count offsets
(words_per_vertex + BoolToUInt32(rc.texture_enable)).

After the rewrite, the four helper definitions are removed from
common/types.h.

Build verification:
  Makefile.libretro platform=unix - clean syntax-check on every
  touched .cpp that compiles on Linux. d3d11/d3d12 sites are all
  simple BoolToUInt8(v) -> static_cast<u8>(v) substitutions on
  bitfield values and verified by code review only.

No behaviour change. Codegen is identical at -O2 - both forms
compile to the same setcc/movzx sequence on x86-64.

Same shape of cleanup as the recently-landed SignExtend/Truncate
and ConvertToBoolUnchecked removals: kill a thin readability
wrapper, use the explicit static_cast spelling everywhere.
common/types.h shrinks by another 16 lines.
2026-05-14 06:08:13 +02:00
LibretroAdmin
ce457db027 core/gpu_hw_opengl: drop redundant outer static_cast in ConvertToFramebufferCoordinates
The expression was

  static_cast<s32>(static_cast<s32>(VRAM_HEIGHT) - y)

where VRAM_HEIGHT is constexpr u32 = 512 and y is s32. The inner
static_cast<s32>(VRAM_HEIGHT) is meaningful - it forces the
subtraction to s32 arithmetic (without it, u32 - s32 would promote
both operands to u32 via the usual arithmetic conversions, then
the make_tuple<s32, s32> would need a narrowing cast back). The
outer static_cast<s32> is a no-op since the subtraction already
produces s32.

Drop the outer cast. Behaviour and codegen unchanged.
2026-05-14 06:01:18 +02:00
LibretroAdmin
b12fb4b291 common: remove ConvertToBoolUnchecked, replace with static_cast<bool>
ConvertToBoolUnchecked was a thin template that did a memcpy of the
low byte of its integer argument into a bool, deliberately bypassing
the standard 'nonzero -> true' conversion. The 'Unchecked' meant: if
your value's low byte happens to be 0 but a higher byte is set (e.g.
0x100), the result is false rather than true. The bool storage is
also left with whatever bit pattern the source's low byte had, which
pre-C++17 was technically a trap representation; only C++17+ made
non-{0,1} bool storage well-defined (any nonzero -> true).

In practice every one of the 46 callsites passed a value already
guaranteed to be in {0, 1}:

 - Bit-masked-to-LSB:  x & 1, value & 0x01, (reg >> i) & u32(1)
   11 sites in cdrom.cpp, gpu.cpp (3 sites), dma.h (2), spu.h (3),
   cpu_core.cpp, cpu_recompiler_code_generator.cpp.

 - Loop variable in {0, 1}: u8 textured/dithering/interlacing/
   wrapped/interlaced/depth_24bit from 'for (u8 v = 0; v < 2; v++)'.
   35 sites across gpu_hw_d3d11.cpp, gpu_hw_d3d12.cpp,
   gpu_hw_vulkan.cpp, gpu_hw_opengl.cpp.

For every caller, the result is the same as static_cast<bool>(x):
0 maps to false, nonzero maps to true. Equivalence verified with a
test harness covering {0, 1, 2, 3, 0x100, 0xFFFFFFFF} masked by 1
and u8 values {0, 1} - all 8 cases produce identical results, and
g++ -O2 inlines both forms to the same comparison-with-zero
sequence (the template was never doing a real memcpy at runtime).

Mechanical rewrite:

  ConvertToBoolUnchecked(EXPR)  ->  static_cast<bool>(EXPR)

then the helper is removed from common/types.h. The <cstring>
include in types.h stays - 40+ files in src/ rely on it being
transitively included; removing it is a separate sweep.

The 'Unchecked' semantics were never actually used. Any value
with low_byte=0 but other bytes set, or anything that would have
hit the pre-C++17 trap representation, would have been a latent
bug at the callsite. After this change such inputs would simply
read as true, matching what the surrounding code already assumes.

Build verification:
  Makefile.libretro platform=unix: clean (post-fold), zero warnings
  -Wconversion delta on the touched files: zero new warnings
  d3d11/d3d12 sites verified by code review (Linux toolchain cannot
  build them; the changes are all simple ConvertToBoolUnchecked(v)
  -> static_cast<bool>(v) substitutions on u8 loop variables, no
  expression rewriting)
2026-05-14 06:01:14 +02:00
LibretroAdmin
717491fd98 core/gpu_sw_backend: drop redundant u8/u32 intermediate casts in rasteriser
DrawRectangle, DrawSpan, and DrawLine all contained two related patterns
that did the same thing as a single plain cast but with an extra layer:

  static_cast<u8>(static_cast<u32>(s32_y)) & 1u    -> y & 1
  static_cast<u8>(static_cast<u32>(u8_v) + u32_o)  -> static_cast<u8>(u8_v + u32_o)

For the interlace LSB check (3 sites: lines 231, 363, 686), `y` is s32,
the cast-to-u32 reinterprets bits (no-op for non-negative, two's-complement
preserving for negative), the cast-to-u8 truncates to low 8 bits, and the
`& 1u` keeps the LSB. Since the low bit of an integer is the same
regardless of which signed/unsigned width it's viewed through, the whole
ladder reduces to `y & 1`. The comparison against `active_line_lsb`
(BitField<u8,u8,1,1>::GetValue() returns u8) then promotes both sides to
int for the equality check - same as before.

For the texcoord wrap (2 sites: lines 236, 244), `origin_texcoord_y` is
u8 (from UnpackTexcoord -> std::tuple<u8,u8>) and `offset_y` is u32 (the
loop variable). The original `static_cast<u32>(origin_texcoord_y) +
offset_y` makes the u32 widening explicit; `origin_texcoord_y +
offset_y` does the same thing implicitly via the usual arithmetic
conversions (u8 integer-promotes to int, then to u32 to match the other
operand). Both end with the same `static_cast<u8>` narrow.

Equivalence verified with a small test harness covering boundary inputs
(0, 255, INT32_MIN, INT32_MAX, negative odd/even, wrap-around offsets);
all 27 cases produce identical results. -O2 g++ x86_64 emits byte-
identical assembly for both pairs:

  interlace check : andl $1, %esi ; movzbl %dil, %edi ; cmpl %edi, %esi
  texcoord wrap   : leal (%rdi,%rsi), %eax

-Wall and -Wconversion delta on the file: zero (13 -> 13 -Wconversion,
all pre-existing in unrelated lines).

Spotted as a follow-up after the helper fold; once `Truncate8` and
`ZeroExtend32` weren't hiding inside function calls, the redundancy
of the explicit double-cast chain became visible.
2026-05-14 06:01:10 +02:00
LibretroAdmin
5d87e9bb0a common: drop redundant intermediate casts surfaced by SignExtend/Truncate fold
After the SignExtend/ZeroExtend/Truncate helpers were inlined as explicit
static_cast chains, a handful of sites ended up with a redundant
`static_cast<uN>` intermediate between the source and a `static_cast<sN>`
(or s64) outer cast. The pattern is:

    static_cast<sN>(static_cast<uM>(EXPR))

where EXPR's natural type already fits in sN. In those cases the uM step
is pure noise - it widens to an unsigned type that's then immediately
reinterpreted as signed of equal or greater width, while EXPR was already
a sub-width unsigned type that converts to sN value-preservingly through
either integer promotion or a direct cast.

Sites collapsed:

  gpu_sw_backend.h:61-63 (SetRGB24Dithered)
    `static_cast<s32>(static_cast<u32>(rN)) + offset` -> `static_cast<s32>(rN) + offset`
    where rN is u8. u8 widens to s32 value-preservingly.

  mdec.cpp:583, 604 (DecodeRLE_Old)
    `static_cast<s32>(static_cast<u32>(qt[i]))` -> `static_cast<s32>(qt[i])`
    qt is u8*; same reasoning.

  cdrom.h:234 (ApplyVolume)
    `static_cast<s32>(static_cast<u32>(volume))` -> `static_cast<s32>(volume)`
    volume is u8.

  gte.cpp:452 (UNRDivide)
    `static_cast<s32>(static_cast<u32>(divisor))` -> `static_cast<s32>(divisor)`
    divisor is already u32; the inner u32 cast is a no-op.

  gte.cpp:663 (NCDS)
    `static_cast<s64>(static_cast<u64>(UNRDivide(...)))` -> `static_cast<s64>(UNRDivide(...))`
    UNRDivide returns u32; u32 widens to s64 value-preservingly.

  cpu_recompiler_code_generator_aarch64.cpp:1087, 1115, 1142
    (EmitLoadCPUStructField, EmitStoreCPUStructField, EmitLoadGuestRegister)
    `static_cast<s64>(static_cast<u64>(offset))` -> `static_cast<s64>(offset)`
    offset is u32 parameter; same reasoning. Three identical sites.

Codegen verification: built a small test harness that exercises each
collapsed pattern alongside its original form. -O2 g++ x86_64 emits
byte-identical assembly for every pair:

  u8 widen + s32 add:    movzbl ; leal           (both)
  self-cast u32:         movl                    (both)
  u32 -> s64 widen:      movl                    (both, mov implicitly zero-extends on x86-64)
  u8 -> s32 * s16 -> sar: movzbl ; movswl ; imull ; movl ; sarl   (both)

These are pure source-readability cleanups - no semantic change, no
warning delta. Spotted while scanning for follow-up opportunities after
the helper-removal commit landed; the patterns become more visible once
the inner step is no longer hidden behind a `ZeroExtend32` function call.
2026-05-14 05:49:38 +02:00
LibretroAdmin
e4b17615a9 common: remove SignExtend / ZeroExtend / Truncate helpers in favour of explicit casts
The src/common/types.h helpers SignExtend16/32/64, ZeroExtend16/32/64,
Truncate8/16/32, the generic SignExtend<TR,TV> and ZeroExtend<TR,TV>
templates, and SignExtendN<N,T> were thin wrappers around explicit
static_cast chains. They served a documentation role ("this cast is
intentional, not a typo") in places where the underlying intent was
"narrow this value" or "sign-extend this value", but in practice
they obscured rather than clarified - particularly when several
nested together (SignExtend32(Truncate8(x)) is just (u32)(s8)x).

Tree-wide fold:

  Truncate8(x)              -> static_cast<u8>(x)
  Truncate16(x)             -> static_cast<u16>(x)
  Truncate32(x)             -> static_cast<u32>(x)
  ZeroExtendN(u_x)          -> static_cast<uN>(u_x)
  SignExtendN(u_x)          -> static_cast<uN>(static_cast<sM>(u_x))   (M = source width)
  SignExtendN(s_x)          -> static_cast<uN>(s_x)                   (relies on int promotion)
  SignExtendN<BITS,T>(x)    -> static_cast<sN>(static_cast<uN>(x) << S) >> S   (S = N*8 - BITS)
  SignExtendK(TruncateM(x)) -> static_cast<uK>(static_cast<sM>(x))
  ZeroExtendK(TruncateM(x)) -> static_cast<uK>(static_cast<uM>(x))

Mask cleanup applied where the mask matched the truncation width:

  Truncate8(x & 0xFFu)            -> static_cast<u8>(x)
  Truncate8((x & 0xFF00u) >> 8)   -> static_cast<u8>(x >> 8)
  Truncate16(x & 0xFFFFu)         -> static_cast<u16>(x)
  Truncate16((x & 0xFFFF0000u) >> 16) -> static_cast<u16>(x >> 16)

The masks were dead-code: a static_cast to uN already keeps exactly
the low N bits.

UB fixes incidental to the fold (visible once the helpers were
unwrapped):

  - SignExtendN<NBITS,T> internally did (static_cast<signed_T>(v) << S) >> S.
    Signed left shift of a negative value is UB pre-C++20. After the
    fold the shift is done in the unsigned domain first:
      static_cast<sN>(static_cast<uN>(v) << S) >> S
    All five SignExtendN callsite expansions (gpu_commands.cpp x2,
    gpu_types.h, gte SignExtendMACResult, mdec.cpp x12) now do the
    left shift on uN. Defined behaviour on every C++ standard from
    C++98 onward. Right shift of a signed negative value remains
    implementation-defined pre-C++20; this is the same as the
    original helper and unchanged.

  - mdec.cpp:650's SignExtendN<9,s32> took an s64 expression and
    forced an implicit s64->int narrowing inside the template, which
    -Wconversion flagged. The explicit static_cast<u32>(...) now
    makes the narrow visible and the warning goes away. Bit-identical
    result.

Sites deliberately not collapsed further, with reasons:

  - spu.cpp:1347 (ADPCM pitch modulation): SignExtend32(step) where
    step is u16 deliberately produces a u32 with the s16 sign bit
    replicated, then multiplies by a u32 factor. Folding it as
    static_cast<u32>(static_cast<s16>(step)) preserves the semantics
    exactly. The naive 'static_cast<s32>(step) * factor' would not -
    it'd evaluate s32 * s32 which is signed and may overflow as UB.

  - gte.cpp:297-299 (IRGB conversion): Sign-extension here is observably
    equivalent to zero-extension because (value & 0x1F) * 0x80 is
    always <= 0xF80, bit 15 always clear. Folded as the literal
    static_cast<u32>(static_cast<s16>(static_cast<u16>(...))) rather
    than dropping the sign-extend step entirely - that would be a
    semantic claim about hardware behaviour beyond the scope of a
    helper-removal change.

  - GTE TruncateRGB, TruncateAndSetMAC, TruncateAndSetIR,
    TruncateAndSetMACAndIR (gte.cpp) and TruncateVertexPosition,
    TruncateGPUVertexPosition (pgxp.cpp, gpu_types.h): these are
    different functions, not the removed helpers. Left untouched.

bitutils.h's CountLeadingZeros / CountTrailingZeros are template
functions over T. The helper-removal leaves them inline-folding via
std::make_unsigned<T>::type, which is what ZeroExtend was doing
under the hood:

  ZeroExtend64(value) ->
  static_cast<u64>(static_cast<typename std::make_unsigned<T>::type>(value))

The remaining mechanical changes in cpu_recompiler_register_cache.h's
GetS32ConstantValue / GetS64ConstantValue and in pgxp.cpp's CPU_MULT
fold dropped redundant intermediate u-of-s-of-x casts that became
visible after the SignExtend64 expansion. Same codegen; cleaner.

Files touched: 43.
Helper definitions removed: 13 functions (~60 lines of types.h).

Build verification:
  - Makefile.libretro platform=unix: clean build, zero warnings,
    .so size 8031016 bytes (unchanged from HEAD).
  - 25 retro_* exports unchanged.
  - -Wall -Wextra on touched files: same warnings as HEAD (zero
    new warnings from the fold, all pre-existing -Wunused-parameter).
  - -Wconversion on touched files: one pre-existing warning
    eliminated (mdec.cpp:650 SignExtendN<9,s32>(s64_expr) narrowing
    is now an explicit static_cast<u32>); zero new warnings.

Codegen equivalence verified by inspection at every transformation
site:

  Truncate8(x)        = static_cast<u8>(x)   ; both emit a movzx/byte-load
  Truncate16(x)       = static_cast<u16>(x)  ; both emit a movzx/halfword-load
  ZeroExtend32(u8)    = static_cast<u32>(u8) ; both emit a movzx eax,al
  ZeroExtend64(u32)   = static_cast<u64>(u32); both emit a mov eax,reg (implicit zero-extend on x86-64)
  SignExtend32(u8)    = static_cast<u32>(static_cast<s8>(x))  ; both emit movsx eax,byte
  SignExtend32(u16)   = static_cast<u32>(static_cast<s16>(x)) ; both emit movsx eax,word
  SignExtend64(u32)   = static_cast<u64>(static_cast<s32>(x)) ; both emit movsxd rax,dword
  SignExtendN<11,s32> = static_cast<s32>(static_cast<u32>(x) << 21) >> 21
                        both emit shl ; sar, identical 2-instruction sequence
2026-05-14 05:41:46 +02:00
LibretroAdmin
75a2316ea3 core/recompiler: fix SRA/SRAV PGXP speculation cache using wrong shift direction
In CodeGenerator::Compile_Shift's switch over the funct codes, the
speculative-value cache fold for sra/srav was using a left shift
instead of an arithmetic right shift. The actual recompiled MIPS via
SarValues() always did the correct shift; the bug was confined to
PGXP CPU-mode's speculative-value cache, which mirrors register
values in u32 so PGXP can correlate vertex precision data across
dependent ops without round-tripping through the host.

The three speculation folds sit adjacent in source:

  sll : *rt_spec << *shamt_spec
  srl : *rt_spec >> *shamt_spec
  sra : static_cast<u32>(static_cast<s32>(*rt_spec)) << *shamt_spec   <-- wrong

Fairly obviously a copy-paste from the sll case that was never
corrected. Fix to use arithmetic right shift via signed intermediate:

  result_spec = static_cast<u32>(static_cast<s32>(*rt_spec) >> *shamt_spec)

Right-shift of a (possibly) negative s32 is implementation-defined
pre-C++20 and well-defined as arithmetic shift in C++20+; on every
target compiler this codebase supports (g++, clang, MSVC) the
implementation-defined choice is arithmetic shift, matching what
the MIPS SRA semantics actually need. As a side effect this also
fixes the existing C++<20 UB of '<< on a (potentially) negative
signed value' the broken line was committing.

Real impact is narrow: any PGXP-tracked value that flowed through
an SRA or SRAV lost its speculative cache correlation, so PGXP
fell back to less precise tracking for downstream uses of that
register. No crashes, no divergence from the actual recompiled
code (SarValues always emitted the correct host shift), just
degraded PGXP precision in a corner case.

Build verification:
  - Makefile.libretro platform=unix: clean build, zero warnings
  - .so size unchanged at 8031016 bytes
  - 25 retro_* exports unchanged

Spotted while folding the SignExtend/Truncate helpers - the three
shift speculation folds sit adjacent in the source and the
mismatch becomes obvious once they line up vertically.
2026-05-14 05:41:41 +02:00
LibretroAdmin
0f7757b319 common: remove dead free functions and one dead member with zero callers
Tree-wide grep audit of src/common's public surface turned up
several functions declared and defined but never called from
anywhere in the codebase (verified across all of src/, dep/, and
the full set of indirection patterns - direct calls, function-
pointer addresses, using/typedef aliases - none found). These are
legacy utility helpers from an earlier era that lost their last
caller as the codebase migrated toward std::string,
std::filesystem-style helpers in libretro-common's vfs layer, and
direct CDImage access.

Removed:

  - FileSystem::CanonicalizePath - all 4 overloads (~126 lines).
    The four overloads call each other through implicit String ->
    const char* conversions; none has an external caller. Path
    canonicalisation is handled either through libretro-common's
    vfs or std::filesystem in the few places it's needed; nothing
    in the live tree calls these.

  - FileSystem::FSize64 (~7 lines). Wraps filestream_tell +
    filestream_seek + filestream_tell to compute file size; the
    callers that need size go through ReadBinaryFile or directly
    track lengths from CDImage. No live caller.

  - FileSystem::GetPathDirectory (~10 lines). Returns the
    directory component of a path via GetLastSeperatorPosition.
    No live caller; the few places that need a path's directory
    use either std::filesystem::path::parent_path() or simple
    rfind('/').

  - StringUtil::DecodeHex (~20 lines). Decodes a hex string into
    a byte vector via the existing FromChars<u8> helper. No live
    caller; hex decoding in the codebase is done inline where
    needed.

  - ISOReader::GetFilesInDirectory (~88 lines). Walks an ISO9660
    directory sector and returns a vector of filename strings.
    No live caller - the only consumer of ISOReader is system.cpp
    for boot-time disc inspection, which uses GetPVD / Open /
    ReadFile only. The LocateFile internal helper that
    GetFilesInDirectory relied on is still used by ReadFile so
    it stays.

Total deletion: ~273 lines across 6 files (3 .cpp + 3 .h).

Verification:

  - grep -rE '\\b<name>\\s*\\(' src/ dep/ scanned for every call
    site of each function. Each name matches only in its own
    declaration, its own definition, and (where applicable)
    internal recursion - i.e. uses inside the function being
    deleted. Confirmed zero external references for all five
    public names.

  - grep -rE '&\\s*\\w*::?<name>\\b' for function-pointer
    address-taken usage: zero matches for all five.

  - grep -rE 'using.*<name>|typedef.*<name>' for alias-based
    indirection: zero matches.

  - The Reserved_* dedup, lock-free fast-path, lazy compile, and
    background worker code paths all continue to function - none
    of the removed helpers were on those code paths.

Build verification:
  - linux platform=unix: clean, zero warnings, .so size shrank
    from 8040152 to 8031024 (9128 byte reduction reflecting the
    deleted code that was actually being linked). 25 retro_*
    exports unchanged.
  - cmake configure + cmake --build --target common: clean. No
    changes to CMakeLists - the source files just have less code
    in them.
  - x86_64-w64-mingw32-g++ -fsyntax-only on gpu_hw_d3d11.cpp and
    gpu_hw_d3d12.cpp (with the existing ID3D12Debug stub): clean.
    Confirms there are no Windows-only consumers of the removed
    helpers that the Linux grep would have missed because the
    consumer file is gated behind WIN32.

Files touched:
  - src/common/file_system.cpp: CanonicalizePath x4,
    GetPathDirectory, FSize64 removed.
  - src/common/file_system.h: corresponding declarations
    removed.
  - src/common/string_util.cpp: DecodeHex removed.
  - src/common/string_util.h: corresponding declaration removed.
  - src/common/iso_reader.cpp: GetFilesInDirectory removed.
  - src/common/iso_reader.h: corresponding declaration removed.
2026-05-11 23:18:29 +02:00
LibretroAdmin
6088a446ea common/CMakeLists: list display.hlsl.h and thread_priority.h alongside their siblings
Both headers were on disk but missing from the cmake source list:

  - display.hlsl.h is the precompiled HLSL bytecode for the D3D11
    display path (a static byte array used by gpu_hw_d3d11.cpp's
    composite blit shader). It pre-dates this commit; just slipped
    through when added.

  - thread_priority.h was added in commit 7db7d25 alongside the
    background shader-compile worker priority lowering. It's
    included from the three workers (D3D11, D3D12, Vulkan) but the
    cmake list was never updated.

Neither is needed for the build to succeed. The static
libretro Makefile.libretro doesn't enumerate headers at all (it
just lists translation units and lets the compiler chase includes
itself), and cmake works the same way at the dependency level -
target_sources() with headers is advisory for IDE indexing
(clangd, Visual Studio CMake mode, Qt Creator, ...). The actual
build doesn't care.

But IDEs do care, and stale source lists eventually trip up
someone trying to navigate-to-definition or rebuild a partial
project from inside the editor. Add them.

display.hlsl.h goes in the existing WIN32 block alongside the
other d3d11/ entries it's logically grouped with. thread_priority.h
goes at the top level since it's used by all three Windows D3D and
the cross-platform Vulkan worker; it's also self-contained (no
platform guards on the include side - all the platform mux is
inside the header itself).

Build verification:
  - cmake configure + cmake --build --target common: clean.
  - linux platform=unix via Makefile.libretro: clean, zero
    warnings, .so size 8040152 unchanged (the static Makefile
    doesn't list headers; this commit is cmake-only). 25 retro_*
    exports unchanged.

Files touched:
  - src/common/CMakeLists.txt: two single-line additions.
2026-05-11 23:18:25 +02:00
LibretroAdmin
5d73da3896 gpu_hw: trigger shader recompile on runtime swanstation_GPU_ShaderPrecompile change
Reported bug: flipping the swanstation_GPU_ShaderPrecompile core
option between Lazy / Enabled / Disabled at runtime had no
immediate effect. The new mode wouldn't take effect until the
user changed some OTHER shader-affecting setting (texture filter,
resolution scale, multisampling, etc.) that triggered the existing
destroy/recompile path.

Root cause: GPU_HW::UpdateHWSettings's shaders_changed predicate
checked 11 fields (resolution_scale, multisamples, true_color,
per_sample_shading, scaled_dithering, texture_filter, uv_limits,
chroma_smoothing, downsample_mode, pgxp_depth_buffer,
disable_color_perspective) but NOT g_settings.gpu_shader_precompile_mode.
So a pure precompile-mode flip computed shaders_changed = false,
the per-backend UpdateSettings skipped the DestroyPipelines /
CompilePipelines round-trip, and:

  - Lazy -> Disabled: the background worker that was already
    spawned just kept running until it naturally finished filling
    the matrix (~30 seconds on heavy filters). The user-visible
    'Disabled' semantics didn't apply until then.

  - Disabled -> Lazy: no worker spawn happened. Each draw kept
    paying first-use compile cost on the runloop. The user got
    Disabled behaviour while the setting said Lazy.

  - {Lazy, Disabled} -> Enabled: no synchronous full precompile
    happened. The user expected 'block until done' and got
    whatever state the matrix was in.

  - Enabled -> {Lazy, Disabled}: the matrix was already fully
    populated from the Enabled-mode sync pass, so this only had
    bearing on FUTURE recompile cycles. Still wrong but the
    least-visible case.

Fix: add m_shader_precompile_mode as the cached previous value
(seeded in GPU_HW::Initialize from g_settings.gpu_shader_precompile_mode,
re-stored every UpdateHWSettings call alongside the other field
copies). Include it in the shaders_changed predicate.

After this patch a runtime flip triggers shaders_changed = true,
which calls into the per-backend UpdateSettings's normal
destroy/recompile path:

  - Lazy -> Disabled: DestroyPipelines calls StopShaderCompileThread
    which joins the worker; CompilePipelines runs in Disabled
    mode (skips the precompile matrix, doesn't spawn a worker).
    The worker is gone within at most one in-flight cell's
    compile worth of latency.

  - Disabled -> Lazy: DestroyPipelines is a no-op for the worker
    (none running); CompilePipelines runs in Lazy mode (skips
    the precompile matrix, spawns a worker that fills the matrix
    asynchronously).

  - Disabled -> Enabled: full sync precompile on the calling
    thread - the documented Enabled-mode behaviour. The frontend
    blocks for tens of seconds on cold disk cache; cached, it's
    a few seconds.

  - Enabled -> Lazy / Disabled: matrix destroyed, recompiled
    according to the new mode. Symmetric with the other cases.

  - Lazy -> Enabled or vice versa with an in-flight worker:
    DestroyPipelines joins the in-flight worker first, then
    CompilePipelines starts fresh in the new mode.

Cost is one full destroy/recompile cycle on each precompile-mode
flip - same cost path the existing 11 settings already pay. For
Lazy and Disabled this is roughly 100-300 ms of teardown plus
non-batch shader rebuild. For Enabled it's that plus the actual
sync precompile of the batch matrix, dominated by driver compile
time (10-40s cold, sub-second from disk cache). The cell-fill
work hits the disk shader cache so it's only expensive on the
first time any given (filter, scale, ...) tuple is seen.

We could have written more precise handling - 'on Lazy ->
Disabled just stop the worker, keep the populated matrix' - but
that's a more complex patch and the simple destroy/recompile path
is well-trodden, well-tested, and the user already pays this cost
for any other shader-affecting setting change. Symmetry trumps
the small redundant work in the Lazy <-> Disabled case.

Files touched:
  - src/core/gpu_hw.h: m_shader_precompile_mode member added.
  - src/core/gpu_hw.cpp: Initialize seeds it from g_settings;
    UpdateHWSettings includes it in shaders_changed predicate
    and writes the latest value back.

Build verification: linux platform=unix clean, zero warnings,
zero errors. .so size 8040152 unchanged (one u8-sized field and
one extra comparison, well within an existing structure-padding
slot). 25 retro_* exports unchanged.
2026-05-11 20:37:35 +02:00
LibretroAdmin
7db7d2527d gpu_hw_d3d11 + gpu_hw_d3d12 + gpu_hw_vulkan: lower background shader-compile worker priority
The three backends with a background worker thread for shader
precompilation (D3D11, D3D12, Vulkan) currently spawn the worker
at default priority and let it run flat-out until the matrix is
filled. On a high-core-count machine with spare cycles this is
fine - the OS scheduler just gives the worker an unused core. But
on more constrained hardware the worker competes directly with
the runloop, CPU emulator, audio mixer, and frontend render
thread, all at the same priority. The OS time-slices between
them; with a heavy texture filter and a 144-2160 cell matrix
that's tens of seconds of contention immediately after boot or
texture-filter change. Even though the lock-free fast-path
commits (3d9d624, a29d202) eliminated the mutex-contention stall
on the draw side, raw CPU pressure can still cause frame drops
and audio glitches on low-spec setups.

Adds a tiny portable helper, common/thread_priority.h, with a
single LowerCurrentThreadPriority() function that drops the
calling thread to a 'below normal' scheduling class. Wired into
all three workers' entry points - it's the first thing they do.

Platform support:

  Windows: SetThreadPriority(GetCurrentThread(),
    THREAD_PRIORITY_BELOW_NORMAL). Straightforward, per-thread,
    well-supported.

  Linux: setpriority(PRIO_PROCESS, 0, +5). On Linux/NPTL this
    targets the calling THREAD rather than the whole process - a
    long-standing Linux deviation from POSIX, documented in
    setpriority(2). Verified empirically on this machine: a
    worker that called the helper saw its nice rise 0 -> 5 while
    the main thread it forked from stayed at 0. +5 is the
    conventional 'background work' offset, far below the default
    20 RLIMIT_NICE ceiling so no privileges needed.
    pthread_setschedparam with SCHED_OTHER is deliberately NOT
    used on Linux - SCHED_OTHER only accepts priority 0 there, so
    it would be a no-op.

  macOS / *BSD: pthread_setschedparam with SCHED_OTHER, target
    priority halfway between current and sched_get_priority_min.
    Halfway rather than absolute minimum because going all the
    way to min has historically caused priority-inversion
    deadlocks when a low-priority thread holds a mutex a
    high-priority thread is waiting on. BELOW_NORMAL-ish, not
    idle. Per-thread by virtue of pthread_setschedparam targeting
    pthread_self().

  Other Unices: same path as macOS/BSDs. Reasonable best-effort
    default; failure (return false) keeps the worker at default
    priority - no incorrect behaviour.

We deliberately avoid the POSIX-portable setpriority() with
PRIO_PROCESS on non-Linux platforms because POSIX defines it as
a per-process attribute, which would lower the priority of the
runloop and audio threads too - the exact opposite of what we
want.

All variants return bool. Failure is silent - the worker just
keeps running at whatever priority the platform gave it. The
helper has no side effects beyond the priority change itself.

OpenGL backend is intentionally unchanged: it has no background
worker thread (the libretro hardware-renderer protocol exposes
a single GL context bound to the runloop, so 'Lazy' mode degrades
to 'Disabled' per commit 5c9cf3e). Lowering the runloop's
priority would obviously be bad.

Build verification:
  - linux platform=unix: clean, zero warnings, .so 8040152
    (+48 bytes for the setpriority PLT call and the inline
    helper body in the Vulkan worker). 25 retro_* exports
    unchanged.
  - x86_64-w64-mingw32-g++ -fsyntax-only on gpu_hw_d3d11.cpp,
    gpu_hw_d3d12.cpp (with the existing ID3D12Debug stub
    workaround), and gpu_hw_vulkan.cpp: all clean. The
    WIN32_LEAN_AND_MEAN define is guarded with ifndef to avoid
    redefinition against windows_headers.h which defines it as 1.
  - Runtime smoke test on Linux: spawned a worker that called
    LowerCurrentThreadPriority(), confirmed worker nice 0 -> 5
    while main thread nice stayed at 0. Per-thread granularity
    validated.

Files added/touched:
  - src/common/thread_priority.h: new header, single inline
    function. Self-contained, no other dependencies.
  - src/core/gpu_hw_vulkan.cpp: include + call at top of
    ShaderCompileThreadEntryPoint.
  - src/core/gpu_hw_d3d11.cpp: include + call at top of
    ShaderCompileThreadEntryPoint.
  - src/core/gpu_hw_d3d12.cpp: include + call at top of
    ShaderCompileThreadEntryPoint.
2026-05-11 20:09:04 +02:00
LibretroAdmin
5c9cf3ea9f gpu_hw_opengl: route batch programs through the same three-mode precompile machinery as D3D11/D3D12/Vulkan
This is the final backend in the swanstation_GPU_ShaderPrecompile
rollout. OpenGL is structurally different from the other three:
the libretro hardware-renderer protocol gives the core a single
GL context bound to the runloop thread, with no way to spin up a
worker thread that shares the context (no second context, no
glShareLists hand-off path). So OpenGL's 'Lazy' mode degrades to
the same shape as 'Disabled' - compile each batch program on the
runloop the first time the game dispatches a draw using it, then
cache it. No worker thread, no mutex, no atomic; everything runs
on one thread.

Adds GetBatchProgram(render_mode, texture_mode, dithering,
interlacing) as the single fault-in path, mirroring the
GetBatchPixelShader / GetBatchPipeline helpers on the other
backends. The matrix is the existing m_render_programs (array of
GL::Program, move-only); slots start as default-constructed
(m_program_id = 0) and GetBatchProgram fills them lazily.

The Reserved_*Direct16Bit dedup is handled differently from the
other three backends - GL::Program is move-only and owns its
GLuint via glDeleteProgram in its destructor, so we can't share
a single handle between two array slots without a double-delete
hazard. Instead, the helper feeds the canonical (lookup_mode)
fragment-shader source string into GetProgram for both slots.
The disk-backed program cache hits on the second call and
reloads the linked binary instead of recompiling, so the
duplicate is cheap (one glProgramBinary call rather than a full
GLSL compile + link).

Mode behaviour:
  - Enabled: synchronous walk of the matrix at CompilePrograms
    time, calling GetBatchProgram on each cell.
  - Lazy / Disabled: matrix stays default-constructed at
    CompilePrograms time; each slot is filled by DrawBatchVertices
    -> GetBatchProgram on first use of that combination.

Two small infrastructure additions to support the lazy path:

  - GL::Program::IsValid() accessor ('return m_program_id != 0').
    GetBatchProgram uses it to distinguish a never-touched slot
    from a compiled one. glUseProgram(0) un-binds; calling
    prog->Bind() on a slot with id 0 would silently un-bind the
    previous program and break rendering, so the explicit
    validity check is required.
  - GL::ShaderCache::IsOpen() accessor, mirroring D3D11 / D3D12
    parity. The shader cache becomes a member (m_shader_cache)
    so the lazy helper can reach it at draw time on
    UpdateSettings round-trips; without IsOpen the second Open()
    call would re-read the index and double-count entries.

GPU_HW_ShaderGen becomes a member (m_shadergen, unique_ptr since
the class is non-default-constructible) so GetBatchProgram can
generate batch shader source at draw time.
use_binding_layout is captured into m_use_binding_layout because
GetBatchProgram's link-callback needs it.

CompilePrograms now explicitly resets the m_render_programs
matrix at function entry. Without that, an UpdateSettings round-
trip (which calls CompilePrograms with new texture_filter /
scale / etc. without an explicit DestroyPrograms step) would
leave the previous programs in place; the lazy fault-in path's
IsValid() short-circuit would return them as if they were fresh,
and the game would render through programs built for the old
settings. The synchronous 'Enabled' precompile loop has the same
short-circuit so it needs the same guarantee. The reset is a
default-assign loop which invokes GL::Program's move-assign
operator, which calls Destroy() (i.e. glDeleteProgram) on each
slot before resetting to id = 0.

DrawBatchVertices routes its m_render_programs lookup through
GetBatchProgram so all three modes share the same fault-in path.

The OpenGL backend has historically had the longest cold-compile
stall in some configurations (long GLSL -> driver compile
pipeline on some Intel / Mesa stacks, no async API in core
OpenGL until ARB_parallel_shader_compile which not all drivers
implement). With 'Lazy' as the default mode, that stall moves
from CompilePrograms-on-init / CompilePrograms-on-settings-change
to a stutter on the first draw that touches each combination -
one per cell, capped at ~144 cells total over the session, often
only a handful in practice for most games. The trade-off is
preferable because it makes the UI feel responsive (RetroArch
keeps drawing frames while gameplay progresses) rather than
froze for the whole compile.

This commit completes the four-backend rollout. All of D3D11,
D3D12, Vulkan, and OpenGL now honour
swanstation_GPU_ShaderPrecompile = Lazy / Enabled / Disabled.

Build verification: linux platform=unix (which DOES compile
gpu_hw_opengl.cpp, unlike the D3D11/D3D12 cases): zero warnings,
zero errors. .so size 8040104 (+4240 vs commit a29d202's
8035864). The growth is the GetBatchProgram body, the matrix-
reset loop at CompilePrograms entry, and the persistent member
storage for the shader cache and shadergen. 25 retro_* exports
unchanged.

Files touched:
  - src/common/gl/program.h: IsValid() accessor.
  - src/common/gl/shader_cache.h: IsOpen() accessor.
  - src/core/gpu_hw_opengl.h: includes, m_shader_cache,
    m_shadergen, m_use_binding_layout members, GetBatchProgram
    declaration.
  - src/core/gpu_hw_opengl.cpp: CompilePrograms resets the matrix
    at entry, uses persistent member shader_cache / shadergen,
    three-way precompile branch; GetBatchProgram helper added;
    DrawBatchVertices routes through the helper.
2026-05-11 19:24:58 +02:00
Lib
a29d202ce3 gpu_hw_d3d11 + gpu_hw_d3d12: lock-free fast-path lookup in lazy shader / PSO helpers
User confirmed the equivalent Vulkan patch (commit 3d9d624)
resolves the perceived freeze after a texture-filter change in
Lazy mode. The D3D11 and D3D12 backends ship the same bug because
they use the same single-mutex pattern: every GetBatchPixelShader
/ GetBatchPipeline call - including the steady-state lookup of an
already-filled slot - takes m_batch_shader_mutex, which the
background precompile worker holds for the duration of each cold
HLSL compile / PSO build (typically 50-200 ms with heavier
texture filters). On any frame with even one DrawBatchVertices
call needing a slot the worker happens to hold the mutex for,
the runloop stalls behind the worker for the full cell.

Apply the same fix here: a parallel atomic-raw-pointer array
alongside each ComPtr-owned matrix, and a double-checked-locking
pattern in the helpers.

For D3D11:
  - m_batch_pixel_shader_fastpath is added next to
    m_batch_pixel_shaders. The ComPtr array continues to own the
    COM reference; the atomic array exists for lock-free fast-path
    lookup. Both are written under m_batch_shader_mutex in the
    slow path. The Reserved_*Direct16Bit dedup is unchanged
    structurally: a single shader is referenced by two ComPtr
    slots and two atomic fast-path slots.
  - GetBatchPixelShader's body is split. The fast path is a
    single atomic acquire-load that returns immediately if the
    slot is non-null. The slow path takes the mutex, re-checks
    the atomic, compiles, populates the canonical ComPtr,
    propagates to the dup ComPtr if applicable, then publishes
    the raw pointer back to fast_slot via memory_order_release.
  - DestroyShaders clears the atomic fast-path array BEFORE
    dropping the ComPtr ownership so a hypothetical concurrent
    reader can never see a raw pointer to a just-freed object.
    In practice DestroyShaders runs on the runloop thread with
    the worker already stopped, so the ordering is purely
    defensive; the explicit relaxed-store is there to document
    intent rather than to handle current callers.

For D3D12:
  - The same pattern is applied at two layers, mirroring the
    structure already in commit d7938d2 (which made the PSO
    matrix lazy on top of the fragment-shader-blob matrix that
    feeds it).
  - m_batch_pipelines_fastpath sits next to m_batch_pipelines.
  - m_batch_fragment_shader_blobs_fastpath sits next to
    m_batch_fragment_shader_blobs.
  - GetBatchFragmentShader gains its own atomic fast path and
    its own mutex acquisition. GetBatchPipeline's slow path
    calls GetBatchFragmentShader WITHOUT holding its own
    m_batch_shader_mutex (the helper takes the same lock
    internally, and std::mutex isn't recursive). This is the
    same restructure the Vulkan commit had to apply.
  - The COM fast-path return path attaches the raw pointer into
    a ComPtr and explicitly AddRefs. This is the standard pattern
    for handing out a raw-pointer-snapshot into ComPtr ownership;
    the matrix ComPtr keeps the underlying object alive for the
    lifetime of the GPU backend, so the AddRef just pays the cost
    of an atomic increment - a few nanoseconds versus the
    unbounded wait on a contended mutex.
  - DestroyPipelines clears both fast-path arrays before
    dropping the ComPtr ownership, using DimensionalArray's
    enumerate with a lambda since Vulkan::Util::SafeDestroy* is
    Vulkan-specific (the lambda is the natural form here too).

Concurrency model: validated by the same TSAN harness used for
the Vulkan fix - 4-thread random-access workload against a
1680-cell matrix with full dedup, plus repeated destroy/recreate
cycles. Results: exactly 1680 PSO compiles and 112 fragment
shader compiles (no double-compilation under contention), zero
data races reported by TSAN, no deadlocks, all 5 destroy/recreate
cycles pass clean. The D3D11/D3D12 fast path additionally does a
COM AddRef on each lookup, which is a single LOCK INC on x86-64
- well-defined and lock-free.

Build verification:
  - linux platform=unix: zero warnings, zero errors. .so size
    8035864 unchanged (D3D11/D3D12 are Windows-only and don't
    enter the Linux binary).
  - gpu_hw_d3d11.cpp -fsyntax-only with x86_64-w64-mingw32-g++:
    clean.
  - gpu_hw_d3d12.cpp -fsyntax-only with the same toolchain +
    the pre-existing ID3D12Debug stub workaround: clean.

Files touched:
  - src/core/gpu_hw_d3d11.h: m_batch_pixel_shader_fastpath array
    added, mutex / helper docstrings updated.
  - src/core/gpu_hw_d3d11.cpp: GetBatchPixelShader restructured
    with atomic acquire-load fast path, mutex-protected slow
    path, double-check on lock acquisition, dup-slot raw-pointer
    publish. DestroyShaders clears fast-path slots before
    ComPtr ownership.
  - src/core/gpu_hw_d3d12.h: m_batch_pipelines_fastpath and
    m_batch_fragment_shader_blobs_fastpath arrays added, mutex /
    member docstrings updated.
  - src/core/gpu_hw_d3d12.cpp: GetBatchFragmentShader gains its
    own atomic fast path and mutex acquisition. GetBatchPipeline
    restructured with atomic acquire-load fast path; its slow
    path calls GetBatchFragmentShader without holding the mutex
    to avoid the std::mutex re-entry deadlock. Both helpers
    publish raw pointers via memory_order_release for both the
    canonical and Reserved_* dup slots. DestroyPipelines clears
    both fast-path arrays before dropping the ComPtr ownership.
2026-05-11 18:58:55 +02:00
Lib
3d9d624ad0 gpu_hw_vulkan: lock-free fast-path lookup in lazy shader / PSO helpers
User-reported regression after commit 9d2997a: in Lazy mode, the
runloop is still effectively frozen for many seconds after a
texture-filter change. The root cause is mutex contention between
the background precompile worker and the main thread's
DrawBatchVertices path, not the precompile work itself - which
is doing exactly what it should.

The shipped Vulkan code took m_batch_shader_mutex on every
GetBatchPipeline / GetBatchFragmentShader call, including the
fast-path (slot already filled). With a 2160-entry PSO matrix and
~50-200 ms per cold vkCreateGraphicsPipelines call on heavy
filters, the precompile worker holds m_batch_shader_mutex for the
duration of every cell's compile. Every concurrent main-thread
draw blocks behind the in-flight compile, so the frontend gets no
frames returned for as long as the worker is making progress.
With heavy filters at full resolution, that's the better part of a
minute - perceived as a freeze, undoing the entire point of
'Lazy' mode.

Fix is the standard atomic-fast-path / locked-slow-path pattern.
m_batch_pipelines, m_batch_fragment_shaders and
m_batch_vertex_shaders flip from plain VkPipeline / VkShaderModule
to std::atomic<VkPipeline> / std::atomic<VkShaderModule>:

  GetBatchFragmentShader / GetBatchPipeline first do a lock-free
  atomic acquire-load on the requested slot. If the slot is
  non-null (i.e. the worker has already published it, or an
  earlier main-thread fault-in did) the helper returns it
  immediately with no kernel calls and no serialisation against
  the worker. This is what DrawBatchVertices hits in steady
  state, so once the matrix is mostly populated the draw path
  runs at full speed regardless of background compile activity.

  Only the slow path (slot still null after the atomic load)
  takes m_batch_shader_mutex - to serialise the underlying
  g_vulkan_shader_cache mutations and the VkPipelineCache passed
  to vkCreateGraphicsPipelines (both of which the spec / the cache
  implementation require external synchronisation for). Under the
  lock we double-check the slot in case another thread already
  filled it while we were waiting; if it's still null we compile,
  publish the result via memory_order_release, return.

GetBatchPipeline's slow path now calls GetBatchFragmentShader
WITHOUT holding m_batch_shader_mutex, because the helper takes the
same lock internally and std::mutex isn't recursive. The call is
also semantically independent (the fragment-shader fetch doesn't
need the same atomic-instant snapshot of the matrix that the PSO
compile does) so the ordering is safe.

DestroyPipelines's enumerate sweep can no longer use
Vulkan::Util::SafeDestroyPipeline / SafeDestroyShaderModule
directly because those expect a VkPipeline& / VkShaderModule&,
not std::atomic<>. Replaced with inline lambdas that load the
slot relaxed (the worker is guaranteed stopped by this point via
StopShaderCompileThread), call vkDestroy*, and clear the slot.

Concurrency model validated against a standalone TSAN harness
modelling the exact same pattern: 4-thread random-access workload
against a 1680-cell matrix with full dedup, plus repeated
destroy/recreate cycles. Results: exactly 1680 PSO compiles and
112 fragment-shader compiles (no double-compilation), no data
races flagged by TSAN, no deadlocks, all 5 destroy/recreate cycles
pass clean.

Note on what this does NOT fix: a draw that lands on a still-empty
slot will still serialise behind one in-flight worker compile
(~50-200 ms) before getting the mutex and compiling its own
fault-in. That's the rare cold-cache stall and it's bounded; the
common case once the worker has filled the hot subset of the
matrix is the lock-free fast path. If the per-cell stall in the
cold case still ends up user-visible, the next step is a per-
thread VkPipelineCache merged into the global cache after each
compile so the worker and the main thread can call
vkCreateGraphicsPipelines truly in parallel.

Builds clean with zero warnings on linux platform=unix. .so size
8035864 unchanged (atomic operations on pointer-sized types
compile to plain MOVs on x86-64 - no instruction-count cost on
the fast path). 25 retro_* exports unchanged.

Files touched:
  - src/core/gpu_hw_vulkan.h: m_batch_pipelines /
    m_batch_fragment_shaders / m_batch_vertex_shaders flipped to
    std::atomic<>, mutex comment updated to reflect 'slow path
    only' role
  - src/core/gpu_hw_vulkan.cpp: GetBatchFragmentShader and
    GetBatchPipeline restructured with the double-checked-locking
    pattern, vertex shader fill uses explicit atomic store,
    DestroyPipelines uses atomic-aware lambdas in place of the
    SafeDestroy* enumerate callbacks
2026-05-11 18:41:14 +02:00
Lib
9d2997a601 gpu_hw_vulkan: route batch fragment shaders + PSOs through the same three-mode precompile machinery as D3D11/D3D12
This is the Vulkan follow-up to commits f188bb0 (D3D11) and
d7938d2 (D3D12), applying the same 'Disabled / Enabled / Lazy'
precompile core option to the Vulkan backend. Vulkan has the
largest PSO matrix of all four hardware backends:
3 x 4 x 5 x 9 x 2 x 2 = 2160 entries (versus D3D12's 1440 and
D3D11's effectively-1 ID3D11PixelShader matrix of 144 entries),
because Vulkan uses three depth-compare values
(VK_COMPARE_OP_ALWAYS / GREATER_OR_EQUAL / LESS_OR_EQUAL) where
D3D12 only uses two. Each vkCreateGraphicsPipelines call is
typically 5-50 ms cold, putting the Enabled-mode synchronous
precompile at 30-90 seconds with heavier texture filters - the
longest stall of any backend by a comfortable margin.

Vulkan thread-safety model:
  - vkCreateGraphicsPipelines: per the spec, when sharing a
    VkPipelineCache across threads it must be externally
    synchronised. The single m_batch_shader_mutex covers that.
  - g_vulkan_shader_cache singleton: its internal unordered_map
    indices aren't thread-safe on insert. Same mutex covers it.
  - vkCreateShaderModule: thread-safe per spec; serialised here
    incidentally because it's called from under the lock.

Two structural differences from the D3D11 / D3D12 commits:

1. Vulkan can't share refcounted resource wrappers between
   dispatch matrix slots, because VkShaderModule and VkPipeline
   are raw handles destroyed via Vulkan::Util::SafeDestroyShaderModule
   and SafeDestroyPipeline. Two slots holding the same handle
   would double-call vkDestroy*, which was the reason commit
   8e7f7a3 (the Reserved_*Direct16Bit dedup) explicitly left
   Vulkan's PSO matrix alone. This commit resolves that by moving
   the Reserved_*Direct16Bit dedup to the *helper entry*: texture
   modes 3 and 7 are remapped to 2 and 6 before the array index is
   computed, so the dup slots remain VK_NULL_HANDLE for the
   lifetime of the GPU backend. SafeDestroy* gracefully no-ops on
   VK_NULL_HANDLE, so DestroyPipelines doesn't trip on them. The
   net effect is the same as the D3D11/D3D12 ComPtr-copy approach
   (~22% fewer real PSO compiles, ~480 of the 2160 entries) but
   without the lifetime hazard.

2. The Vulkan shader cache is already a global singleton
   (g_vulkan_shader_cache), opened once via ShaderCache::Create at
   backend bring-up and torn down at shutdown. There's no
   re-open-on-UpdateSettings problem to guard against (which is
   what motivated the new ShaderCache::IsOpen() accessor on the
   D3D11 / D3D12 caches), so no equivalent change is needed in
   common/vulkan/shader_cache.h.

Otherwise the structure is identical to the D3D12 commit:

  - GetBatchFragmentShader(render, texture, dithering, interlacing)
    returns the VkShaderModule for one cell of the fragment-shader
    matrix, faulting in via g_vulkan_shader_cache->GetFragmentShader
    on miss. Caller-locked (the only callers, GetBatchPipeline and
    the Enabled-mode precompile loop, hold the mutex / are
    single-threaded respectively).

  - GetBatchPipeline(depth, render, texture, transparency,
    dithering, interlacing) returns the VkPipeline for one cell of
    the 6-D PSO matrix. Calls GetBatchFragmentShader for the bound
    shader, builds a fresh Vulkan::GraphicsPipelineBuilder for the
    cell, calls gpbuilder.Create which goes through the shared
    VkPipelineCache. Internal mutex lock.

  - DrawBatchVertices routes its m_batch_pipelines lookup through
    GetBatchPipeline so all three modes share the same fault-in
    path.

  - The background-thread worker (Lazy mode) walks the full PSO
    matrix and calls GetBatchPipeline on each cell. Same
    double-checked-locking pattern as D3D11 / D3D12: main thread
    races ahead, worker observes filled slots under the lock and
    moves on. Quit flag checked between cells so DestroyPipelines
    can stop the worker within at most one PSO compile of latency.

Persistence changes:

  - GPU_HW_ShaderGen is now a member (m_shadergen) so
    GetBatchFragmentShader can call into it at draw time. Rebuilt
    each CompilePipelines because its baked-in settings may have
    changed.
  - m_batch_vertex_shaders and m_batch_fragment_shaders are now
    members, previously locals in CompilePipelines. They were
    leaked-on-success in the previous code path (no
    enumerate(SafeDestroyShaderModule) after the PSO loop
    completed). Now properly destroyed in DestroyPipelines.

Re-entry safety: CompilePipelines calls StopShaderCompileThread at
the top so any worker from a prior UpdateSettings round-trip is
joined before a new matrix fill begins. DestroyPipelines does the
same before clearing the matrix.

The TSAN test from the D3D11 commit (double-checked lock +
Reserved_*Direct16Bit dedup + worker vs random main-thread
fault-ins) models the exact same pattern as Vulkan; the only
difference is the dedup location (helper entry here, post-compile
ComPtr-copy there), which doesn't affect the lock structure being
tested.

Only OpenGL remains. The libretro hardware-renderer protocol
doesn't give us a shareable GL context for a worker thread, so
its Lazy mode will degrade to Disabled (compile-on-first-use on
the main thread, no background work).

Build: zero warnings, zero errors on linux platform=unix. .so size
8035864 (+5288 vs commit d7938d2's 8030576) - Vulkan is unlike
D3D11/D3D12 in that gpu_hw_vulkan.cpp does compile on Linux, so
this number reflects the real binary growth from the new helpers
and threading machinery. 25 retro_* exports unchanged.

Files touched:
  - src/core/gpu_hw_vulkan.h: includes (atomic, mutex, thread,
    shadergen), m_batch_shader_mutex, m_shadergen,
    m_shader_compile_thread, m_shader_compile_thread_quit,
    persistent m_batch_vertex_shaders / m_batch_fragment_shaders
    arrays, declarations for GetBatchFragmentShader /
    GetBatchPipeline / ShaderCompileThreadEntryPoint /
    StopShaderCompileThread
  - src/core/gpu_hw_vulkan.cpp: persistent shadergen, three-way
    CompilePipelines branch, helpers, worker entry point,
    DestroyPipelines joins worker and adds SafeDestroyShaderModule
    sweeps for the now-persistent shader arrays, DrawBatchVertices
    routes through the helper
2026-05-11 18:17:41 +02:00
Lib
d7938d2099 gpu_hw_d3d12: route batch fragment shaders + PSOs through the same three-mode precompile machinery as D3D11
This is the D3D12 follow-up to commit f188bb0, applying the same
'Disabled / Enabled / Lazy' precompile core option to the
D3D12 backend. The cost of cold-cache shader-and-pipeline
compilation on D3D12 is larger than on D3D11 because the matrix is
larger: the fragment-shader array has the same 4 x 9 x 2 x 2 =
144 slots, but the PSO matrix is 2 x 4 x 5 x 9 x 2 x 2 = 1440 -
ten times bigger. Each PSO build calls
ID3D12Device::CreateGraphicsPipelineState, which on a cold pipeline
cache typically runs 5-50 ms; the wall-clock for a full Enabled-
mode precompile lands in the 20-60-second range with the heavier
texture filters. ID3D12Device is documented as free-threaded for
this call, so the lazy / background-worker path is safe.

Same plumbing as D3D11, generalised by adding a second dedup
layer:

  - GetBatchFragmentShader(render, texture, dithering, interlacing)
    returns the ID3DBlob containing compiled HLSL bytecode for
    one cell of the fragment-shader array, faulting in via
    m_shader_cache.GetPixelShader on a cache miss and routing
    Reserved_Direct16Bit (3) -> Direct16Bit (2) and
    Reserved_RawDirect16Bit (7) -> RawDirect16Bit (6). The
    matrix is stored in m_batch_fragment_shader_blobs which is
    now a member - previously it was a local in CompilePipelines.

  - GetBatchPipeline(depth_test, render, texture, transparency,
    dithering, interlacing) returns the ID3D12PipelineState for a
    cell of the full 6-D PSO matrix. It calls
    GetBatchFragmentShader for the bound shader, applies the
    same Reserved_* dedup at the PSO level (the resulting PSO is
    identical because the only texture_mode-dependent input to
    the pipeline desc is the bound fragment shader, which is
    itself dedup'd), builds a fresh GraphicsPipelineBuilder for
    the cell, and hands the descriptor to
    m_shader_cache.GetPipelineState (which hits the on-disk PSO
    cache when warm).

  - DrawBatchVertices routes its m_batch_pipelines lookup through
    GetBatchPipeline so all three precompile modes use the same
    fault-in path; the difference is purely whether anyone called
    GetBatchPipeline before the draw did.

  - The background-thread worker (Lazy mode) walks the full PSO
    matrix in the same nested-loop order CompilePipelines uses
    for the Enabled mode, calling GetBatchPipeline on each cell.
    The double-checked-locking pattern in the helpers means the
    main thread can race ahead and pre-fill any slot it needs at
    draw time; the worker just observes the filled slot and moves
    on. The quit flag is checked between cells so DestroyPipelines
    can bring the worker down within at most one PSO-compile
    worth of latency.

Lifetime changes match the D3D11 commit:
  - D3D12::ShaderCache and GPU_HW_ShaderGen now live as long as
    the GPU backend (m_shader_cache and m_shadergen members)
  - m_batch_vertex_shader_blobs and m_batch_fragment_shader_blobs
    persist past CompilePipelines so the lazy PSO builder can
    reach them at draw time
  - On UpdateSettings round-trips through DestroyPipelines/
    CompilePipelines the shader cache instance persists (Open is
    guarded by a new D3D12::ShaderCache::IsOpen() accessor) so the
    in-memory index isn't re-read from disk each time
  - The shadergen is rebuilt each CompilePipelines because its
    baked-in settings may have changed

Re-entry safety: CompilePipelines calls StopShaderCompileThread
at the top so any worker from a prior UpdateSettings round-trip
is joined before a new matrix fill begins. DestroyPipelines does
the same before clearing the matrix.

Concurrency model is the same as the D3D11 commit: one
m_batch_shader_mutex serialising both the D3D12::ShaderCache
mutation (its m_shader_index / m_pipeline_index unordered_maps
aren't thread-safe on insert) and the m_batch_pipelines /
m_batch_fragment_shader_blobs matrix writes. Fast path is one
uncontended mutex lock per DrawBatchVertices call. The TSAN test
from the D3D11 commit (double-checked lock + Reserved dedup + worker
vs random main-thread fault-ins) covers the exact same pattern, so
no new test machinery is needed.

The other two backends still take the historical
Enabled-equivalent path regardless of the user's choice (commit 4
will do OpenGL, commit 5 Vulkan). OpenGL is the trickiest -
the GL context isn't shareable across threads under the libretro
hardware-renderer protocol, so its Lazy mode will degrade to
Disabled (compile-on-first-use on the main thread, no background
work).

Build verification:
  - Linux platform=unix: gpu_hw_d3d12.cpp is guarded with
    ifeq IS_WINDOWS=1 in Makefile.libretro so it isn't compiled
    here. Build is clean (zero warnings, zero errors), .so size
    8030576 unchanged from commit f188bb0.
  - gpu_hw_d3d12.cpp + common/d3d12/shader_cache.cpp both
    -fsyntax-only check clean with x86_64-w64-mingw32-g++; the
    only mingw header gap is the pre-existing ID3D12Debug
    typedef which is not available outside the Windows SDK and
    is unrelated to this change.
  - gpu_hw_d3d11.cpp still cross-compiles clean to verify the
    helper rename / structure introduced for D3D11 still works
    alongside the new D3D12 shape.

Files touched:
  - src/common/d3d12/shader_cache.h: IsOpen() accessor
  - src/core/gpu_hw_d3d12.{h,cpp}: persistent shader cache and
    shadergen members, persistent vertex/fragment shader blob
    arrays, GetBatchFragmentShader, GetBatchPipeline, worker
    thread machinery, three-way CompilePipelines branch,
    DrawBatchVertices routes through the helper, DestroyPipelines
    joins the worker and drops the blob arrays
2026-05-11 18:01:40 +02:00
Lib
f188bb0ee2 gpu_hw_d3d11: introduce three-mode shader precompile core option
Switching the texture filter from Nearest to JINC2 / xBR / Bilinear
in the D3D11 backend currently freezes RetroArch for multiple
seconds: GPU_HW_D3D11::UpdateSettings -> DestroyShaders ->
CompileShaders rebuilds the entire batch fragment shader matrix
(4 render modes x 9 texture modes x 2 dithering x 2 interlacing =
144 permutations, 112 of them unique) synchronously on the runloop
thread. With high-optimisation HLSL compiles at 50-200 ms per
shader the total can run 10-20 seconds; the previously-shipped
RETRO_MESSAGE_TYPE_PROGRESS notification is unreadable against
the RetroArch menu UI during the stall, so users perceive a hang.

This adds a 'swanstation_GPU_ShaderPrecompile' core option with
three values, defaulting to 'Lazy', and threads its behaviour
through the D3D11 backend (other backends follow in subsequent
commits):

  - Disabled: CompileShaders skips the batch fragment shader matrix
    entirely. Each combination compiles on the main thread the
    first time the game dispatches a draw using it, then is
    cached. Lowest startup latency; trades the single multi-second
    stall for a small number of first-use hitches scattered
    through early gameplay. Useful on low-end hardware and for
    users who don't intend to use the heavier filters.
  - Enabled: the historical behaviour. CompileShaders walks the
    full matrix synchronously at GPU init. RetroArch is blocked
    the entire time. After that, no per-draw hitches. Useful for
    benchmarking and for users who want a single up-front cost.
  - Lazy (default): CompileShaders spawns a background thread
    that walks the matrix and fills it slot-by-slot. The main
    thread starts gameplay immediately. If the game asks for a
    combo the worker hasn't reached yet, the main thread compiles
    it itself (same hitch as Disabled for that one combo);
    otherwise the slot is already populated and the draw proceeds
    at full speed. After the worker finishes, behaviour is
    identical to Enabled.

A new GetBatchPixelShader(render_mode, texture_mode, dithering,
interlacing) helper centralises the lazy-compile path. It:

  - Applies the Reserved_Direct16Bit (3) -> Direct16Bit (2) and
    Reserved_RawDirect16Bit (7) -> RawDirect16Bit (6) dedup
    discovered in commit 8e7f7a3, by routing the lookup through a
    canonical slot and ComPtr-copying the result into the
    reserved-variant slot the first time it's accessed.
  - Takes m_batch_shader_mutex around both the cache mutation
    (D3D11::ShaderCache::m_index is an unordered_map and is not
    thread-safe on insert) and the m_batch_pixel_shaders array
    write. The fast path is one uncontended mutex lock per
    DrawBatchVertices call; on a modern std::mutex impl that's
    roughly 20 ns of overhead.
  - Returns a non-owning ID3D11PixelShader* (consumer side is
    free-threaded, so PSSetShader from the runloop is safe even
    while the worker thread is still publishing future entries).

DrawBatchVertices routes its m_batch_pixel_shaders lookup through
GetBatchPixelShader so all three precompile modes use the same
fault-in path; the difference is purely whether anyone called
GetBatchPixelShader before the draw did.

D3D11::ShaderCache and GPU_HW_ShaderGen lifetimes change to match
the GPU backend's lifetime instead of being locals in
CompileShaders. The shader cache now lives in m_shader_cache; the
shader generator lives in m_shadergen (a unique_ptr because the
class is non-default-constructible). On UpdateSettings round-trips
through DestroyShaders/CompileShaders, the shader cache instance
persists (Open is guarded by a new D3D11::ShaderCache::IsOpen()
accessor), so the in-memory cache index isn't re-read from disk
each time. The shadergen is rebuilt because its baked-in settings
may have changed.

The background-thread worker walks the matrix in
(render, texture, dithering, interlacing) order, calling
GetBatchPixelShader on each slot. The double-checked-locking
pattern means the main thread can race ahead and pre-fill any
slot it needs at draw time; the worker just observes the filled
slot under the lock and skips its own compile.

DestroyShaders signals m_shader_compile_thread_quit before
joining the worker so teardown latency is bounded by one
in-flight shader compile (up to ~200 ms in pathological cases).
The worker checks the flag between every cell. Re-entry safety:
CompileShaders calls StopShaderCompileThread at the top so any
worker from a prior UpdateSettings round-trip is joined before a
new matrix fill begins.

A standalone TSAN test exercising the same concurrency model
(double-checked lock + dedup + race against random main-thread
fault-ins) confirmed: exactly 112 unique compiles, 32 dedup'd
slots, no data races, no double-init, clean early-quit termination,
clean 5-cycle teardown/recreate.

For 'Lazy' mode the ShaderCompileProgressTracker is given a total
of 0 for the batch matrix dimension (the worker doesn't update it),
so the progress widget shipped in commit 1089822 only reports the
~12 non-batch shaders during init - a sub-second blip rather than
the previous multi-second crawl. The total wall-clock cost is the
same; it's just moved off the runloop.

The other three backends (D3D12, OpenGL, Vulkan) still take the
historical Enabled-style path regardless of the user's choice,
because the core option doesn't reach their CompileShaders yet.
Follow-up commits will extend this. OpenGL is harder because the
GL context can't be shared with a worker thread under the libretro
hardware-renderer protocol - the Lazy option will degrade to
Disabled there (compile-on-first-use on the main thread, no
background work).

Build: zero warnings, zero errors on linux platform=unix (which
doesn't compile gpu_hw_d3d11.cpp - guarded ifeq IS_WINDOWS=1).
gpu_hw_d3d11.cpp and common/d3d11/shader_cache.cpp both
cross-compile cleanly with x86_64-w64-mingw32-g++. .so size
8030576 (+2336 vs master); the growth is GetBatchPixelShader,
the worker entry point, and the thread/mutex member machinery.
25 retro_* exports unchanged.

Files touched:
  - src/core/types.h: new GPUShaderPrecompileMode enum
  - src/core/settings.{h,cpp}: gpu_shader_precompile_mode field,
    Parse/Get helpers, Load wiring
  - src/libretro/libretro_core_options.h: swanstation_GPU_ShaderPrecompile
  - src/common/d3d11/shader_cache.h: IsOpen() accessor
  - src/core/gpu_hw_d3d11.{h,cpp}: persistent shader cache and
    shadergen members, GetBatchPixelShader, worker thread
    machinery, three-way CompileShaders branch, DrawBatchVertices
    routes through the helper, DestroyShaders joins the worker.
2026-05-11 17:25:43 +02:00
Lib
8e7f7a30cb gpu_hw: skip duplicate-source compiles for the two Reserved_*Direct16Bit texture modes
GPU_HW_ShaderGen::GenerateBatchFragmentShader emits a fragment
shader source string parameterised by (BatchRenderMode,
GPUTextureMode, dithering, interlacing). The texture_mode arm
masks the RawTextureBit out of the input -

  const GPUTextureMode actual_texture_mode = texture_mode & ~GPUTextureMode::RawTextureBit;

- and consults the masked value only via three macros: PALETTE,
PALETTE_4_BIT, and PALETTE_8_BIT. None of those three is true for
any of {Direct16Bit (2), Reserved_Direct16Bit (3),
RawDirect16Bit (6), Reserved_RawDirect16Bit (7)}: the masking
collapses 2 and 6 to the same code path, and the reserved variants
3 and 7 are bit-identical to their non-reserved counterparts in
the generated shader source.

The disk-backed shader cache does dedup at the MD5 level - it
hashes the generated source text and only invokes the underlying
compiler once per unique key - but reaching that fast-path still
requires (a) calling GenerateBatchFragmentShader to assemble the
~3000-line shader source for the duplicate, then (b) computing
the MD5 to look it up. Across the 144-iteration shader-compile
matrix (4 render-modes x 9 texture-modes x 2 dither x 2 interlace),
2/9 of the iterations - 32 - run that redundant source assembly
and MD5 for no end-state gain. The D3D12 and Vulkan PSO loops
multiply the redundancy further: D3D12's pipeline matrix is
2 x 4 x 5 x 9 x 2 x 2 = 1440 entries, Vulkan's is
3 x 4 x 5 x 9 x 2 x 2 = 2160 entries, of which 22% are duplicates.

This commit short-circuits the duplicate work at each backend's
loop instead of relying on the cache's MD5 dedup to catch it.
The exact mechanism varies by backend's resource model:

  - GPU_HW_D3D11: m_batch_pixel_shaders stores ComPtr<ID3D11PixelShader>,
    refcounted. When texture_mode is 3 or 7, copy the ComPtr from
    the canonical slot (2 or 6 respectively) instead of regenerating
    the shader source and invoking the cache. Both source generation
    AND the device-side CreatePixelShader call are eliminated.

  - GPU_HW_D3D12: same ComPtr<ID3DBlob>/ComPtr<ID3D12PipelineState>
    treatment for both the batch_fragment_shaders blob array AND
    the m_batch_pipelines PSO matrix - which is the bigger win
    (~320 PSOs avoided rather than ~32 shaders).

  - GPU_HW_OpenGL: GL::Program is non-copyable (owns a GLuint),
    so the m_render_programs array can't simply share entries.
    Skip the GenerateBatchFragmentShader call for the duplicate
    modes by passing the source-mode's parameters to it, and let
    the program-binary cache hit on the lookup - the GL compile/
    link path is bypassed because of the MD5 match.

  - GPU_HW_Vulkan: VkShaderModule destroy is done via enumerate
    over the array using SafeDestroyShaderModule, which would
    double-destroy if two slots held the same handle, so we
    can't copy. Apply the same approach as OpenGL: skip the
    source generation by reusing the canonical source string,
    let the shader cache's MD5 match short-circuit the
    GLSL->SPIR-V step, and pay only the cheap vkCreateShaderModule
    call to get a fresh handle for each slot. The Vulkan PSO
    matrix is not deduplicated in this commit because VkPipeline
    has the same enumerate-destroy hazard with no convenient
    refcounting alternative; that win (~480 PSOs avoided) is
    left for a future commit that introduces an ownership-aware
    pipeline wrapper.

Per backend, the per-call elimination breakdown:

  - D3D11:  32 GenerateBatchFragmentShader + 32 MD5 + 32 D3DCompile
            cache-lookup + 32 CreatePixelShader avoided
  - D3D12:  32 GenerateBatchFragmentShader + 32 MD5 +
            320 gpbuilder.Create (the actual D3D12 PSO compile
            into GPU machine code, the dominant cost) avoided
  - OpenGL: 32 GenerateBatchFragmentShader avoided
            (cache + CreateProgramBinary on the rest)
  - Vulkan: 32 GenerateBatchFragmentShader avoided
            (cache + vkCreateShaderModule on the rest)

Behaviour is identical at draw time: every backend's dispatch
indexes m_batch_pixel_shaders/m_render_programs/m_batch_pipelines/
batch_fragment_shaders directly with m_batch.texture_mode, and
those slots now hold either the same compiled artifact (D3D11/D3D12
via ComPtr copy) or a logically-equivalent freshly-created artifact
(GL/Vulkan via cache-warmed lookup). The dispatch matrix is fully
populated.

Build: zero warnings, zero errors. 4 files changed, +105/-2 lines.
.so size unchanged at 8028240 bytes (control-flow change inside
existing functions; no new code or removed code from the binary).
25 retro_* exports unchanged.

The cold-cache cost of switching the texture filter from Nearest
to xBR/JINC2/Bilinear is dominated by 'compile 112 unique shader
sources from scratch with high-optimization HLSL/SPIR-V/GLSL
compilers'; this commit eliminates the redundancy on top of that
baseline rather than the baseline itself, but reduces the
constant overhead by enough to be perceptible in the slowest
paths (D3D12 / Vulkan PSO matrices).
2026-05-11 16:53:28 +02:00
Lib
10898224d8 libretro: surface DisplayLoadingScreen progress through the frontend OSD
HostInterface::DisplayLoadingScreen was a no-op stub in the libretro
backend. The DuckStation interface contract is documented as: a
caller invokes it repeatedly during a bounded long operation with
(value, total) progress counters, throttled by the caller to roughly
10 Hz. In swanstation the existing call sites are:

  - GPU_HW::ShaderCompileProgressTracker::Increment (once per
    compiled batch/screen-quad/etc. shader, throttled by a 100 ms
    interval and a 1-second minimum-time-before-first-message
    floor; the total is 1+1+2+(4*9*2*2)+1+(2*2)+4+(2*3)+1 = 172 for
    the D3D11 backend)
  - texture_replacements.cpp preload loop (once per replacement
    texture)
  - HostInterfaceProgressCallback (the generic ConsoleProgressCallback
    bridge - not used by the libretro path today but still wired in
    via the same hook)

Because the libretro implementation discarded all of these, users
saw nothing during shader precompilation. With a cold shader cache
and the texture filter set to xBR or one of the other heavier
options, that's typically tens of seconds of synchronous work on
the runloop thread, during which RetroArch appears to be hung. The
hint that it isn't hung was only visible to anyone willing to
attach a debugger.

Forward DisplayLoadingScreen to the libretro frontend. The mapping:

  - When the frontend reports message-interface v1+ (the cached
    libretro_msg_interface_version probed in InitInterfaces),
    use RETRO_ENVIRONMENT_SET_MESSAGE_EXT with type =
    RETRO_MESSAGE_TYPE_PROGRESS, target = RETRO_MESSAGE_TARGET_OSD,
    and an int8 progress percentage derived from the
    (value, total) pair. RetroArch renders this as a dedicated
    progress widget rather than a generic OSD notification.
  - When the frontend is older (libretro_msg_interface_version == 0),
    fall back to RETRO_ENVIRONMENT_SET_MESSAGE with the formatted
    'Compiling Shaders 47/172' text in the message body. The user
    still sees the progress count, just without the widget.

The progress percentage is computed in long arithmetic to avoid
overflow on totals up to ~21 million (more than two orders of
magnitude beyond what the shader tracker actually uses, but the
preload-textures path can in theory hit larger totals on a heavily
modded game). The result is clamped to [0,100] to match the
libretro spec.

The displayed text always includes 'value/total' even when the
EXT path is taken, because the spec is explicit that the progress
field is a hint and frontends may ignore it; that way the same
information shows up regardless of which path the frontend uses.

Message duration on the EXT path is set to 1000 ms with priority 3:
the priority matches the libretro header's documented
'frontend-generated notifications' tier (so we don't outrank
later game-relevant messages), and the duration is comfortably
larger than the tracker's 100 ms update interval, so consecutive
calls keep the widget alive smoothly until the operation
completes and the last message ages out.

Empty-message protection is added since SET_MESSAGE_EXT documents
'undefined behavior' for a NULL or empty msg field. Without this,
a stray DisplayLoadingScreen call from anywhere with a null
title would crash the frontend.

libretro_msg_interface_version was already being probed in
InitInterfaces() (since RA 1.9 / 2020) but never consumed; this
commit puts it to use. AddOSDMessage still uses the legacy
SET_MESSAGE path; moving it to SET_MESSAGE_EXT is a separate
change because the semantics around message lifetime
(frames vs ms) differ and AddOSDMessage callers pass an explicit
duration that needs careful translation.

Throttling is unchanged: the existing
ShaderCompileProgressTracker only invokes DisplayLoadingScreen
after the operation has been running for >= 1 second, and then
at most every 100 ms. For warm-cache shader loads (the common
case where everything resolves from disk in <100 ms) this still
produces zero OSD traffic.

Build: zero warnings, zero errors. 100 insertions, 1 deletion in
src/libretro/libretro_host_interface.cpp. .so size 8028240 bytes
(was 8027408, +832 - the new code path is ~80 lines of mostly
straightforward integer arithmetic and one snprintf). 25 retro_*
exports unchanged.
2026-05-11 16:53:24 +02:00
Lib
3cc74f4963 common: remove the unused ConsoleProgressCallback class
ConsoleProgressCallback is a stderr-drawing progress-bar implementation
of the ProgressCallback interface, inherited from upstream DuckStation
where the headless NoGui frontend used it for command-line image
preloading and similar long-running tasks. The libretro core never
instantiates it - HostInterfaceProgressCallback (which routes through
the host interface's OSD/log machinery) is the only ProgressCallback
subclass actually used (system.cpp:534 in OpenCDImage's RAM-preload
path).

A grep for ConsoleProgressCallback turns up only the class definition,
the implementation block, and the includes those needed - no
construction sites, no friend declarations, no test code. It's pure
dead code on this build.

Drop the class declaration from progress_callback.h and the 162-line
implementation block from progress_callback.cpp. With ConsoleProgress-
Callback gone, three includes also become unused: <cstdio> (only
fprintf/fwrite/fflush in the dead code), <limits> (only the
numeric_limits<float>::infinity in the dead ctor), and <cmath> (only
the std::abs in the dead Redraw). Drop them too.

ProgressCallback's modal-confirmation surface (ModalConfirmation,
DisplayFormattedModalConfirmation) is left in place: it's part of the
abstract interface, the only remaining ProgressCallback impl
(HostInterfaceProgressCallback) overrides ModalConfirmation, and that
override is part of the forward-looking shader-compilation /
async-task progress hookup that future libretro API surfaces would
plug into.

Net: 201 lines deleted across two files, zero added. .so size drops
~5.7 KiB. No behaviour change.
2026-05-08 18:15:45 +02:00
Lib
f11dfea0a7 system: honour AllowBootingWithoutSBIFile in the libretro core
CheckForSBIFile detects libcrypt-protected discs that are missing
their SBI sidecar. When the user has opted in via the
AllowBootingWithoutSBIFile=true setting the function was supposed to
boot the game anyway with a warning, but the libretro core has no
synchronous yes/no UI: the implementation routed through
HostInterface::ConfirmMessage, which in this fork is a stub that
unconditionally returns false. The result was that users who
explicitly set the override still got booting denied, and the only
way to actually boot a libcrypt game without SBI was unreachable.

Cut out the ConfirmMessage indirection. When the override is set,
post a 30-second OSD warning explaining that the game will likely
not run correctly and to consult the README about adding an SBI
file, and return true to proceed with boot. The off-by-default
branch is unchanged: report the error and refuse the boot, which
is what users who haven't opted in want to see.

Net effect:
  - Without the override: identical behaviour (refuse + error).
  - With the override: now actually boots, with a long, informative
    OSD warning. Previously: silently failed via the ConfirmMessage
    stub returning false.
2026-05-08 18:05:17 +02:00
Lib
3caececb52 host_interface: remove the unreachable ToggleSoftwareRendering helper
ToggleSoftwareRendering had zero callers in the libretro core. Its
historical role on the upstream DuckStation HostInterface base was a
hotkey hook (Qt/NoGui frontends bound it to a key) that swapped between
software and hardware rendering at runtime by calling RecreateGPU.

The libretro frontend has no such hotkey path: the gpu_renderer setting
flows through the core options, and if it changes between frames
CheckForSettingsChanges drives RecreateGPU directly (libretro_host_interface.cpp:1959).
The other RecreateGPU caller in this fork is the hardware-context-loss
fallback (libretro_host_interface.cpp:2004), which calls RecreateGPU
straight too. Neither path goes through ToggleSoftwareRendering.

So the method was a Qt-frontend leftover that the merge-down kept
defined but never wired up. Drop the body and the declaration; refresh
the historical-context comment that listed it as an example of a method
kept from the former base, replacing it with AddOSDMessage which is
genuinely on that boundary and still in use.
2026-05-08 17:45:51 +02:00
Lib
ca8ed6a084 audio: hardcode the libretro audio config; remove Reconfigure plumbing
The libretro core has a single fixed audio configuration: the PSX is
structurally 44.1 kHz stereo, the libretro frontend does its own
resampling, and the FIFO drain is paced by retro_run() rather than by
buffer fill. The Settings field 'audio_buffer_size' that nominally
parameterised this had no setter anywhere - no core option, no
libretro_settings_interface entry, no game_settings override - so the
only value ever seen was the 2048 default. Likewise the four-argument
LibretroAudioStream::Reconfigure(input_rate, output_rate, channels,
buffer_size) signature carried no information that the core would ever
vary; three of its arguments were already documented in the header as
existing only 'for signature compatibility with the historical
AudioStream base'. That base class was removed earlier in this branch.

Make the configuration compile-time:

  - Drop g_settings.audio_buffer_size (dead field) and the unused
    HostInterface::AUDIO_SAMPLE_RATE / AUDIO_CHANNELS /
    DEFAULT_AUDIO_BUFFER_SIZE constants alongside it.

  - Replace the LibretroAudioStream Default* / MaxSamples / FullVolume
    constants with named, single-source-of-truth SAMPLE_RATE / CHANNELS
    / BUFFER_SIZE / FIFO_CAPACITY. SAMPLE_RATE is what
    GetSystemAVInfo passes to retro_get_system_av_info; BUFFER_SIZE
    is what the SPU's UpdateEventInterval reads via GetBufferSize();
    FIFO_CAPACITY (= 32768, unchanged from the historical MaxSamples)
    is the FIFO backing store size.

  - Remove Reconfigure(): BootSystem now just default-constructs the
    stream and is done.

  - Remove the dead Shutdown() method (the unique_ptr destructor
    handles teardown), the dead IsSilentMode() accessor, the dead
    SetBufferSize() helper (its runtime capacity check was tautological
    once buffer_size became a constant), and the dead m_buffer_size
    member (GetBufferSize() is now constexpr).

  - Drop the '#ifndef AUDIO_CHANNELS / #define AUDIO_CHANNELS 2' macro
    in libretro_audio_stream.cpp; it shadowed the class member of the
    same name and was a footgun if the values ever diverged.

The .so size is unchanged - all the removed indirection compiled to
the same constant loads after inlining, so this is a code-clarity
patch rather than a perf patch. The wins are: smaller surface area
(no dead methods, no dead member, no dead Settings field), no path
that could plumb a non-2048 buffer size into the SPU and break the
audio-frame budget invariant, and a single source of truth for the
audio configuration constants.
2026-05-08 17:37:28 +02:00
Lib
716c520863 system: remove the unreachable internal rewind subsystem
There were three pieces of rewind code in System:

  - The save side (SaveRewindState, s_rewind_states deque,
    s_rewind_save_counter / s_rewind_save_frequency, the
    DoMemorySaveStates rewind branch).
  - The load side (LoadRewindState, DoRewind, SetRewinding,
    s_rewind_load_counter / s_rewind_load_frequency,
    s_rewinding_first_save).
  - The plumbing (CalculateRewindMemoryUsage, the rewind half of
    UpdateMemorySaveStateSettings, the s_rewind_load_counter check
    in RunFrame, the FixIncompatibleSettings clamp on Android32,
    the rewind triplet in CheckForSettingsChanges' settings-changed
    predicate, three Settings fields, an unused <cinttypes>
    include).

None of it is reachable in this build:

  - SetRewinding, the only function that ever sets
    s_rewind_load_counter to a non-negative value, has zero callers.
    A grep across src/ and dep/ returns just the declaration in
    system.h and the definition in system.cpp.

  - With s_rewind_load_counter permanently -1, RunFrame's
    'if (s_rewind_load_counter >= 0) DoRewind(); return;' branch
    never fires, so DoRewind, LoadRewindState and everything
    they touch are dead.

  - g_settings.rewind_enable is declared in settings.h with
    default false, but Settings::Load(SettingsInterface&) does not
    populate it from any 'Main RewindEnable' key (no such key is
    referenced anywhere) and there is no swanstation_Main_RewindEnable
    entry in libretro_core_options.h. Same for rewind_save_frequency
    and rewind_save_slots. They are stuck at their defaults.

  - With rewind_enable always false, s_memory_saves_enabled is set
    to false in UpdateMemorySaveStateSettings, so RunFrame's
    'if (s_memory_saves_enabled) DoMemorySaveStates();' branch
    never fires either. That removes DoMemorySaveStates entirely
    (its only other caller was the rewind path that's already
    dead), and with it the s_runahead_frames > 0 SaveRunaheadState
    fallback inside it - but DoRunahead already calls
    SaveRunaheadState directly on every frame the runahead window
    is active, so removing the fallback changes nothing observable.

The shape of the dead code mirrors upstream DuckStation, where
SetRewinding is wired to the Qt frontend's 'hold rewind' hotkey.
swanstation has no Qt frontend; the libretro frontend's own rewind
feature works through retro_serialize / retro_unserialize and does
not touch System's rewind state at all. So the entire subsystem has
been a no-op since the libretro fork.

What this commit removes:

  - System: SaveRewindState, LoadRewindState, SetRewinding, DoRewind,
    DoMemorySaveStates, CalculateRewindMemoryUsage and their forward
    declarations.
  - System static state: s_rewind_states, s_rewind_save_counter,
    s_rewind_save_frequency, s_rewind_load_counter,
    s_rewind_load_frequency, s_rewinding_first_save,
    s_memory_saves_enabled.
  - RunFrame: the s_rewind_load_counter branch and the
    s_memory_saves_enabled branch.
  - UpdateMemorySaveStateSettings: the rewind-config block.
  - ClearMemorySaveStates: the s_rewind_states.clear() call (the
    runahead clear is preserved).
  - Settings: rewind_enable, rewind_save_frequency, rewind_save_slots.
  - HostInterface::FixIncompatibleSettings: the Android-32 rewind
    clamp.
  - HostInterface::CheckForSettingsChanges: the rewind triplet from
    the System::UpdateMemorySaveStateSettings dispatch predicate
    (only runahead_frames is left).
  - system.cpp: the now-unused <cinttypes> include.
  - SaveMemoryState: 'Failed to create rewind state.' -> 'Failed to
    create runahead memory state.', because runahead is now the only
    caller of the helper.

What stays:

  - retro_serialize / retro_unserialize and the
    RETRO_ENVIRONMENT_GET_SAVESTATE_CONTEXT logic, which is what the
    libretro frontend actually uses for rewind/runahead via the
    standard save-state path. is_memory_state still threads through
    to System::DoState so the JIT cache is invalidated rather than
    flushed when the frontend signals same-binary-same-instance.
  - The whole runahead subsystem (s_runahead_states, DoRunahead,
    SaveRunaheadState, SetRunaheadReplayFlag and its ~15 callers in
    the controllers).
  - The MemorySaveState struct and SaveMemoryState / LoadMemoryState
    helpers.

Build clean, .so size drops from 8035664 to 8034592 bytes (-1072).
25 retro_* exports unchanged. Zero warnings. Net diff: 4 files
changed, +3 / -164 lines.
2026-05-08 16:51:10 +02:00
Lib
93ee18884d libretro: stop double-polling pad buttons each frame in AnalogController/NeGconRumble
UpdateControllersAnalogController and UpdateControllersNeGconRumble
each polled the libretro frontend twice per frame for the same
buttons - once to drive controller->SetButtonState() and again to
drive the analog-mode combo-press detection that follows. The two
phases reused the same RETRO_DEVICE_ID_JOYPAD_* IDs but never reused
the value, so each frame did 8 extra g_retro_input_state_callback
hops (analog) or 1 extra (NeGconRumble) per active controller port.

The frontend supplies a single-shot bitmask read via
RETRO_DEVICE_ID_JOYPAD_MASK that returns all 16 standard JOYPAD bits
in one u16. The previous code already used that for the SetButtonState
loop when m_supports_input_bitmasks was true, but then dropped the
'active' value on the floor at end of the if-block and went back to
per-button callbacks for the combo logic. This commit hoists 'active'
into the function scope and feeds it into both phases:

  - AnalogController: 8 redundant callbacks per controller per frame
    eliminated (PadCombo_L1, R1, L2, R2, L3, R3, Start, Select were
    all sitting in 'active' already).
  - NeGconRumble: 1 redundant callback per controller per frame
    (Analog_Select).

The fallback path (frontend without bitmask support) is restructured
to also produce a 'active' u16 by querying the 16 individual buttons
once. The cost there is sixteen-callbacks-then-do-everything-from-
the-mask, which is strictly fewer than the previous sixteen-for-the-
loop-then-eight-more-for-the-combos.

Semantics are preserved: PadCombo_L1..PadCombo_Select and
Analog_Select had been u16 holding 0/1 from the digital JOYPAD path;
they are now bool with the same 0/1 values, and the combo-detect /
release-detect chains compute the same logical product.

The button SetButtonState / axis SetAxisState / rumble logic in
between is unchanged.

Build clean, .so size unchanged at 8035664 bytes (lost 9 callback
sites, added one small bitmask-build loop in the fallback path; the
two roughly cancel in object size). 25 retro_* exports unchanged.
Zero warnings.
2026-05-08 16:23:38 +02:00
Lib
98f88e5058 host_interface: stop rebuilding the GPU when rewind/runahead settings change
CheckForSettingsChanges has a long predicate that triggers
g_gpu->UpdateSettings() when any GPU-relevant setting changes (the
resolution scale, MSAA level, PGXP flags, display aspect ratio,
display offsets, etc.). Two of the conditions in that predicate
were rewind_enable and runahead_frames, but the GPU layer doesn't
read either of those: a 'grep -rn rewind_enable\|runahead_frames'
across src/core/gpu*.cpp / src/core/gpu*.h returns nothing. They
are read only by System (s_memory_saves_enabled,
UpdateMemorySaveStateSettings, DoRunahead, SaveRunaheadState) and
by the libretro game-settings overrides.

The same function already has a dedicated predicate ten lines
further down -

  if (g_settings.rewind_enable      != old_settings.rewind_enable ||
      g_settings.rewind_save_frequency != old_settings.rewind_save_frequency ||
      g_settings.rewind_save_slots  != old_settings.rewind_save_slots ||
      g_settings.runahead_frames    != old_settings.runahead_frames)
  {
    System::UpdateMemorySaveStateSettings();
  }

- which is the correct hook for those changes and is still in place.

The two stray entries had been in the predicate since the file was
created (b37eec0, 'libretro: add static Makefile.libretro build');
they look inherited from upstream DuckStation, where rewind/runahead
state used to live closer to the GPU. In swanstation that coupling
is gone but the predicate was never trimmed.

Effect of the bug: toggling rewind via the libretro core option, or
changing the runahead frame count, drove a full
g_gpu->UpdateSettings() call. Per the GPU_HW_D3D11 / D3D12 / OpenGL
/ Vulkan UpdateSettings impls, that path can rebuild the framebuffer
(VRAM read-back, display texture clear, framebuffer recreate) and
recompile shaders, neither of which is affected by rewind or
runahead. Most users would notice a brief stutter and a shader
cache rebuild for no reason.

Build is unaffected (this is a control-flow predicate change inside
an existing function); .so size is unchanged at 8035664 bytes; 25
retro_* exports unchanged; zero warnings.
2026-05-08 16:07:11 +02:00
Lib
3054cb57d3 host_interface: devirtualize, fold LibretroHostInterface into HostInterface
The host interface had been split into an abstract HostInterface base
in src/core/host_interface.{h,cpp} and a concrete LibretroHostInterface
final subclass in src/libretro/libretro_host_interface.{h,cpp}. The
split predates this fork's libretro-only build of swanstation -
upstream DuckStation has multiple frontends (Qt, NoGui, Android) - but
in this fork there has only ever been one concrete subclass, and the
separation only added a vtable on every method that used to be virtual,
plus the usual cross-translation-unit cost of pure-virtual dispatch.

This commit collapses the two classes into a single non-abstract
HostInterface declared in src/core/host_interface.h. The data members
that used to be private to LibretroHostInterface (DiskControlInfo,
m_hw_render_callback, retropad_device, m_rumble_interface, the game
settings entry, the controller-update aspect ratio cache, and the
hardware-renderer display) move alongside the existing m_display /
m_audio_stream / m_user_directory members. The retro_* entry-point
methods, the controller update helpers, the disk control callbacks,
the hardware renderer setup, and the BIOS / memory-card / shader-cache
path helpers are likewise hoisted into the consolidated class.

Header-side mechanics:

  - src/core/host_interface.h includes <libretro.h> directly. Many
    files in src/core already pull libretro.h in transitively via
    gpu_hw_*.h, so this doesn't expand the include cost meaningfully.
  - src/libretro/libretro_host_interface.h is deleted. Its callers
    (libretro_audio_stream.cpp, libretro_settings_interface.cpp,
    libretro_host_display.cpp, gpu_hw_d3d11/opengl/vulkan.cpp,
    texture_replacements.cpp) all had #include 'libretro_host_interface.h'
    or '../libretro/libretro_host_interface.h'; those become
    #include 'core/host_interface.h'.
  - g_libretro_host_interface (the storage instance, of type
    LibretroHostInterface) is renamed g_host_interface_storage and is
    of type HostInterface. The pointer g_host_interface keeps its name
    and role (set by the constructor, cleared by the destructor); both
    are now defined in libretro_host_interface.cpp next to each other.
  - Forward-decls of class HostInterface and class LibretroHostInterface
    in other headers and other files collapse to one HostInterface decl.

Three places in the libretro override called back into the base impl:

  - LibretroHostInterface::Initialize did 'if (!HostInterface::Initialize())'
    which dispatched to a base impl that just returned true. Folded
    the base body in (no-op).
  - LibretroHostInterface::Shutdown did 'HostInterface::Shutdown()'
    which dispatched to a base impl that called System::Shutdown() if
    the system wasn't already shut down. Folded the body in.
  - LibretroHostInterface::CheckForSettingsChanges did
    'HostInterface::CheckForSettingsChanges(old_settings)' and then
    ran two extra calls (UpdateGeometry, UpdateLogging) for libretro-
    specific resync. Moved those two calls to the end of the unified
    body in core/host_interface.cpp; the override is gone.

These were the only base-class delegations: every other libretro-side
override was a complete replacement.

Method consolidation: nine methods were defined in both files and the
libretro impls are kept (they are the real impls; the base impls were
either default-noop placeholders or generic fallbacks):

  - Initialize, Shutdown
  - ReportError, ReportMessage, ConfirmMessage
  - GetBIOSDirectory
  - GetSharedMemoryCardPath, GetGameMemoryCardPath
  - GetShaderCacheBasePath

The HostInterface() and ~HostInterface() ctor/dtor merge into the
libretro side: the constructor still does g_host_interface = this; the
destructor does the libretro-side hardware-renderer teardown plus
g_host_interface = nullptr.

All 'virtual' / 'override' / pure-virtual annotations are gone from
the resulting class. There is no vtable.

Build: zero warnings, zero errors. .so size drops from 8046184 to
8035664 bytes (-10520) - the HostInterface and LibretroHostInterface
vtables and typeinfo, the indirect-call thunks at every former-virtual
method site, and the second class's name-mangled symbols all go away.
25 retro_* exports unchanged. No behaviour change is intended;
duplicate methods are resolved deterministically (libretro impls win,
matching the previous override semantics).
2026-05-08 15:53:49 +02:00
Lib
1c836c10ca audio: devirtualize AudioStream, fold NullAudioStream into LibretroAudioStream
The audio path used to be:

  - common/audio_stream.h declared an abstract AudioStream base with
    one pure virtual (FramesAvailable) and shared non-virtual
    BeginWrite/EndWrite/Reconfigure/Shutdown.
  - libretro/libretro_audio_stream.{h,cpp} overrode FramesAvailable
    with the real libretro frontend drain.
  - common/null_audio_stream.{h,cpp} overrode FramesAvailable to
    discard, and was constructed only to feed the SPU during
    internal-runahead replay so audio from those frames never reached
    the frontend. The SPU pointer-swapped between the host stream and
    the null stream around DoRunahead's replay loop.

The base class buys nothing here. There is exactly one runtime audio
stream in swanstation - LibretroAudioStream - and the second subclass
exists only to express 'discard everything' behaviour, which is
trivially representable as a flag on the real one. EndWrite ran a
virtual call to FramesAvailable on every SPU update (~150-300 times
per frame), the indirection resolving to the same place every time.

Drop the base class and the null subclass:

  - Delete common/audio_stream.{h,cpp} and common/null_audio_stream.{h,cpp}.
  - LibretroAudioStream becomes a plain class with no inheritance,
    absorbing the BeginWrite/EndWrite/Reconfigure/Shutdown bodies and
    the SampleType/MaxSamples/etc. constants from the old base.
  - FramesAvailable's contents are inlined into EndWrite (it was the
    only caller), with an early-return for fast-hook mode that
    matches the previous behaviour exactly.
  - The 'discard' role of NullAudioStream becomes a m_silent_mode flag
    and a SetSilentMode() setter on LibretroAudioStream. EndWrite
    drains the FIFO immediately when silent, so the SPU keeps ticking
    state-machines (envelope counters, ADPCM phase, etc.) for
    correctness, the FIFO does not build up backpressure across the
    runahead window, and nothing reaches the frontend.

  - System::DoRunahead replaces the SPU pointer-swap with a
    SetSilentMode(true)/SetSilentMode(false) toggle on the host's
    existing LibretroAudioStream. s_runahead_audio_stream
    (std::unique_ptr<AudioStream>) and the matching reset() in
    System::Shutdown go away entirely.

  - HostInterface drops the virtual CreateAudioStream() factory
    method; its single override in LibretroHostInterface returned
    std::make_unique<LibretroAudioStream>() which is now inlined at
    the only call site (HostInterface::BootSystem).

  - HostInterface::m_audio_stream and HostInterface::GetAudioStream
    become typed as LibretroAudioStream (forward-declared in
    host_interface.h, the libretro header included from the cpp).
    SPU::SetAudioStream and SPU::m_audio_stream similarly get the
    concrete type. The static_cast in retro_run_frame's
    UploadToFrontend call goes away.

  - Makefile.libretro and src/common/CMakeLists.txt drop the deleted
    source files from their lists.

Linux x64 build still warning-clean. .so size drops from 8047800 to
8046184 bytes (-1616) - the AudioStream and NullAudioStream
vtables/typeinfo, the virtual destructor and FramesAvailable, the
indirect-call sites in EndWrite, and the second runahead audio
stream instance and its construction code are all gone. 25 retro_*
exports unchanged. Behaviour is identical: the SetSilentMode toggle
produces exactly the same observable result as the
swap-to-NullAudioStream pattern (the SPU's frame output is
discarded during the replay window in both cases).
2026-05-08 15:07:36 +02:00
Lib
0f4a4a3e1f GameSettings: disable PGXP depth buffer for PS1 Tekken/Soul Edge
Tekken 1/2/3 and Soul Blade/Soul Edge submit character submeshes in an
order that lets PGXP-corrected w-values fail the depth test against
earlier submeshes of the same model. With PGXP Depth Buffer enabled,
parts of character bodies intermittently disappear (e.g. Xiaoyu's torso
on Tekken 3 with 8x scale + xBR + all PGXP options on).

The DisablePGXPDepthBuffer trait already existed in
libretro_game_settings.cpp but was never AddTrait'd for any game. Wire
it up for the Namco PSX fighter line.
2026-05-08 14:46:21 +02:00
Lib
2fdb5240d4 settings: devirtualize SettingsInterface
SettingsInterface was a base class with five pure-virtual config-getter
methods, defined in core/settings.h. There has only ever been one
concrete subclass: LibretroSettingsInterface (in libretro/), which
backs every GetXxxValue call with a single retro_environment_callback
to RETRO_ENVIRONMENT_GET_VARIABLE.

The single-impl shape means every si.GetBoolValue / si.GetIntValue /
si.GetStringValue call in Settings::Load and elsewhere goes through a
vtable indirection that resolves to exactly one place. Settings::Load
issues 61 such calls, and runs at boot plus on every libretro
core-options change. The cost per call is small (~2 ns per virtual
dispatch on modern CPUs), so the wall-clock saving is modest, but
the abstraction itself buys nothing - there is no second
implementation, no plan to add one (the core target is libretro-only),
and no use case where the indirection would help.

Drop the base class:

  - Remove 'class SettingsInterface' from core/settings.h, along with
    its virtual destructor and five pure virtuals.
  - Remove the SettingsInterface destructor definition from
    core/settings.cpp.
  - Make LibretroSettingsInterface a plain class with non-virtual
    methods (drop the 'override' keyword and the public-inheritance
    base).
  - Change Settings::Load's signature from (SettingsInterface&) to
    (LibretroSettingsInterface&). The one caller already passes a
    LibretroSettingsInterface, so no call site needs to change.
  - Forward-declare LibretroSettingsInterface in core/settings.h
    (the type only appears as a reference in Load's signature) and
    include the libretro header from settings.cpp where the
    member function calls actually have to see the definition.

The forward-declaration plus include-from-cpp pattern keeps
core/settings.h free of libretro headers - a header-level layering
nicety. The cpp-level dependency is an existing pattern (multiple
core/ TUs already include libretro/ headers - gpu_hw_d3d11.cpp,
gpu_hw_opengl.cpp, gpu_hw_vulkan.cpp, texture_replacements.cpp).

Linux x64 build still warning-clean. .so size drops from 8048432
to 8047800 bytes (-632) from removing the SettingsInterface vtable,
its typeinfo, the virtual destructor, and the indirect-call sites
in Settings::Load. 25 retro_* exports unchanged. Behaviour is
identical (same calls, same arguments, just direct now).
2026-05-08 14:22:28 +02:00
Lib
354b8b5e6d settings: drop two dead enhancement-toggle fields and one dead branch
Two fields in struct Settings have been dead since the swanstation
fork's first import:

  bool disable_all_enhancements = false;
  bool display_show_enhancements = false;

Neither is loaded from a config file (settings.cpp has no
si.GetBoolValue() entry for either), neither is exposed as a libretro
core option (libretro_core_options.h does not list either key), and
neither is written anywhere else in the tree. Both stay at the
default 'false' for the entire process lifetime.

display_show_enhancements is read nowhere - it is a pure dead field.

disable_all_enhancements has one read site, host_interface.cpp:250,
which gates a 21-line block of conservative-defaults assignments:

    if (g_settings.disable_all_enhancements)
    {
      Log_WarningPrintf("All enhancements disabled by config setting.");
      g_settings.cpu_overclock_enable = false;
      ...                                                    (21 lines)
      g_settings.bios_patch_tty_enable = false;
    }

Since the gate is permanently false, the entire block is unreachable.
The presumed intent is upstream DuckStation's 'safe mode' toggle
that swanstation never wired up; the equivalent functionality in
swanstation lives in apply_game_settings, which IS exposed and IS
the per-game compatibility-overrides feature described by
'swanstation_Main_ApplyGameSettings' in libretro_core_options.h.

Drop both fields and the dead branch. Behaviour is identical (the
read sites either don't exist or were unreachable). The two-field
removal saves a couple of bytes in the Settings struct after
padding; the 21-line branch removal reduces FixIncompatibleSettings
from 64 lines to 39 lines.

Linux x64 build still warning-clean. .so size unchanged at 8048432
bytes - the dead code was already eliminated by the optimizer, this
just removes it from the source. 25 retro_* exports unchanged.
2026-05-08 14:02:29 +02:00