Commit graph

4,790 commits

Author SHA1 Message Date
LibretroAdmin
9dcfea435a common/vulkan, core: pre-bake batch FS textured Nearest slice (48 blobs)
Patch 14 in the glslang-elimination series. Second slice of the
batch FS conversion: the textured + Nearest-filter path
(texture_mode != Disabled AND m_texture_filter == Nearest). The
runtime decision in GetBatchFragmentShader now routes both the
untextured slice (patch 13) and this slice through the embedded
blob set; only textured non-Nearest still goes through
shadergen + glslang.

Five SPIR-V-structural axes (48 blobs total = 3 x 2 x 2 x 2 x 2):

  - Input interpolation qualifier (none / centroid / sample). 3.
  - Color input perspective (standard / noperspective). 2.
  - Dual-source output (1 vs 2 outputs). 2.
  - PGXP depth output (writes gl_FragDepth or omits it). 2.
  - UV limits (without / with v_uv_limits flat input). 2.

The UV_LIMITS axis is new vs the untextured slice - it controls
whether v_uv_limits is declared as a per-vertex flat input on the
FS, matching the per-session m_using_uv_limits choice that already
drives the matching batch VS structural pick. Without UV limits the
FS skips the per-sample clamp.

Three new per-call specialisation constants relative to the
untextured slice cover the textured texture_mode encoding:

  id = 107 PALETTE_4_BIT  (bool, actual_texture_mode == 0)
  id = 108 PALETTE_8_BIT  (bool, actual_texture_mode == 1)
  id = 109 RAW_TEXTURE    (bool, RawTextureBit set in texture_mode)

PALETTE = PALETTE_4_BIT || PALETTE_8_BIT is derived inside the
shader. The texture_mode bit layout is described in
src/core/gpu_types.h; the C++ side derives the three boolean spec
const values from the per-call texture_mode in GetBatchPipeline.
Untextured blobs do not declare 107-109; passing them is harmless
per the Vulkan spec (unrecognised spec const IDs in the supplied
VkSpecializationInfo are silently dropped).

The shader body covers the helpers the shadergen path inlines:
ApplyTextureWindow, ApplyUpscaledTextureWindow, FloatToIntegerCoords,
RGBA8ToRGBA5551, and SampleFromVRAM. SampleFromVRAM splits on the
derived PALETTE flag and, within the palette branch, on
PALETTE_4_BIT vs PALETTE_8_BIT to do the correct sub-texel address
arithmetic. fixYCoord on Vulkan is the identity function so we use
the coord directly. The Vulkan-only API_VULKAN-y-flip in the VS
already accounts for sample-space orientation.

Output and discard logic mirrors the shadergen TEXTURED branches:
the no-TRANSPARENCY case writes o_col0 (and o_col1 when DUAL_SOURCE)
unconditionally; the TRANSPARENCY case branches on the texel's
semitransparency bit and applies the TRANSPARENCY_ONLY_OPAQUE /
TRANSPARENCY_ONLY_TRANSPARENT per-texel discard the way the
shadergen does.

Helper-side index encoding for the 48-blob array, matching
GetBatchTexturedNearestFragmentShaderBlob in embedded_shaders.cpp:

  interp = per_sample_shading ? 2 : (msaa ? 1 : 0)        (0..2)
  persp  = noperspective_color ? 1 : 0                    (0..1)
  dual   = dual_source ? 1 : 0                            (0..1)
  pgxp   = pgxp_depth ? 1 : 0                             (0..1)
  uv     = uv_limits ? 1 : 0                              (0..1)
  index  = interp*16 + persp*8 + dual*4 + pgxp*2 + uv     (0..47)

The use_dual_source derivation in GetBatchFragmentShader matches
the shadergen-side check exactly: supports_dual_source_blend &&
((render_mode is transparent) || filter != Nearest). For the two
embedded branches (untextured and textured Nearest) the filter-half
of the OR evaluates false, so both branches fall through to the
render_mode test.

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on all 48 blobs - 48/48 valid.
  - Total .inc size: ~2.2 MiB across all 48 blobs (~46 KiB each in
    text form, which is the 0xNNNNNNNNu, packed layout from the regen
    tool; binary contribution to the linked output is roughly 1/4 of
    that, so ~550 KiB. Acceptable for a renderer that previously
    pulled in glslang at runtime).
  - --target-env vulkan1.0 vs un-flagged glslangValidator: byte-
    identical for every variant.

Test priority:
  - Routine smoke under Enabled / Lazy / Disabled with Nearest
    filter (the default). Any textured polygon in any game now
    exercises the embedded path: dialogue portraits, sprite layers,
    background textures - the vast majority of pixels in most
    games.
  - Toggle PGXP UV correction (drives m_using_uv_limits) to flip
    the UV_LIMITS structural axis. Games that benefit most from
    PGXP corrections - Final Fantasy series, Tekken 3, Soul Blade -
    are good exercise targets.
  - Antialiasing toggle round-trip under Disabled mode per the
    patch-5-fix protocol (flips interpolation axis).
  - Each texture mode is exercised by different draws: palette
    textures dominate (most game art is 4-bit indexed), with
    direct-16bpp showing up for render-to-texture effects. Raw
    textures appear in framebuffer effects and some UI passes.
  - Cross-check with shadergen path by switching texture filter to
    Bilinear (still on the shadergen path) and back to Nearest -
    rendering should remain consistent across the switch.

After this lands, the only remaining glslang consumers in the
Vulkan backend are the texture-filter slices (Bilinear /
BilinearBinAlpha, JINC2 / JINC2BinAlpha, xBR / xBRBinAlpha). Each
of those filter families has its own FilteredSampleFromVRAM body
and will get its own template in subsequent patches.
2026-05-18 01:43:15 +02:00
LibretroAdmin
cde9da3c4b common/vulkan, core: pre-bake batch FS untextured slice (24 blobs)
Patch 13 in the glslang-elimination series. First slice of the batch
FS conversion (Bucket B's bigger half) - the untextured path
(texture_mode == GPUTextureMode::Disabled). Solid-shaded polygons
with no VRAM sampling, no palette logic, no texture filter
machinery, no UV limit logic; the shader is comparatively simple
and a good first cut into the FS state space.

Four SPIR-V-structural axes (24 blobs total = 3 x 2 x 2 x 2):

  - Input interpolation qualifier on v_col0, matching the batch VS
    this FS is bound with. None / centroid / sample. (3)
  - Color input perspective. Standard / noperspective. (2)
  - Dual-source colour output. With dual-source-blend hardware the
    TransparentAndOpaque and OnlyTransparent render modes write a
    second colour at (location 0 index 1) that drives SRC1_COLOR /
    SRC1_ALPHA. The pipeline blend state references SRC1_* or it
    does not - the output declaration count must match. (2)
  - PGXP depth output. With PGXP Depth Buffer enabled the FS omits
    gl_FragDepth so the rasterizer-interpolated VS depth (a_pos.w
    under PGXP) is used directly and early-Z stays available.
    Splitting this structurally preserves the early-Z optimisation
    that the original shadergen also relies on. (2)

Per-call knobs (TRANSPARENCY tri-state from BatchRenderMode,
DITHERING, INTERLACING) and the remaining per-session knobs
(TRUE_COLOR, DITHERING_SCALED, RESOLUTION_SCALE) collapse into
specialisation constants applied at pipeline-create time:

  id =   0  RESOLUTION_SCALE              (uint, per-session)
  id = 100  TRANSPARENCY                  (bool, per-call)
  id = 101  TRANSPARENCY_ONLY_OPAQUE      (bool, per-call)
  id = 102  TRANSPARENCY_ONLY_TRANSPARENT (bool, per-call)
  id = 103  DITHERING                     (bool, per-call)
  id = 104  INTERLACING                   (bool, per-call)
  id = 105  DITHERING_SCALED              (bool, per-session)
  id = 106  TRUE_COLOR                    (bool, per-session)

The TRANSPARENCY trio encodes the BatchRenderMode enum:
  TransparencyDisabled  -> (false, *, *)
  TransparentAndOpaque  -> (true,  false, false)
  OnlyOpaque            -> (true,  true,  false)
  OnlyTransparent       -> (true,  false, true)

These are spec consts applied to the FS in GetBatchPipeline.
The same constant_id values are passed to the runtime shadergen-
compiled textured FS as well, where they are silently dropped per
the Vulkan spec (unrecognised spec const IDs in the supplied
VkSpecializationInfo are ignored).

GetBatchFragmentShader now branches on lookup_mode at the slot-
miss path: GPUTextureMode::Disabled goes to the embedded blob set,
everything else continues through GenerateBatchFragmentShader +
g_vulkan_shader_cache->GetFragmentShader. The textured slices land
in subsequent patches, one or two texture filter values at a time
(Nearest first, then Bilinear / BilinearBinAlpha / JINC2 / xBRZ).

The regen tool's TEMPLATE_VARIANTS manifest grows a second entry
covering the 24 untextured FS variants alongside the 18 batch VS
variants that were already there. Same -D-flag-driven template
mechanism as patch 12. The unused 'fs' local at the bottom of
GetBatchPipeline before the SetFragmentShader call now collects
the FS spec constant info; both batch VS and FS spec constants
are independent VkSpecializationInfo blobs per Vulkan rules.

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on all 24 blobs - 24/24 valid.
  - Total .inc size: ~127 KiB across all 24 blobs (~5 KiB each).
  - --target-env vulkan1.0 vs un-flagged glslangValidator: byte-
    identical for every variant.

Untextured batch draws are extremely common - solid-shaded
polygons in 2D HUDs, fills, debug overlays, the framebuffer clear
quads at the top of every frame on many games. If the embedded
untextured FS is wrong it will be IMMEDIATELY obvious on the first
frame of any game (HUD bars / lifebars / dialogue boxes will be
visibly broken).

Test priority:
  - Routine smoke under Enabled / Lazy / Disabled. Boot any game
    and watch the HUD: solid-shaded health/mana bars (most JRPGs),
    fade-in/fade-out solid alpha overlays (cutscenes), and 2D menu
    backgrounds are direct exercises of this path.
  - Antialiasing toggle round-trip under Disabled mode per the
    patch-5-fix protocol, confirming the structural blob-pick
    flips cleanly across interpolation axes as m_multisamples /
    m_per_sample_shading change.
  - Toggle PGXP Depth Buffer at runtime to flip the PGXP_DEPTH
    structural axis. Behaviour should be unchanged from the
    shadergen baseline.
  - Toggle 'disable color perspective' (under Texture Correction)
    to flip the perspective axis.
2026-05-18 01:15:55 +02:00
LibretroAdmin
890211d080 common/vulkan, core: pre-bake batch VS (18-blob template, 2 spec consts)
Patch 12 in the glslang-elimination series, and the first step into
Bucket B (batch shaders). The batch VS state space has three SPIR-V-
structurally-distinct axes that specialisation constants cannot fold:

  1. Vertex attribute layout. 2 inputs (untextured), 4 (textured
     without UV limits) or 5 (textured with UV limits). The 'in <type>
     <name>' declarations are part of the SPIR-V module interface.
  2. Output interpolation qualifier on the v_col0 / v_tex0 outputs.
     None / centroid / sample, selected per session by UsingMSAA() /
     UsingPerSampleShading(). These compile to OpMemberDecorate
     Centroid / Sample on the VertexData output block, which is not
     a spec-constant-controllable property of the SPIR-V module.
  3. Color output perspective. m_disable_color_perspective toggles a
     'noperspective' qualifier on v_col0, compiling to
     OpMemberDecorate NoPerspective.

3 x 3 x 2 = 18 structurally distinct blobs. Body-level knobs
(RESOLUTION_SCALE, PGXP_DEPTH) are common-knob specialisation
constants on every blob (constant_id = 0 and 3 per the project
convention).

To avoid maintaining 18 hand-edited .glsl files, the source is a
single template (data/shaders/vulkan/batch.vert.glsl) with #if
guards on TEXTURED, UV_LIMITS, INTERP_CENTROID / INTERP_SAMPLE, and
NOPERSP. The regen tool (tools/regen_vulkan_spirv.py) is extended
with a TEMPLATE_VARIANTS manifest that compiles the template once
per variant with the corresponding -D flags. Build-time impact is
zero - the script is still developer-only and the .inc files are
checked in.

The matching index encoding lives in src/common/vulkan/embedded_-
shaders.cpp next to the lookup helper:

  attr   = !textured ? 0 : (uv_limits ? 2 : 1)        (0..2)
  interp = per_sample_shading ? 2 : (msaa ? 1 : 0)    (0..2)
  persp  = noperspective_color ? 1 : 0                (0..1)
  index  = attr * 6 + interp * 2 + persp              (0..17)

The C++ side calls GetBatchVertexShaderBlob with the per-session
state (m_using_uv_limits, m_multisamples > 1, m_per_sample_shading,
m_disable_color_perspective) and the per-call 'textured' loop
variable to pick the right blob in CompilePipelines. The existing
m_batch_vertex_shaders[2] cache shape is preserved - the helper just
selects which two of the 18 blobs to instantiate this session.

Spec constants are applied at PIPELINE-create time inside
GetBatchPipeline rather than at module-create time, matching the
SpecConstants infrastructure laid down in patch 3. The values are
session-constant, so they are the same for every batch pipeline in
a session and the driver caches them keyed by (module + spec values)
in the pipeline cache.

Header-side ergonomics: instead of declaring 36 individual extern
arrays (18 SPIR-V + 18 size), the .h declares a small
EmbeddedShaderBlob struct and a single
k_batch_vs_blobs[18] array, plus the GetBatchVertexShaderBlob
helper. The same struct is intended to be reused for the eventual
batch FS conversion (likely many more blobs given the texture filter
state space).

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on all 18 blobs - 18/18 valid.
  - Total .inc size: ~53 KiB across all 18 blobs.
  - --target-env vulkan1.0 vs un-flagged glslangValidator: byte-
    identical for every variant.

The batch VS is filled in CompilePipelines for all three precompile
modes (Enabled, Lazy, Disabled), so this conversion does not change
the hot-path-pre-build pattern from the patch 10-fix. The two VS
modules are present before any batch draw on every code path.

Test priority:
  - Routine smoke under Enabled / Lazy / Disabled. Any rendering at
    all exercises both VS modules immediately, so visual regressions
    show up on the first frame of the first game booted.
  - SSAA / MSAA round-trip in Disabled mode (per the patch-5-fix
    protocol), specifically to confirm the structural-blob-pick
    flips through 'none' -> 'centroid' -> 'sample' interp variants
    cleanly as m_multisamples changes.
  - Toggle 'disable color perspective' core option (under Texture
    Correction) to flip the perspective axis; visual difference is
    subtle but the blob-pick change is real.
  - Toggle PGXP Geometry Correction (drives UV_LIMITS via
    m_using_uv_limits) and PGXP Depth Buffer (drives PGXP_DEPTH
    spec const) to flip the body and attribute-layout axes.

After this lands, the only remaining runtime glslang consumer in
the Vulkan backend is the batch FS (GenerateBatchFragmentShader at
gpu_hw_shadergen.cpp line ~667). That is a far larger state space
- six texture filters x ~14 boolean macros plus the structural
USE_DUAL_SOURCE / PALETTE_* axes - and will need to land in
several patches, one or two texture filters at a time.
2026-05-18 00:56:03 +02:00
LibretroAdmin
74bebf8908 common/vulkan, core: pre-bake VRAM update-depth FS (MSAA blob pair, no spec consts)
Patch 11 in the glslang-elimination series, and the last non-batch
shader on the runtime shadergen path. This was the original patch 5
culprit - lazy-building this pipeline inside UpdateSettings tripped an
NVIDIA driver quirk that produced corrupted rendering on the next
frame. The preceding fix patch (pre-build hot-path utility pipelines
in shader_precompile=Disabled) sidestepped the failure mode by
ensuring m_vram_update_depth_pipeline is always built before any
cmdbuf that could need it, regardless of precompile mode, so this
conversion is now safe to land.

Shader converted:

  VRAMUpdateDepthFragmentShader. Rebuilds the depth attachment of the
  upscaled VRAM render pass from the colour attachment's alpha after a
  framebuffer recreation (resolution scale change, antialiasing toggle,
  true colour toggle). Trivial body - one texelFetch, one assignment
  to gl_FragDepth.

  Blobs:
    vram_update_depth_fs      - sampler2D, texelFetch(samp0, coord, 0).
    vram_update_depth_msaa_fs - sampler2DMS, texelFetch(samp0, coord,
                                gl_SampleID). The gl_SampleID reference
                                forces per-sample shading per the
                                Vulkan spec, regardless of the
                                SetMultisamples per_sample_shading
                                flag the C++ side leaves at false (the
                                original shadergen relies on the same
                                implicit-per-sample behaviour).

  No spec constants on either blob - there is nothing to specialise.
  The pipeline-state knobs the C++ side cares about (sample count,
  depth state, blend state) are pipeline-creation-time choices, not
  shader-source knobs.

Bindings unchanged: set=0 binding=1 sampler from
m_single_sampler_descriptor_set_layout, no UBO at binding 0 (the
descriptor set layout only declares binding 1; the pipeline layout's
push constants are declared for ABI symmetry with other consumers but
are not read by this shader, and the C++ caller does not push any).

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on both blobs (219 / 242 words,
    0.9 KiB each - the smallest blobs in the project).
  - --target-env vulkan1.0 vs un-flagged glslangValidator: byte-
    identical SPIR-V for both.

m_vram_update_depth_pipeline is on the antialiasing-toggle hot path
(UpdateSettings -> UpdateDepthBufferFromMaskBit at gpu_hw_vulkan.cpp
line ~817). With the preceding fix patch in place, the Disabled-mode
pre-build in CompilePipelines ensures the pipeline is always ready
before UpdateSettings' second cmdbuf starts recording, so the bug
that broke the original patch 5 (lazy build of MSAA depth blob in
the second SSAA toggle cycle, NVIDIA driver producing corrupt next
frame) is structurally impossible here.

Test priority:
  - shader_precompile=Disabled: same SSAA / MSAA round-trip protocol
    Lib used to surface the original patch 5 bug. Toggle SSAA None
    -> 8x -> None -> 8x, MSAA 1 -> 4 -> 1 -> 4, resolution scale
    1 -> 2 -> 1 -> 2, true colour off -> on -> off. Each toggle
    should produce a clean frame.
  - shader_precompile=Enabled / Lazy: routine smoke (any game).

After this lands, every non-batch shader in the Vulkan backend is
pre-baked SPIR-V; the only remaining runtime glslang consumers are
the two batch shaders (GenerateBatchVertexShader and
GenerateBatchFragmentShader at gpu_hw_vulkan.cpp lines ~1462 and
~1799). Those are Bucket B and a separate refactoring effort -
their state space is wide enough to warrant a different conversion
strategy from the per-shader spec-const collapses used here.
2026-05-18 00:38:31 +02:00
LibretroAdmin
427317c2ff core: pre-build hot-path utility pipelines in shader_precompile=Disabled
Three Vulkan utility pipelines are exercised inside UpdateSettings
when a setting change triggers framebuffer recreation (antialiasing
toggle - MSAA, SSAA, per-sample shading - resolution-scale change,
or any other setting that flips m_multisamples / m_resolution_scale
and forces a fresh m_vram_render_pass / m_vram_texture pair):

  - m_vram_readback_pipeline    (ReadVRAM before the cmdbuf drain).
  - m_vram_write_pipelines[0/1] (UpdateVRAM after the new framebuffer
                                 is in place).
  - m_vram_update_depth_pipeline (UpdateDepthBufferFromMaskBit
                                  directly after UpdateVRAM).

Lazy-building any of these inside their respective UpdateSettings
cmdbufs hits an NVIDIA driver quirk that produces corrupted
rendering on the frame immediately after the toggle: on the second
toggle cycle, HUD and background tiles render as blocky / wrong-
colour blocks while the foreground geometry (drawn through the
already-cached batch pipelines) looks correct. shader_precompile
modes Enabled and Lazy already pre-build the full non-batch
pipeline set as part of their startup sequence, so neither hits
this path; only Disabled was deferring these pipelines until the
in-cmdbuf lazy fault.

Fix: in the Disabled branch of CompilePipelines, do a targeted pre-
build of just the three pipelines above (plus the fullscreen-quad
VS they all share). The rest of Disabled's contract is preserved:
batch pipelines stay truly lazy (which is where the bulk of the
init-time cost actually lives), and the other utility pipelines
(VRAM fill / copy / display / downsample / readback for non-toggle
paths) remain lazy too because they are only ever exercised on
game-driven draws - well after the UpdateSettings cmdbuf has been
submitted and a fresh cmdbuf is recording.

Cost: four extra vkCreateGraphicsPipelines calls on the main thread
at boot and on each subsequent setting-change rebuild. Well under
50 ms in aggregate on a desktop GPU; invisible to the user.

Note that this lands as a separate behavioural fix BEFORE the next
embedded-SPIR-V conversion patch in the series (VRAM readback). The
fix is correct on the current shadergen-driven implementation of all
three pipelines too - the NVIDIA quirk is independent of the SPIR-V
source path, and Disabled-mode toggling was already a fragile path
under the original code. Verified by inspection that the existing
Lazy branch comments call out the equivalent pre-fill as 'mandatory,
not an optimisation' for an unrelated reason
(PipelineCacheMutex / std::mutex FIFO interaction with the batch
worker thread); the comment block above the precompile_sync
non-batch loop is updated accordingly.

Smoke tests:
  - g++ -fsyntax-only on src/core/gpu_hw_vulkan.cpp.

Test priority:
  - shader_precompile=Disabled, Tekken 2 (or any game with a
    discernible 2D HUD over 3D geometry): toggle SSAA None -> 8x ->
    None -> 8x, MSAA 1 -> 4 -> 1 -> 4, resolution scale 1 -> 2 -> 1
    -> 2. Each toggle should produce a clean frame on the very next
    draw, with no HUD or background corruption.
  - shader_precompile=Enabled / Lazy: regression check. These paths
    are unchanged structurally (the new code is gated behind the
    Disabled branch of the if/else if/else if ladder); behaviour
    should be byte-identical to before.
2026-05-18 00:30:49 +02:00
LibretroAdmin
cc69fc08e5 common/vulkan, core: pre-bake VRAM readback FS (MSAA blob pair, 1-2 spec consts)
Patch 10 in the glslang-elimination series. The shadergen helper is
named GenerateVRAMReadFragmentShader, but the pipeline it lives in
(m_vram_readback_pipeline) is the CPU readback path: it samples the
upscaled m_vram_texture, runs a box filter to downsample blocks back
to PSX-native 16bpp, and packs two adjacent 16-bit pixels into one
RGBA8 output texel for the host to pick up via staging.

Shader converted:

  VRAMReadFragmentShader. Single output slot, no per-frame variance
  - the existing C++ side already caches it as a single
  m_vram_readback_pipeline VkPipeline. Two blobs only because of the
  source texture's MSAA structural split (sampler2D vs sampler2DMS).

  Blobs:
    vram_readback_fs      - sampler2D, no per-pixel sample averaging.
    vram_readback_msaa_fs - sampler2DMS, LoadVRAM averages
                            MULTISAMPLES texelFetch results before
                            the box filter runs.

  Common spec constant:
    id = 0 RESOLUTION_SCALE (uint) - drives both the base_coords stride
                                     and the box-filter inner-loop
                                     bounds.
  MSAA blob adds:
    id = 1 MULTISAMPLES     (uint) - LoadVRAM averaging loop bound.

The OpenGL lower-left-origin Y-flip branch in the shadergen source is
omitted: Vulkan VRAM Y matches scanout Y directly, so the conditional
fold-up never fires on this backend. The single output pipeline keeps
its single C++ slot - no per-mode array needed.

Render target (m_vram_readback_texture) is always single-sample at
line 1118, so the pipeline's multisample state stays at the default
single-sample on both blobs. As with display, the MSAA-ness lives
entirely in the input sampler type.

Bindings unchanged: push_constant for the UBO, set=0 binding=1 for
the source sampler, matching m_single_sampler_pipeline_layout.

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on both blobs (1158 / 1302
    words, 4.5K / 5.1K).
  - --target-env vulkan1.0 vs un-flagged glslangValidator: byte-
    identical SPIR-V for both.

VRAM readback is the rarest of the utility pipelines - it's exercised
only when something reads from upscaled VRAM through the host (save-
state capture, debugger introspection, certain games that read back
their own framebuffer for special effects). Not on the SSAA-toggle
hot-build path; shader_precompile=Disabled is expected to behave
identically to Enabled / Lazy.

Test priority:
  - shader_precompile=Enabled / Lazy: routine smoke.
  - shader_precompile=Disabled: any savestate save + load round-trip
    (forces a readback). A few games also self-read for visual
    effects - Silent Hill's fog overlay and the Castlevania:
    Symphony of the Night transition flashes are known triggers.
    SSAA round-trip is incidental but quick.

After this lands, the only non-batch shaders still on the runtime
shadergen + glslang path are the VRAM update depth pair, which is on
the SSAA-toggle hot-build path and broke patch 5. Plan for those is
to introduce a targeted pre-build at CompilePipelines time even in
Disabled mode, separately from the SPIR-V conversion itself.
2026-05-18 00:16:58 +02:00
LibretroAdmin
59b6fac749 common/vulkan, core: pre-bake display FS (MSAA blob pair, 5-6 spec consts)
Patch 9 in the glslang-elimination series. The display FS is the
densest shader in the project - shadergen takes depth_24bit (bool) x
interlace_mode (None/InterleavedFields/SeparateFields) x smooth_chroma
(bool) source variants, and the source m_vram_texture's sample count
varies with MSAA on top of that. The depth_24bit / interlace_mode pair
is the only knob set that varies at runtime within a session
(GPUSTAT.display_area_color_depth_24 and the CRTC interlace mode flip
during normal gameplay); smooth_chroma, MSAA, and RESOLUTION_SCALE are
all session-constant (toggling any of them goes through UpdateSettings
-> DestroyPipelines).

Shader converted:

  DisplayFragmentShader. Reads the upscaled m_vram_texture, applies
  field-discard for interlaced output, and writes the visible scanout
  rectangle to m_display_texture - either as direct 16bpp samples or as
  reconstructed 24bpp YUV-smoothed colour depending on the GPUSTAT bit.

  Blobs:
    display_fs       - source sampler is sampler2D       (non-MSAA path).
    display_msaa_fs  - source sampler is sampler2DMS, plus an extra
                       MULTISAMPLES spec constant for the LoadVRAM
                       averaging loop bound.

  Common spec constants on both blobs:
    id =   0 RESOLUTION_SCALE (uint) - common-knob convention.
    id = 100 DEPTH_24BIT      (bool) - 16bpp vs 24bpp reconstruction.
    id = 101 INTERLACED       (bool) - field-discard logic gate.
    id = 102 INTERLEAVED      (bool) - only meaningful when INTERLACED.
                                       Selects interleaved-both-fields
                                       coord folding vs separate-field.
    id = 103 SMOOTH_CHROMA    (bool) - only meaningful when DEPTH_24BIT.
                                       Enables bilinear UV smoothing.

  MSAA blob adds:
    id =   1 MULTISAMPLES     (uint) - common-knob convention.

The m_display_pipelines[depth_24][interlace_mode] 2x3 slot table is
preserved; each entry gets its own spec-const-specialised pipeline at
first-touch, like the VRAM fill pattern. interlace_mode is folded into
INTERLACED / INTERLEAVED at the call site:
  None              -> INTERLACED=false, INTERLEAVED=*  (INTERLEAVED
                                                         irrelevant when
                                                         INTERLACED is
                                                         false)
  InterleavedFields -> INTERLACED=true,  INTERLEAVED=true
  SeparateFields    -> INTERLACED=true,  INTERLEAVED=false

The render target (m_display_texture) is always single-sample at this
stage (line 1114 hardcodes VK_SAMPLE_COUNT_1_BIT regardless of MSAA);
the pipeline's multisample state is therefore single-sample on both
blobs, matching the original which did not call SetMultisamples either.
The MSAA-ness lives entirely in the input sampler type and the LoadVRAM
loop on the MSAA blob.

Bindings unchanged: push_constant for the UBO, set=0 binding=1 for the
source sampler, matching m_single_sampler_pipeline_layout.

The fixYCoord call from the original shadergen is dropped because the
Vulkan-side fixYCoord is the identity function (PSX VRAM Y matches
Vulkan Y); removing it spares a redundant function definition. The
GLSL-side helper macros (float4 / uint2 / etc) from WriteHeader are
also dropped since the .glsl files only need to work for Vulkan and
GLSL-native types are clearer than HLSL-style aliases.

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on both blobs (2391 / 2535
    words, 9.5K / 9.9K).
  - --target-env vulkan1.0 vs un-flagged glslangValidator: byte-
    identical SPIR-V for both blobs.

Like VRAM fill / copy / write, the display pipeline is built on its
own first-touch path and is not on the UpdateSettings SSAA-toggle
hot-build path. shader_precompile=Disabled is expected to behave
identically to Enabled / Lazy.

Test priority:
  - shader_precompile=Enabled / Lazy: routine smoke (any game).
  - shader_precompile=Disabled: any game that flips interlace_mode
    during gameplay (interlaced cutscenes -> progressive gameplay
    transitions) or that toggles 24bpp display mode (FMV intros in
    most JRPGs). Smooth-chroma path is exercised by enabling the
    Chroma Smoothing 24-bit option in the core options and watching
    an FMV. Worth doing a coarse SSAA round-trip too even though the
    display pipeline shouldn't be sensitive to it.
2026-05-18 00:02:50 +02:00
LibretroAdmin
30793791f8 common/vulkan, core: pre-bake VRAM write FS (SSBO + texbuf blob pair)
Patch 8 in the glslang-elimination series. VRAM write has a structural
variant the rest of Bucket A has not had to deal with: the descriptor
type at set=0 binding=0 differs depending on
m_use_ssbos_for_vram_writes (storage buffer vs uniform texel buffer),
so a single SPIR-V blob with a spec constant cannot collapse it. Two
blobs, otherwise sharing the same spec-constant interface.

Shader converted:

  VRAMWriteFragmentShader. Writes one upscaled PSX pixel per fragment
  from a host-staged 16-bit-per-pixel VRAM tile.

  Blobs:
    vram_write_ssbo_fs   - readonly restrict std430 SSBO ssbo_data[],
                           two PSX pixels packed per uint32 element.
    vram_write_texbuf_fs - uniform usamplerBuffer samp0 with R16_UINT
                           buffer view, one PSX pixel per element.

  Spec constants (identical between the two blobs):
    id = 0  RESOLUTION_SCALE (uint) - common-knob convention. Drives
                                      both the upscale-aware coord
                                      conversion (gl_FragCoord.xy
                                      divided by RESOLUTION_SCALE) and
                                      the VRAM_SIZE wrap-around math.
    id = 3  PGXP_DEPTH       (bool) - common-knob convention. Selects
                                      between sampled-alpha-derived
                                      depth and a fixed 1.0.

The depth_test pipeline knob remains a SetDepthState toggle, not a
spec constant; the C++ side keeps the 2-entry slot lookup in
m_vram_write_pipelines and selects the SSBO-vs-texbuf blob inside the
slot miss path. m_use_ssbos_for_vram_writes is a per-session decision
(set in CompilePipelines based on device features), so in any given
session only one of the two blobs will ever be touched at
vkCreateShaderModule time.

Inlined the RGBA5551ToRGBA8 helper directly into both .glsl files
rather than relying on what WriteCommonFunctions would have emitted -
keeps each blob self-contained and avoids dragging in the other
WriteCommonFunctions helpers (fixYCoord, RGBA8ToRGBA5551) that are not
used here. The Vulkan-side fixYCoord is the identity function in any
case.

Bindings unchanged from the shadergen path - both blobs target
m_vram_write_pipeline_layout, which is constructed with the matching
descriptor type at CreateLayouts time.

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on both blobs (1433 / 1356 words).
  - --target-env vulkan1.0 vs un-flagged glslangValidator: byte-
    identical SPIR-V for both.

Like patches 6 and 7, VRAM write is exercised by game-driven VRAM
uploads, not by UpdateSettings, so this pipeline does not see the
SSAA-toggle lazy-build path. shader_precompile=Disabled is expected to
match Enabled / Lazy behaviour.

Test priority:
  - shader_precompile=Enabled / Lazy: routine smoke (any game).
  - shader_precompile=Disabled: any game with heavy texture streaming
    over CPU-side DMA - JRPG cutscenes, pre-rendered backgrounds,
    movie-frame VRAM uploads. The SSBO blob is the common one on
    desktop GPUs; the texbuf blob may be exercised by retesting on
    something with the SSBO path disabled.
2026-05-17 23:46:01 +02:00
LibretroAdmin
34cda08c7a common/vulkan, core: pre-bake VRAM copy FS (single blob, 2 spec consts)
Patch 7 in the glslang-elimination series. VRAM copy is the simplest
remaining shader from the original shadergen-driven set: the source-side
has no MSAA variant (the shadergen hard-codes msaa=false at the top of
GenerateVRAMCopyFragmentShader because Vulkan won't let us bind the
source texture to both an input sampler and a colour attachment), so
unlike VRAM read / update-depth we collapse to a single SPIR-V blob with
just two spec constants.

Shader converted:

  VRAMCopyFragmentShader. Copies a rectangular region from one part of
  upscaled VRAM to another, with PSX-style modulo-1024x512-VRAM wrap-
  around at the destination and optional mask-bit writeback.

  Spec constants used (documented in the .glsl):
    id = 0  RESOLUTION_SCALE (uint) - common-knob convention.
    id = 3  PGXP_DEPTH       (bool) - common-knob convention.

  No MSAA spec const; no shader-specific spec consts. The depth_test
  state knob the C++ side cares about is a SetDepthState pipeline-state
  toggle, not a shader knob, so it stays as a 2-entry slot lookup in
  m_vram_copy_pipelines and does not factor into spec constants.

Bindings unchanged: push_constant block for the UBO, set=0 binding=1 for
the source sampler2D, matching m_single_sampler_pipeline_layout.

Smoke tests:
  - g++ -fsyntax-only on the touched common TU.
  - spirv-val --target-env vulkan1.0 on the regenerated blob (1203
    words, 4.7 KiB).
  - Verified --target-env vulkan1.0 produces byte-identical SPIR-V to
    the un-flagged glslangValidator default (relevant since the runtime
    glslang path does not call setEnvTarget; both paths emit the same
    bytes for our shaders).

Like patch 6, this pipeline is not on the SSAA-toggle hot path - VRAM
copy is exercised by game-driven VRAM-to-VRAM blits, not by
UpdateSettings. shader_precompile=Disabled is therefore expected to
behave identically to Enabled / Lazy for this pipeline.

Test priority:
  - shader_precompile=Enabled / Lazy: routine smoke (any game).
  - shader_precompile=Disabled: any game that performs frequent VRAM
    copies (Final Fantasy series, anything with prerendered backgrounds
    streamed into VRAM). SSAA toggle round-trip should be fine.
2026-05-17 22:57:44 +02:00
LibretroAdmin
af9c287efb common/vulkan, core: pre-bake VRAM fill FS (single blob, 8 specialisations)
Patch 6 in the glslang-elimination series. Demonstrates the
'multiple-spec-constants-collapse-source-variants' pattern: the original
shadergen produced four GLSL source strings (wrapped x interlaced) and
a per-session constructor-level PGXP_DEPTH bake, for up to eight cached
SPIR-V blobs on the disk-backed cache. This patch collapses all of that
into a single SPIR-V blob with three boolean specialisation constants.

Shader converted:

  VRAMFillFragmentShader. Writes u_fill_color to a destination rectangle
  in upscaled VRAM, optionally discarding pixels for interlace masking
  or out-of-bounds-wrapped fills.

  Spec constants used (documented in the .glsl):
    id =   3 PGXP_DEPTH  (bool, common-knob convention).
    id = 100 INTERLACED  (bool, shader-specific).
    id = 101 WRAPPED     (bool, shader-specific).

  Cross-shader id reuse note: id=100 is also FIRST_PASS in
  adaptive_downsample_mip.frag.glsl. SPIR-V spec scopes spec-constant
  ids per-stage, so reuse across different shaders is harmless. Each
  shader file documents its own ids at the top.

Call site changes in src/core/gpu_hw_vulkan.cpp:

- GetVRAMFillPipeline: switched to embedded path. The 'wrapped' and
  'interlaced' uint8 inputs (each 0 or 1) now drive AddBool calls into
  the SpecConstants helper rather than picking a GLSL source string.
  PGXP_DEPTH is sourced from GPU_HW::m_pgxp_depth_buffer. m_shadergen
  null-check removed.

  Pipeline cache shape unchanged: m_vram_fill_pipelines[wrapped][interlaced]
  still gives a 2x2 grid of distinct VkPipeline handles, since
  specialisation is per-pipeline. (A future patch could fold this into
  one VkPipeline per visible PGXP_DEPTH state if pipeline-create cost
  becomes a measurable burden, but that's a different optimisation;
  current state matches the pre-patch pipeline count.)

Notes on spec-const evaluation:

- The dst_coords uvec2 conversion at the top of main() is always
  computed in the SPIR-V even when neither INTERLACED nor WRAPPED is
  taken. The driver's optimiser is expected to dead-code-eliminate it
  at vkCreateGraphicsPipelines time once both spec constants are bound
  to false; spirv-dis on the non-specialised blob shows the IR allows
  this. If a driver doesn't optimise it the cost is negligible (a few
  ALU ops per fragment).

- gl_FragDepth = PGXP_DEPTH ? 1.0 : u_fill_color.a translates to an
  OpSelect on a spec-constant condition. After specialisation the
  OpSelect collapses to one of its two operands; modern drivers do
  this fold during pipeline compile.

Cumulative state after this patch:

- 14 of ~25-30 Bucket A blob variants converted (counting this single
  blob with eight specialisations as one blob - the on-disk pipeline
  cache shape across the four wrapped x interlaced combos and two
  PGXP states is what matters operationally, and that remains 4-or-8
  distinct VkPipelines as before).
- Spec-constant infrastructure exercised with 3 booleans driving
  source-level variants - the densest specialisation use so far.
- First use of constant_id=3 (PGXP_DEPTH common knob).
- Remaining Bucket A: VRAM copy FS (MSAA pair + spec consts),
  VRAM write FS (SSBO vs uniform-buffer pair + spec consts),
  Display FS (the densest one).

Smoke tests in the sandbox:

- vram_fill_fs.inc reconstructs to SPIR-V that passes
  spirv-val --target-env vulkan1.0.
- spirv-dis confirms three SpecId decorations (3, 100, 101) on three
  separate OpSpecConstantFalse %bool entries.
- g++ -fsyntax-only on embedded_shaders.cpp is clean.

Smoke tests at user's end:

- VRAM fill is exercised heavily during VRAM-to-VRAM copies and
  initial framebuffer clears at game boot. Cold-boot with cache nuked
  at scales 1x and 4x, run any game past the first few frames.
  Wrong behaviour in the INTERLACED branch would show as missing
  every-other-line in interlaced video modes (most visible in some
  PSX RPG cutscenes). Wrong behaviour in the WRAPPED branch would
  cause incorrect VRAM-to-VRAM rectangles in games that DMA between
  overlapping regions.

- Toggle PGXP Depth Buffer on/off at runtime. This forces a
  pipeline destroy + rebuild with the new spec-constant value for
  PGXP_DEPTH (id=3). If the spec const isn't being re-applied on
  rebuild, the depth output stays at the old value across the
  toggle - visually that means correct-vs-broken depth ordering in
  PGXP-affected games (Tekken 3 is a known fixture for this).

- The four wrapped/interlaced combinations are exercised by
  oversized VRAM fills and by interlaced-video games respectively.
  At least one of each in normal gameplay should hit a code path
  that runs through every spec-const combination.
2026-05-17 22:51:37 +02:00
LibretroAdmin
bc2776687f common/vulkan, core: pre-bake adaptive composite + box-sample downsample FS
Patch 4 in the glslang-elimination series. Completes the downsample
subsystem: all four downsample pipeline build paths in
src/core/gpu_hw_vulkan.cpp now use embedded SPIR-V. This patch is the
first to plumb the common-knobs spec constant (RESOLUTION_SCALE at
constant_id=0), establishing the project-wide pattern for the
larger remaining utility shaders.

Shaders converted by this patch:

1. AdaptiveDownsampleCompositeFragmentShader. The runtime-baked
   RESOLUTION_SCALE used to derive RCP_VRAM_SIZE = 1/(VRAM_SIZE) and a
   mip-level multiplier '(RESOLUTION_SCALE - 1)'. Both are now SPIR-V
   OpSpecConstantOp arithmetic chained from the constant_id=0 input;
   the driver folds them to literals at vkCreateGraphicsPipelines time
   once GPU_HW_Vulkan::m_resolution_scale is bound. Reads two textures
   at bindings 1 and 2 (matching ShaderGen's 'index + 1' convention
   for Vulkan).

2. BoxSampleDownsampleFragmentShader. Same RESOLUTION_SCALE spec
   constant, used three ways: in 'base_coords = gl_FragCoord *
   uvec2(RESOLUTION_SCALE, RESOLUTION_SCALE)' (OpSpecConstantComposite),
   in the inner loop bounds 'offset < RESOLUTION_SCALE', and in the
   final divisor 'color /= RESOLUTION_SCALE * RESOLUTION_SCALE'
   (OpSpecConstantOp IMul). Whether the loop unrolls is left to the
   driver; this matches the original runtime path's behaviour where
   GLSL frontend often unrolled the bound-as-literal version. At
   extreme RESOLUTION_SCALE=16 the inner body runs 256 times either
   way.

GLSL constraint discovered (documented in the composite shader for
future contributors): glslangValidator rejects spec-const-derived
expressions at global 'const' scope - 'global const initializers must
be constant'. The workaround is to compute the derived value inside
main() as a regular vec2; the SPIR-V will then contain runtime
ALU ops chained from the OpSpecConstant rather than the cleaner
OpSpecConstantOp form, but the driver constant-folds either at
specialisation time.

Call site changes in src/core/gpu_hw_vulkan.cpp:

- GetDownsampleCompositePassPipeline: switched to embedded blob with
  RESOLUTION_SCALE spec const. m_shadergen null-check dropped (it
  was only there for the glslang path).

- GetDownsampleFirstPassPipeline (Box branch): switched to embedded
  blob with RESOLUTION_SCALE spec const. m_shadergen null-check that
  patch 3 had left inside this branch is now also removed - both
  branches of this function are fully pre-baked. The comment block
  at function entry is updated to reflect the new state.

Cumulative state after this patch:

- 9 of ~25-30 Bucket A variants converted. The entire downsample
  subsystem (4 pipelines: Adaptive first-pass, mid-pass, blur,
  composite, plus Box first-pass) is now glslang-free.
- Spec constant infrastructure exercised on its second-stage use
  case: a numeric uint (RESOLUTION_SCALE) rather than a bool
  (FIRST_PASS from patch 3). Confirms the
  OpSpecConstant/OpSpecConstantOp paths through the SpecConstants
  helper work for both flavours.
- Remaining Bucket A: VRAM read FS, VRAM update-depth FS (both
  trivial - just need MULTISAMPLES + possibly an MSAA-vs-not blob
  pair), VRAM copy FS (MSAA blob pair + RESOLUTION_SCALE +
  PGXP_DEPTH), VRAM write FS (SSBO vs uniform-buffer blob pair +
  RESOLUTION_SCALE), VRAM fill FS (RESOLUTION_SCALE + PGXP_DEPTH +
  WRAPPED + INTERLACED), Display FS (the multi-variant one).

Smoke tests in the sandbox:

- Both new .inc files reconstruct to SPIR-V that passes
  'spirv-val --target-env vulkan1.0'.
- spirv-dis on the composite FS confirms 'OpDecorate %RESOLUTION_SCALE
  SpecId 0' and 'OpSpecConstantOp %uint ISub %RESOLUTION_SCALE
  %uint_1' for the mip-level multiplier.
- spirv-dis on the box-sample FS confirms 'OpDecorate
  %RESOLUTION_SCALE SpecId 0', 'OpSpecConstantComposite %v2uint'
  for the base_coords scaling, and 'OpSpecConstantOp %uint IMul' for
  the final divisor.
- g++ -fsyntax-only on embedded_shaders.cpp against the real tree
  headers is clean.

Smoke tests at user's end:

- Cold-boot with shader cache nuked, downsample mode = Adaptive at
  several resolution scales (1x, 4x, 8x, ideally 16x). The composite
  pipeline now drives a spec-constant for RESOLUTION_SCALE; if the
  plumbing is wrong, the downsampled output will be either at the
  wrong scale (mip 0 used everywhere -> overly sharp) or at the
  maximum mip everywhere (overly blurry). Both modes should be
  visually unchanged from the patch-3 baseline.
- Cold-boot with cache nuked, downsample mode = Box, same scales.
  Box-sample now also takes the spec constant; if mis-plumbed at
  scale > 1 the output will be all-black (loop runs 0 times if
  RESOLUTION_SCALE = 0 in SPIR-V) or wildly wrong colors (if the
  averaging divisor is wrong).
- Toggle resolution scale at runtime (which triggers pipeline
  destroy + rebuild). Confirms the SpecConstants helper correctly
  re-specialises on each build with the new m_resolution_scale
  value. This is the test most likely to catch a 'spec value latched
  on first build and never updates' bug, if one exists.
2026-05-17 20:49:05 +02:00
LibretroAdmin
6727587113 common/vulkan, core: spec-constant infrastructure + adaptive downsample mip/blur pre-bake
Patch 3 in the glslang-elimination series. Introduces the specialization-
constant plumbing that subsequent patches need, and applies it to two
adaptive-downsample shaders that demonstrate both the no-spec-const and
the with-spec-const paths through the new infrastructure.

Infrastructure additions:

- Vulkan::SpecConstants class in builders.{h,cpp}. A small builder that
  owns a VkSpecializationMapEntry array and a 4-byte-per-slot payload
  buffer, exposing AddBool/AddUInt/AddInt/AddFloat by constant_id. The
  consumer typically declares a SpecConstants on the same stack frame
  as the GraphicsPipelineBuilder, fills it, and passes GetInfo() to
  SetVertexShader / SetFragmentShader. GetInfo() returns nullptr if no
  entries have been added (equivalent to no specialization info), so
  the same code path can serve both spec-const and non-spec-const
  shaders without conditionals at the call site.

  Up to MAX_ENTRIES (16) constants per stage; AddBool stores the
  value as a 4-byte word (1 for true, 0 for false) per the Vulkan
  spec-constant ABI. Larger types (vec4, double) intentionally not
  supported - no current shader needs them; can be added later if
  the batch shaders end up needing wider values.

- GraphicsPipelineBuilder::SetVertexShader and ::SetFragmentShader now
  take an optional 'const VkSpecializationInfo*' that defaults to
  nullptr. All 36 existing call sites continue to compile unchanged
  via the default. SetShaderStage is also extended; in addition to
  threading spec_info through it now explicitly clears pNext, flags,
  and pSpecializationInfo on every call. The builder is sometimes
  reused across pipelines without an intervening Clear() (e.g. the
  display / cursor pair in LibretroVulkanHostDisplay::CreateResources),
  so a stale spec_info pointer or flags bit could previously leak from
  one pipeline build into the next. Latent issue pre-existing this
  patch; fixed defensively because the new code path exercises it.

Spec-constant ID allocation convention (documented in the SpecConstants
class header and adhered to project-wide):

    0-99    common knobs (RESOLUTION_SCALE, MULTISAMPLES,
            PER_SAMPLE_SHADING, PGXP_DEPTH) - to be plumbed by patch 4.
    100+    shader-specific; e.g. FIRST_PASS for the adaptive-downsample
            mip FS in this patch.

Shaders converted by this patch:

1. AdaptiveDownsampleBlurFragmentShader (no spec constants). One
   SPIR-V blob, replaces GetDownsampleBlurPassPipeline's runtime
   glslang call. Establishes that the embedded path works alongside
   the spec-constant path - the call site is identical to a patch-1
   or patch-2 conversion.

2. AdaptiveDownsampleMipFragmentShader. The 'first_pass' bool that
   previously produced two distinct GLSL source strings (and so two
   cached SPIR-V blobs) is now a single 'bool FIRST_PASS' spec
   constant at constant_id=100. ONE SPIR-V blob serves both
   GetDownsampleFirstPassPipeline (Adaptive branch) with
   FIRST_PASS=true, and GetDownsampleMidPassPipeline with
   FIRST_PASS=false. The branch is preserved as a runtime 'if'; the
   driver's SPIR-V optimizer drops the dead arm at vkCreateGraphics
   Pipelines time because the bool is a compile-time constant in
   that context.

   spirv-dis on the blob confirms 'OpDecorate %FIRST_PASS SpecId 100'
   and 'OpSpecConstantFalse %bool' are emitted as expected.

Other changes in gpu_hw_vulkan.cpp:

- GetDownsampleFirstPassPipeline: m_shadergen null-check moved from
  function entry into the Box branch (which still uses
  GenerateBoxSampleDownsampleFragmentShader at runtime). The Adaptive
  branch no longer needs the check - pre-baked SPIR-V doesn't depend
  on shadergen.
- GetDownsampleMidPassPipeline and GetDownsampleBlurPassPipeline:
  m_shadergen null-checks removed entirely - both are Adaptive-only
  (early-return on non-Adaptive) and now fully pre-baked.

Cumulative state after this patch:

- 7 of ~25-30 Bucket A variants converted (1 in patch 1, 4 in patch 2,
  2 in this patch; the mip FS is one source but two specializations).
- Spec-constant infrastructure ready for patches 4+ to plumb
  RESOLUTION_SCALE / MULTISAMPLES / PGXP_DEPTH into the remaining
  utility shaders.
- glslang and the runtime ShaderGen path still in the tree, still used
  by every Vulkan path not yet converted (batch shaders, remaining
  utility shaders, Box downsample, all GL/D3D backends).

Smoke tests in the sandbox:

- Both new .inc files reconstruct to SPIR-V that passes
  spirv-val --target-env vulkan1.0.
- spirv-dis on the mip FS confirms the OpDecorate SpecId 100 +
  OpSpecConstantFalse pair.
- g++ -fsyntax-only on both modified TUs (builders.cpp,
  embedded_shaders.cpp) is clean; the only warnings are two
  pre-existing unused-parameter warnings in SamplerBuilder::Create
  and BufferViewBuilder::Create, unchanged by this patch.

Smoke tests at user's end:

- Cold-boot with the shader cache nuked and the downsample mode set
  to Adaptive. All three Adaptive pipelines must succeed; the visual
  output should be byte-identical to the pre-patch baseline (same
  algorithm, same texture binds, just specialized SPIR-V instead of
  hand-rolled GLSL).
- Same cold-boot test with Box mode is also useful - it exercises
  that the Box branch in GetDownsampleFirstPassPipeline still works
  via the runtime-glslang path (regression check on the m_shadergen
  null-check relocation).
2026-05-17 20:39:19 +02:00
LibretroAdmin
64c9adaca8 common/vulkan, core: pre-bake UV-quad VS and three presentation-stage shaders
Patch 2 in the glslang-elimination series (probe was 2cbcefc). Converts
four more shaders to the pre-baked SPIR-V path established in the probe.
No new infrastructure - each blob just adds an extern pair to
embedded_shaders.h, a #include inside the namespace block in
embedded_shaders.cpp, and a call-site swap. The probe pattern handles
N=5 blobs as cleanly as it handled N=1.

Shaders converted by this patch:

1. UV-quad vertex shader (GPU_HW_Vulkan::GetUVQuadVertexShader, the
   variant of the screen-quad that maps the swept triangle into a
   [u_uv_min..u_uv_max] UV rect from a push constant). The runtime
   equivalent is ShaderGen::GenerateUVQuadVertexShader().

2. Presentation-stage fullscreen-quad VS - the one with the u_src_rect
   push constant, distinct from the GPU_HW screen quad. Used only by
   LibretroVulkanHostDisplay to blit the rendered frame and the
   software cursor into the libretro framebuffer.

3. Presentation-stage display FS - writes the source texture opaque.

4. Presentation-stage cursor FS - preserves source alpha for blending.

Shaders 2-4 previously lived as inline R"()" string literals at the
top of LibretroVulkanHostDisplay::CreateResources() in
src/core/gpu_hw_vulkan.cpp. They are now in data/shaders/vulkan/ with
matching pre-compiled SPIR-V under src/common/vulkan/embedded_spirv/.
The C++-side pipeline layout (16-byte u_src_rect push constant, single
combined image sampler at set 0 / binding 0) is unchanged, so no
descriptor or push-constant byte-layout coordination is needed.

Cumulative state after this patch:

- 5 of ~25-30 utility-shader variants in Bucket A converted.
- glslang is still in dep/ and still in the build - it is needed by
  every shader generator not yet converted, in particular all of
  GPU_HW_ShaderGen plus the remaining utility shaders that bake
  RESOLUTION_SCALE / MULTISAMPLES / PGXP_DEPTH into source via
  WriteCommonFunctions. The next patch in the series introduces
  specialization-constant infrastructure in GraphicsPipelineBuilder so
  those constants can be moved out of GLSL into SPIR-V OpSpecConstant,
  enabling the rest of Bucket A.

Smoke tests in the sandbox:

- All 5 .inc files reconstruct to SPIR-V that passes
  'spirv-val --target-env vulkan1.0'.
- spirv-dis confirms each blob's entry point, descriptor bindings, and
  push-constant block match the call-site expectations.
- g++ -fsyntax-only on embedded_shaders.cpp against the real tree
  headers is clean.

Smoke tests at user's end:

- Cold-boot the Vulkan backend with the disk shader cache nuked. The
  three presentation-stage pipelines build during
  LibretroVulkanHostDisplay::CreateResources(); the UV-quad VS is
  faulted in lazily by any of the three adaptive-downsample pipeline
  paths (line ~2284 in gpu_hw_vulkan.cpp post-patch). All four must
  succeed for the emulator to reach a first frame.
- A second cold boot (same nuke) verifies the embedded path is
  reproducibly correct, not relying on any leftover state.
2026-05-17 20:23:11 +02:00
LibretroAdmin
2cbcefcff6 common/vulkan, core: pre-bake screen-quad VS, no glslang at runtime
This is the probe patch in a series that eliminates dep/glslang from the
libretro core build. It establishes the infrastructure - the GLSL source
tree, the embedded-SPIR-V loader, the regeneration tool, and the build
wiring - by converting exactly one call site so the pattern can be
smoke-tested in isolation before the rest of Bucket A and then Bucket B
follow in subsequent patches. glslang stays in the tree until the final
patch in the series, which removes dep/glslang and the surrounding
shader_compiler.cpp.

What this patch does:

- Adds data/shaders/vulkan/screen_quad.vert.glsl - the GLSL source for
  the screen-quad VS, kept in the tree for human readability. The build
  does NOT see this file; it is consumed only by the offline regen tool.

- Adds src/common/vulkan/embedded_spirv/screen_quad_vs.inc - the
  pre-compiled SPIR-V blob as a 'const uint32_t[]' (367 words, 1.4 KiB),
  generated offline from the .glsl by glslangValidator targeting
  vulkan1.0. The .inc is checked in and #include'd by embedded_shaders.cpp
  inside namespace Vulkan::EmbeddedShaders. spirv-val confirms the blob
  is valid Vulkan 1.0 SPIR-V (magic 0x07230203, version 1.0).

- Adds src/common/vulkan/embedded_shaders.{h,cpp}. The header exposes a
  pair of extern declarations per blob and a single
  CreateShaderModule(const uint32_t*, size_t) loader. The loader
  intentionally bypasses Vulkan::ShaderCache - pre-baked SPIR-V is
  already final, so there is nothing to compile and nothing worth
  caching on disk. Just a sized-and-checked vkCreateShaderModule call.

- Adds tools/regen_vulkan_spirv.py - the offline workflow for
  contributors who edit shader .glsl sources. It invokes
  glslangValidator on each .glsl under data/shaders/vulkan/ and rewrites
  the matching .inc. CRITICAL: this tool is NEVER invoked by Make or
  CMake. The build sees only .h/.cpp/.inc files and has no shader-
  compiler dependency. Contributors run the script manually after
  editing .glsl, commit both files together.

- Adds data/shaders/vulkan/README.md documenting the workflow and the
  invariant that the build must never invoke an external shader
  compiler.

- Switches GPU_HW_Vulkan::GetFullscreenQuadVertexShader() (in
  src/core/gpu_hw_vulkan.cpp) from
      g_vulkan_shader_cache->GetVertexShader(m_shadergen->Generate...)
  to
      Vulkan::EmbeddedShaders::CreateShaderModule(k_screen_quad_vs, ...).
  The m_shadergen null-check is removed since the embedded path has no
  such ordering dependency. The function's contract (lazy creation,
  stored in m_fullscreen_quad_vertex_shader, returned to multiple
  pipeline builders) is unchanged.

- Registers src/common/vulkan/embedded_shaders.cpp in both
  Makefile.libretro (alphabetical order in the vulkan/ SOURCES_CXX
  block) and src/common/CMakeLists.txt (alphabetical order in the
  common target's source list). Neither change adds any build-tool
  dependency; the new .cpp compiles like any other.

What this patch does NOT do:

- It does not remove dep/glslang or the SOURCES_CXX entries that pull
  in its 99 translation units. glslang is still needed for every shader
  generator that has not yet been converted - in particular all of
  GPU_HW_ShaderGen, plus the remaining utility shaders (UV quad VS,
  VRAM read/copy/write/fill/update-depth FS, display FS, adaptive
  downsample mip/blur/composite FS, box-sample downsample FS).
  Subsequent patches in this series convert those one bucket at a time.
  The final patch removes dep/glslang, src/common/vulkan/shader_compiler.{h,cpp},
  the glslang link line in CMake, and the Makefile entries.

- It does not touch the disk-backed Vulkan::ShaderCache. That cache
  still serves the runtime-glslang path for remaining shaders.

Smoke tests performed in isolation:

- glslangValidator --target-env vulkan1.0 succeeds on the .glsl source,
  producing 367 32-bit words of SPIR-V.
- spirv-val --target-env vulkan1.0 reports VALID on the blob.
- spirv-dis confirms the entry point, VertexData block, and Position/
  VertexIndex built-ins are correctly emitted.
- A standalone harness including the .inc inside the
  Vulkan::EmbeddedShaders namespace and calling CreateShaderModule
  through a stubbed vkCreateShaderModule reads back the correct magic
  word and size.
- g++ -fsyntax-only on embedded_shaders.cpp against the real headers
  in the tree (excluding only the platform-specific X11 surface define
  not used by this TU) is clean.

Smoke tests that require the user's setup:

- Real build on Windows (RTX 5090) and macOS.
- Vulkan core boots, RetroArch's pipeline cache populates, and at
  least one game renders past the first frame using the screen-quad
  pipeline (VRAM ops, display, downsample - all of which call
  GetFullscreenQuadVertexShader internally).
2026-05-17 20:09:57 +02:00
LibretroAdmin
f5feac555a core, common/d3d12: revive on-disk PSO cache via ID3D12PipelineLibrary
# Background

Commit 81e3a2b8 dropped the per-PSO disk cache because the previous
implementation had the wrong granularity - each cached PSO blob
carried its own copy of the embedded VS+PS bytecode, producing
~75 MB on disk for a fully populated session with no meaningful
cold-start benefit. The comment in shader_cache.cpp explicitly
flagged ID3D12PipelineLibrary (D3D12.1, Windows 10 v1703+) as the
right replacement: a single driver-managed blob that internally
dedupes shader bytecode across PSOs, comparable in size to the
existing ~5 MB shader bytecode cache.

This change wires up that path. It does NOT undo the 81e3a2b8 drop -
the per-PSO blob cache stays gated off via m_use_pipeline_cache and
its scrub-on-Open logic stays in place. The pipeline library is a
parallel, independently-gated mechanism behind m_use_pipeline_library.

# Runtime detection

ShaderCache::Open now takes an ID3D12Device*. Inside Open we
QueryInterface for ID3D12Device1 - present on Windows 10 v1703+
(April 2017). On success, m_use_pipeline_library is set true and
the library path is used. On a pre-D3D12.1 device or any failure,
m_use_pipeline_library stays false and behaviour reverts to the
current (post-81e3a2b8) "no PSO cache" path.

# Behaviour change

For a session on D3D12.1-capable hardware:

  GetPipelineState first calls LoadGraphicsPipeline on the library
  with a deterministic 32-wchar hex name derived from the existing
  CacheIndexKey hash. On hit: returns a PSO in microseconds, no
  D3DCompile, no CreateGraphicsPipelineState. On miss: compiles
  fresh via CreateGraphicsPipelineState (same as today), then
  best-effort StorePipeline. StorePipeline returning E_INVALIDARG
  (race loser, name already exists) is expected and ignored.

  At session end, ~ShaderCache calls GetSerializedSize +
  Serialize and writes atomically (.tmp + filestream_rename) to
  d3d12_pipeline_library_sm50.bin. Library invalidation on driver
  update returns D3D12_ERROR_DRIVER_VERSION_MISMATCH from
  CreatePipelineLibrary at the next Open; we delete the file and
  recreate empty.

# Effect

Per CompilePipelines walk through the batch matrix (after the
reachability skip from 19b118b):

  Enabled mode cold start: ~1-2 s (was ~52 s on dual-source
    hardware). The library load + ~1040 LoadGraphicsPipeline hits
    replace ~1040 CreateGraphicsPipelineState calls.
  Lazy mode: worker walk completes ~50 s sooner. User-invisible
    (already playing) but pollutes m_batch_pipeline_states less
    quickly.
  Disabled mode: first-draw stutter eliminated. Every cell's
    first fault was a ~50 ms CreateGraphicsPipelineState compile;
    becomes a microsecond LoadGraphicsPipeline. Disabled becomes
    "instant startup, no stutter, no upfront cost" - now a viable
    default for users who want minimum disk usage and quickest
    in-game-arrival.

Disk footprint: comparable to the existing ~5 MB shader bytecode
cache; not the 75 MB the dropped per-PSO cache reached. The library
internally shares VS+PS bytecode across PSOs that reference the
same shader source, which is most of the batch matrix.

# Lock-free property preserved

ID3D12PipelineLibrary methods (LoadGraphicsPipeline, StorePipeline,
Serialize) are documented thread-safe by Microsoft. No cache mutex
is held across either Load or Create, so the parallel-compile
property from 75e8269 (the D3D12 lazy non-batch PSO commit) and
the broader f46be3e-family lock-free-compile pattern continue to
hold. The Lazy worker can race the main thread on any (name,
desc) cell and the library's own race-loser handling on
StorePipeline is correct.

# mingw-w64 header compatibility

The MinGW-w64 d3d12.h ships only the CreatePipelineLibrary method
signature on ID3D12Device1 - the ID3D12PipelineLibrary interface
itself, plus D3D12_ERROR_DRIVER_VERSION_MISMATCH and
D3D12_ERROR_ADAPTER_NOT_FOUND, are missing. New header
src/common/d3d12/pipeline_library_compat.h provides them under
the standard __ID3D12PipelineLibrary_INTERFACE_DEFINED__ guard,
matching the published Microsoft spec. On toolchains that DO have
the full d3d12.h declarations the guard fires and our forward
declaration is skipped; on toolchains that don't (mingw-w64, some
older SDKs) our declaration provides the interface. Same pattern
Wine and various cross-compiled D3D12 projects use.

The IID and method layout have been stable since the D3D12.1
release. The interface inherits from ID3D12DeviceChild (which
inherits ID3D12Object, which inherits IUnknown), so the COM
vtable slots line up with what runtime objects expose.

# Files

  - src/common/d3d12/pipeline_library_compat.h: NEW. Forward
    declares ID3D12PipelineLibrary plus the two error HRESULTs
    that drive the cache-invalidation path, with the standard
    SDK guard so we no-op when present.
  - src/common/d3d12/shader_cache.h: include the compat header,
    add m_pipeline_library / m_pipeline_library_blob /
    m_use_pipeline_library members, declare the three new
    helpers (TryOpenPipelineLibrary, SerializePipelineLibrary,
    GetPipelineLibraryFilename, FormatPipelineLibraryName), and
    update the Open signature to accept an ID3D12Device*.
  - src/common/d3d12/shader_cache.cpp: implement detection in
    Open, library-fast-path in GetPipelineState, and
    Serialize-on-destroy. The legacy m_use_pipeline_cache path
    (currently always false) is untouched.
  - src/core/gpu_hw_d3d12.cpp: pass g_d3d12_context->GetDevice()
    to the Open call.
2026-05-15 06:18:13 +02:00
LibretroAdmin
19b118b9ae core, common/d3d11,d3d12,vulkan: skip unreachable cells in batch matrices
The 4 x 9 x 2 x 2 batch shader matrix (and the larger D3D12 / Vulkan
PSO matrices that extend it with depth_test and transparency_mode)
have structurally unreachable cells that the precompile loop and
background-compile worker were burning shader-compiler time on
anyway. Add IsBatchShaderReachable to gpu_hw.h and consult it from
all walk sites in all three backends.

# Three classes of unreachable cell

  - Texture modes 3 (Reserved_Direct16Bit) and 7
    (Reserved_RawDirect16Bit). GetBatchPixelShader's lookup_mode
    dedup aliases these to canonical modes 2 and 6, so the slot
    fills lazily on first runtime fault via a ComPtr copy. No
    compile required.

  - OnlyOpaque / OnlyTransparent with texture_mode == Disabled.
    NeedsTwoPassRendering returns false for untextured polys, so
    FlushRender never selects the two-pass fallback path for them.
    Unique source compiles on all hardware.

  - TransparentAndOpaque with texture_mode != Disabled, on hardware
    without dual-source blend. NeedsTwoPassRendering returns true
    in that combination, so the single-pass dual-source render
    mode is never selected. Unique source compiles, but only on
    non-dual-source hardware.

# Effect

On hardware that supports dual-source blend (modern desktop /
most discrete GPUs):

  - D3D11 shader matrix: 104/144 cells reachable, 40 skipped.
    ~7% cold-compile time saved in Enabled mode (most of the
    saved cells were cache-hits anyway).
  - D3D12 shader matrix: same. PSO matrix: 1040/1440 cells
    reachable (28% saved, ~400 cells). With ~50 ms per PSO
    that's roughly 20 s saved on cold compile.
  - Vulkan shader matrix: same. PSO matrix: 1560/2160
    reachable (28% saved, ~600 cells). ~30 s saved on cold
    compile.

On hardware WITHOUT dual-source blend (some integrated /
legacy parts):

  - D3D11: 80/144 cells (44% saved), ~29% cold-compile reduction.
  - D3D12: PSO matrix 800/1440 (44%), ~33 s saved.
  - Vulkan: PSO matrix 1200/2160 (44%), ~48 s saved.

Zero runtime cost. We're not changing what gets drawn, just not
pre-compiling shaders that wouldn't be drawn. The runtime fault
paths through GetBatchPixelShader / GetBatchPipeline (slow-path
mutex publish, dup_slot aliasing for reserved texture modes)
are unchanged and handle the first draw to a skipped cell
correctly without falling over - the dedup just kicks in via
the canonical slot on first fault, exactly as it would for any
other unfilled slot in Disabled mode.

The depth_test and transparency_mode axes don't affect
reachability (NeedsTwoPassRendering doesn't depend on them), so
the PSO progress unit count is just
CountReachableBatchShaders * <depth_test_count> * 5.

# What's NOT changed

  - GetBatchPixelShader / GetBatchFragmentShader / GetBatchPipeline
    themselves. The lookup_mode dedup and the slow-path publish
    step still handle reserved texture modes and unforeseen
    runtime cell selections correctly.
  - Matrix storage layouts. The arrays stay dense at their full
    sizes - skipping cells leaves them null, which is harmless.
  - Non-batch shaders. The non-batch upfront ticks still apply.

# Files touched

  - src/core/gpu_hw.h: IsBatchShaderReachable +
    CountReachableBatchShaders helpers (static, inline, no
    per-instance state).
  - src/core/gpu_hw_d3d11.cpp: skip in ShaderCompileThreadEntryPoint
    worker loop and in the precompile_sync block in CompileShaders.
  - src/core/gpu_hw_d3d12.cpp: skip in CompilePipelines (shader
    precompile + PSO precompile) and in
    ShaderCompileThreadEntryPoint.
  - src/core/gpu_hw_vulkan.cpp: skip in CompilePipelines (shader-
    module precompile + PSO precompile) and in
    ShaderCompileThreadEntryPoint.

Progress unit counts now use CountReachableBatchShaders so the
Enabled progress bar lands at exactly the compile count for the
running hardware.
2026-05-15 05:21:19 +02:00
LibretroAdmin
5d8a12acea core, common/d3d11: lock-free shader compile in lazy batch path
Symmetry pass for the D3D11 backend matching the D3D12 / Vulkan
fixes. The same Lazy-mode lockup pattern was reproducible: the
worker held m_batch_shader_mutex across the slow D3DCompile, and
the main thread's first DrawBatchVertices stalled on the mutex
for the duration of one shader compile - in practice locking up
the runloop before the BIOS screen as the worker walked the
144-entry batch matrix on its first run.

# What changed

  * common/d3d11/shader_cache: D3D11::ShaderCache is now thread-
    safe. One internal mutex (m_shader_cache_mutex) covers the
    DXBC index (unordered_map), the blob file, and the index
    file. NOT held across ShaderCompiler::CompileShader, so two
    threads compiling different shaders run truly in parallel.
    Two threads racing to compile the same shader is harmless:
    D3DCompile is deterministic on identical source so both
    produce identical DXBC; the double-check under the lock
    picks whichever publishes first and the loser's DXBC is
    discarded.

    Unlike D3D12 / Vulkan, no pipeline-cache analog is needed -
    D3D11 binds individual state objects rather than monolithic
    PSOs, and ID3D11Device::CreatePixelShader is documented
    free-threaded by Microsoft.

  * core/gpu_hw_d3d11: GetBatchPixelShader restructured. Shadergen
    + m_shader_cache.GetPixelShader (D3DCompile HLSL -> DXBC +
    CreatePixelShader) now run WITHOUT m_batch_shader_mutex held.
    The mutex is taken BRIEFLY at the end for the publish step -
    a slot.store + race-loser detection under double-check.
    Window measured in microseconds instead of the previous
    50-200 ms per compile.

    Race-loser handling: two threads racing to compile the same
    slot both produce equivalent ID3D11PixelShader objects. The
    loser's ComPtr falls out of scope at function exit and
    releases its COM reference automatically; the winner's
    canonical_slot ownership is the one published.

# Behaviour summary

Same shape as the D3D12 / Vulkan commits:

  * Disabled: CompileShaders builds the ~20 non-batch shaders
              upfront (D3D11 has no lazy non-batch path). Batch
              matrix stays empty; faulted on first draw. ~200 KB
              cache footprint after a session.
  * Lazy:     CompileShaders builds the ~20 non-batch shaders
              upfront, spawns the worker to walk the 144-entry
              batch matrix in the background. Gameplay starts
              instantly; worker fills slots opportunistically.
              ~5 MB cache footprint when worker finishes.

              Pre-fix this mode locked up before BIOS as the
              worker held the compile mutex across each ~50-200 ms
              D3DCompile call and the runloop starved on its first
              DrawBatchVertices.
  * Enabled:  CompileShaders builds every shader upfront. ~60 s
              first-run cold compile (D3DCompile is slow on the
              heavier shaders); near-instant warm-cache runs
              afterward. ~5 MB cache footprint immediately.

# Files touched

  * src/common/d3d11/shader_cache.h: include <mutex>, add
    m_shader_cache_mutex.
  * src/common/d3d11/shader_cache.cpp: scope-narrow
    m_shader_cache_mutex around index + file I/O in GetShaderBlob;
    add the double-check + publish pattern to
    CompileAndAddShaderBlob.
  * src/core/gpu_hw_d3d11.cpp: move shadergen + compile out
    before the publish-only m_batch_shader_mutex window in
    GetBatchPixelShader; update worker-entrypoint comment to
    reflect the new mutex semantics.
  * src/core/gpu_hw_d3d11.h: update the two-level-sync comment on
    GetBatchPixelShader and the storage-mutex comment on
    m_batch_pixel_shaders to describe the publish-only window.
2026-05-15 04:40:56 +02:00
LibretroAdmin
65d02fd1cc core, common/vulkan: lazy-fault non-batch PSOs
Symmetry pass for the Vulkan backend matching the D3D12 fix.

# What changed

Three threads now share the lazy-fault PSO matrix without
serialising on a single compile mutex:

  * common/vulkan/shader_cache: ShaderCache is now thread-safe.
    Two internal mutexes:
      - m_shader_cache_mutex covers the SPIR-V index
        (unordered_map), the blob file, and the index file. NOT
        held across ShaderCompiler::CompileShader, so two threads
        compiling different shaders run truly in parallel. Two
        threads compiling the SAME shader both run glslang; the
        double-check under the lock picks whichever publishes
        first and the loser's SPIR-V is discarded.
      - m_pipeline_cache_mutex serialises the VkPipelineCache.
        Per Vulkan 1.0 spec, the pipelineCache parameter to
        vkCreateGraphicsPipelines is in the host-synchronised
        parameter list - the application must guarantee no
        concurrent use of the same VkPipelineCache. Exposed via
        PipelineCacheMutex() for callers that need to honour the
        contract.

  * core/gpu_hw_vulkan: non-batch pipelines (VRAM fill / copy /
    write / update depth / readback, display, downsample) and
    their shared fullscreen-quad / UV-quad vertex shaders are now
    lazy-fault helpers, same shape as the D3D12 backend's
    GetVRAMFillPipeline / GetDisplayPipeline / etc. Each helper
    runs glslang lock-free, takes PipelineCacheMutex briefly
    around vkCreateGraphicsPipelines, and writes the slot.
    Twelve sites that bound the raw member pipelines via
    vkCmdBindPipeline now go through the helpers.

  * core/gpu_hw_vulkan: the batch helpers (GetBatchFragmentShader,
    GetBatchPipeline) no longer hold m_batch_shader_mutex across
    the slow operations. Each runs glslang + vkCreateShaderModule
    lock-free, takes PipelineCacheMutex around the
    vkCreateGraphicsPipelines call, then takes m_batch_shader_mutex
    BRIEFLY to publish under a double-check - the mutex is now a
    publish-step lock only, scoped to a slot.store + race-loser
    vkDestroy*. Window measured in microseconds instead of the
    previous hundreds of milliseconds.

# Why this matters (Vulkan-specific reasoning)

In the pre-fix design, m_batch_shader_mutex covered the entire
compile-and-publish sequence, including the glslang -> SPIR-V
step. After a UpdateSettings change (e.g. texture filter,
resolution scale) the precompile worker would hold the mutex
across each ~150-300 ms glslang compile of the heavier shaders,
and every concurrent main-thread DrawBatchVertices stalled
behind it for the full duration. The runloop never made forward
progress until the worker finished the entire 2160-entry batch
matrix - same user-visible multi-second hang the D3D12 backend
had.

Unlike D3D12, Vulkan 1.0 cannot drop the lock entirely:
vkCreateGraphicsPipelines requires external sync on the
pipelineCache parameter (D3D12's CreateGraphicsPipelineState
is thread-safe by Microsoft's documentation, no equivalent
guarantee in Vulkan 1.0). The
VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT flag from
Vulkan 1.3 would let us elide this, but SwanStation targets
VK_API_VERSION_1_0, so the lock around vkCreateGraphicsPipelines
is mandatory.

The win is still substantial because the EXPENSIVE step -
glslang -> SPIR-V translation, which has the D3DCompile-style
optimiser cost characteristic - now runs lock-free across
threads. vkCreateGraphicsPipelines itself is mostly the driver
enqueueing SPIR-V -> GPU-ISA work onto its own background
threads; the caller-thread time inside that call is short. So
PipelineCacheMutex is held for tens of milliseconds per
compile, not hundreds.

# Lazy main-thread pre-fill (mandatory)

Same pattern as D3D12: in Lazy mode, after the non-batch
upfront block (which is now empty - all non-batch PSOs are
lazy too), the main thread pre-fills every non-batch helper
before spawning the worker. Without this, the worker could
hold PipelineCacheMutex through the batch matrix walk and the
runloop's first FillVRAM / UpdateDisplay would starve on
non-FIFO Windows std::mutex.

# Behaviour summary (same shape as D3D12 commit)

  * Disabled: CompilePipelines builds only the two batch vertex
              shaders. All other PSOs faulted in on first draw.
              ~150 KB shader-cache + ~150 KB pipeline-cache
              footprint after a session.
  * Lazy:     CompilePipelines builds the two batch vertex
              shaders + all non-batch PSOs via the main-thread
              pre-fill, then spawns the worker to walk the
              batch matrix in the background. Gameplay starts
              instantly; worker fills slots opportunistically.
              ~5 MB cache footprint when worker finishes.
  * Enabled:  CompilePipelines builds the two batch vertex
              shaders + every batch shader-module + every PSO
              upfront via the same helpers (so the progress bar
              ticks per pipeline). Original ~35 s upfront pause.
              ~5 MB cache footprint immediately.

# Files touched

  * src/common/vulkan/shader_cache.h: declare
    m_shader_cache_mutex, m_pipeline_cache_mutex, add
    PipelineCacheMutex() accessor.
  * src/common/vulkan/shader_cache.cpp: scope-narrow
    m_shader_cache_mutex around index + file I/O in
    GetShaderSPV; add the double-check + publish pattern to
    CompileAndAddShaderSPV.
  * src/core/gpu_hw_vulkan.h: declare 13 lazy helpers, two
    member shader-module slots for the shared
    fullscreen-quad / UV-quad vertex shaders.
  * src/core/gpu_hw_vulkan.cpp: implement the helpers, gate the
    upfront non-batch block on precompile_sync, add the
    main-thread pre-fill for Lazy, swap 12 draw-path bindings
    onto the helpers, update DestroyPipelines to tear down the
    member shaders.

The 25 retro_* libretro exports are preserved. .so size is
unchanged versus master.
2026-05-15 03:49:01 +02:00
LibretroAdmin
75e826954f core, common/d3d12: lazy-fault non-batch PSOs
Background
==========

The shader precompile mode core option is documented as:
  - Enabled: build the full matrix synchronously at GPU init.
  - Lazy: kick off a background thread that walks the matrix; fault
    in any cell the main thread needs first.
  - Disabled: skip precompile, compile on first use.

But the gate on those modes only covered the batch matrix - 144
unique fragment shaders (after the Reserved_*Direct16Bit dedup)
plus 1440 PSOs across the depth_test x render_mode x texture_mode x
transparency_mode x dithering x interlacing dimensions. The 17
non-batch PSOs (VRAM fill x4, VRAM copy x2, VRAM write x2, VRAM
update depth, VRAM readback, display x6, copy/blit) and the
fullscreen-quad vertex shader were built unconditionally at the
end of CompilePipelines, regardless of mode.

The user-visible effect on 'Disabled': a non-trivial init pause
(D3DCompile HLSL->DXBC for 18 distinct shaders, plus 17 driver-
side PSO compiles) even though the user explicitly opted out of
precompile. On 'Lazy' the same work blocked the runloop briefly
while the worker hadn't started.

This commit moves the non-batch pipelines under the same lazy-
fault umbrella as the batch matrix, honouring the 'Disabled'
contract: nothing is compiled at GPU init.

Change shape
============

New helpers in GPU_HW_D3D12, mirroring the GetBatchPipeline /
GetBatchFragmentShader pattern:

  GetFullscreenQuadVertexShader()      // shared input
  GetVRAMFillPipeline(wrapped, interlaced)
  GetVRAMCopyPipeline(depth_test)
  GetVRAMWritePipeline(depth_test)
  GetVRAMUpdateDepthPipeline()
  GetVRAMReadbackPipeline()
  GetDisplayPipeline(depth_24, interlace_mode)
  GetCopyPipeline()

Each runs:

  fast path: atomic acquire-load on a parallel raw-pointer array
             (m_xxx_pipelines_fastpath). One uncontended atomic
             load per call once the slot is filled.
  slow path: compile the shader and PSO WITHOUT any helper-level
             mutex held. D3D12::ShaderCache itself is thread-safe
             (see below), so the GetPixelShader call runs lock-
             free and the gpbuilder.Create's CreateGraphicsPipelineState
             also runs lock-free. After both succeed, take
             m_batch_shader_mutex briefly to publish the result
             into the ComPtr slot, the Reserved_* dup slot (where
             applicable), and the fast-path atomic. The publish
             step double-checks the atomic in case another thread
             won the race - the loser discards its own fresh
             result via ComPtr destructor.

The 7 PSO helpers all call GetFullscreenQuadVertexShader() before
the compile to fetch the shared VS - the first non-batch helper
invocation pays for that single VS compile.

Why lock-free compile is mandatory
==================================

The previous draft of this commit (squashed below) held
m_batch_shader_mutex across the D3DCompile / CreateGraphicsPipelineState
calls. GDB confirmed that pattern produced a hard lockup on Lazy
mode before BIOS:

  Worker (Thread 29):
    D3DCompile (stuck deep in D3DReflect optimiser passes)
      D3D11::ShaderCompiler::CompileShader
      D3D12::ShaderCache::CompileAndAddShaderBlob
      D3D12::ShaderCache::GetShaderBlob
      GPU_HW_D3D12::GetBatchFragmentShader  <- m_batch_shader_mutex held
      GPU_HW_D3D12::GetBatchPipeline
      ShaderCompileThreadEntryPoint

  Main (Thread 1):
    ntdll!ZwWaitForSingleObject  <- waiting on same mutex
      libwinpthread mutex acquire
      GPU_HW_D3D12::GetBatchFragmentShader
      GPU_HW_D3D12::GetBatchPipeline
      GPU_HW_D3D12::DrawBatchVertices
      GPU::CRTCTickEvent

The heavier filter combinations of the batch matrix have shaders
where D3DCompile takes a long time (one was effectively non-
terminating during the user's test session). With the mutex held
across the compile, the worker monopolised the mutex while stuck
in D3DCompile and the main thread couldn't fault its own (fast)
BIOS-text shader.

The fix is to never hold the mutex during the slow operation -
which required making D3D12::ShaderCache thread-safe internally
so that the cache calls themselves don't need external locking.

D3D12::ShaderCache changes
==========================

  - Two new mutexes: m_shader_cache_mutex (covers m_shader_index,
    m_shader_blob_file, m_shader_index_file) and
    m_pipeline_cache_mutex (covers the pipeline-side state).

  - GetShaderBlob takes m_shader_cache_mutex only for the index
    lookup and file read. On miss, it releases the lock before
    calling CompileAndAddShaderBlob.

  - CompileAndAddShaderBlob does D3DCompile WITHOUT the cache
    mutex held. Then takes the lock to publish, with a double-
    check: if another thread won the race and already wrote this
    key, return their cached blob instead of writing ours
    (avoids duplicate file writes and uniquely-keys the index).

  - GetPipelineState and CompileAndAddPipeline get the same
    treatment: cache I/O under the lock, the slow
    CreateGraphicsPipelineState call lock-free.

  - Latent bug fixed in passing: CompileAndAddPipeline at the
    write step did m_shader_index.emplace instead of
    m_pipeline_index.emplace. Inert since the per-PSO disk cache
    was dropped in commit 81e3a2b8 (m_pipeline_blob_file is
    always null), but corrected so the code is right if the
    pipeline cache ever comes back.

CompilePipelines flow
=====================

  - Always: open the disk shader cache, construct m_shadergen, and
            compile the two batch vertex shaders. These are very
            cheap (no D3DCompile heavy lifting) and are needed by
            GetBatchPipeline.
  - 'Enabled' only: walk the full batch fragment-shader matrix and
                    the full batch PSO matrix synchronously, then
                    call the 7 non-batch helpers once each to fill
                    their slots upfront.
  - 'Lazy' only: pre-fill the 18 non-batch units on the main
                 thread, then spawn the worker. With lock-free
                 compiles this is now an optimisation rather than
                 a correctness requirement - it just avoids the
                 duplicate-compile cost a race window would
                 otherwise pay for those 18 helpers.
  - 'Disabled': nothing else.

ShaderCompileThreadEntryPoint (Lazy worker) is responsible only
for the batch matrix. Main-thread batch PSO fault-ins mid-game
still work - both threads truly run concurrently through
D3DCompile / CreateGraphicsPipelineState. D3DCompile is documented
thread-safe per Microsoft and D3D12Core spawns its own background
threads for PSO compilation, so this maps cleanly onto the
underlying API surface.

Call sites
==========

Seven runloop hot-path call sites updated to use the helpers
instead of m_xxx_pipeline.Get():

  FillVRAM                      -> GetVRAMFillPipeline
  CopyVRAM                      -> GetVRAMCopyPipeline
  UpdateVRAM                    -> GetVRAMWritePipeline
  UpdateDepthBufferFromMaskBit  -> GetVRAMUpdateDepthPipeline
  ReadVRAM                      -> GetVRAMReadbackPipeline
  UpdateDisplay                 -> GetDisplayPipeline
  BlitVRAMReplacementTexture    -> GetCopyPipeline

All return early on helper failure (null PSO) - no Log spam, no
divergent behaviour; the helper itself logs the source-level cause.

DestroyPipelines was already missing m_copy_pipeline.Reset() (an
existing latent leak across UpdateSettings -> DestroyPipelines ->
CompilePipelines cycles, masked because the next CompilePipelines
overwrote the slot). Fixed here in passing along with the new
fast-path array and m_fullscreen_quad_vertex_shader resets.

Progress tracker math updated: non-batch units only counted when
precompile_sync. 'Lazy' and 'Disabled' get a precompile progress
bar with just the batch vertex shader ticks (2 units) instead of
the prior "2 + 18 = 20" minimum.

Behaviour summary
=================

  Enabled  : unchanged - identical PSOs built upfront in the same
             order, same progress bar. Routed through the helpers'
             slow path which now exercises the same lock-free
             compile sequence Lazy/Disabled use.
  Lazy     : main thread pre-fills 18 non-batch PSOs (sub-second)
             then spawns the worker. Worker walks the 1440 batch
             cells lock-free. Main thread runs gameplay and faults
             its own batch PSOs in parallel with the worker -
             both threads truly concurrent through D3DCompile.
             Slow shader compiles in the worker no longer block
             anything.
  Disabled : zero PSO work at init. Runloop faults each pipeline
             on first use - one ms-scale hitch per unique pipeline
             over the first few seconds of any new game. Net runloop
             cost is the same total work that used to happen upfront,
             but spread out and aligned with actual usage.

Verified on a Windows MinGW build with a clean shader cache:

  Disabled: ~2 shaders compiled at startup (the batch VS pair),
            instant startup, ~150 KB shader cache after a session.
  Lazy:     ~2 shaders at startup, window unfrozen, gameplay
            starts within a second or two; full ~5 MB cache after
            worker completes in background. (Previous draft of
            this patch locked up before BIOS could render - see
            'Why lock-free compile is mandatory' above.)
  Enabled:  ~1600 shaders at startup, ~35s stall, same ~5 MB
            cache. Identical to pre-patch behaviour.

Build verification (Linux host)
================================

  make platform=unix: clean, .so unchanged at 7,905,720 bytes,
  25 retro_ exports preserved (D3D12 TU is Windows-only so the
  Linux build path is untouched).

  make platform=win dry-run: gpu_hw_d3d12.o still compiled with
  -DUSE_D3D12=1 and linked with -ld3d12; all common/d3d12 TUs
  unchanged at the link level (only their implementations gained
  the new internal locking).

Vulkan side
===========

Intentionally left alone for now. Same structural mismatch
exists - the Vulkan precompile mode gate is on the batch matrix
only - but Vulkan's per-PSO compile cost is dominated by
SPIR-V->GPU-ISA in the driver which the VkPipelineCache
amortises across PSOs by shared shader hashes, so the user-
visible 'Disabled' init pause is much smaller. A follow-up
commit will apply the same surgery there if 'Disabled' on Vulkan
also turns out to feel slow.
2026-05-15 03:13:01 +02:00
LibretroAdmin
81e3a2b2b3 common/d3d12: drop the per-PSO disk cache
Background
==========

D3D12::ShaderCache maintained two on-disk caches: a shader bytecode
cache (d3d12_shaders_sm50.bin / .idx) keyed by HLSL source hash, and
a pipeline state object cache (d3d12_pipelines_sm50.bin / .idx) keyed
by the merged D3D12_GRAPHICS_PIPELINE_STATE_DESC hash. The pipeline
cache persisted each PSO's full ID3D12PipelineState::GetCachedBlob
output as an independent entry.

On a stock SwanStation session that has touched most of the batch
matrix that comes out to ~1440 PSO blobs plus the non-batch
pipelines, each blob carrying the fully-validated state object with
VS+PS bytecode embedded. Roughly 16 KB per PSO on average. The user-
visible result was a ~75 MB d3d12_pipelines_sm50.bin file with no
corresponding benefit at runtime.

For comparison: PCSX2's D3D12 cache for a fully populated session
sits at ~1.5 MB - 45x smaller for a more complex GPU emulation -
because it caches at the shader-bytecode level only and lets the
runtime build PSOs from cached bytecode on demand. The driver-side
PSO assembly from already-compiled DXBC is sub-millisecond on modern
desktop GPUs, so re-doing it on cold start is not a real cost.

Diagnosis
=========

Two independent things were going on:

1) Per-PSO disk persistence is the wrong granularity. PSOs that
   share a vertex/pixel shader (most of the batch matrix - the
   1440 cells differ only in fixed-function state: depth_test x
   render_mode x texture_mode x transparency_mode x dithering x
   interlacing) each carry their own copy of the same shader
   bytecode in the cached blob. Reading 75 MB back from disk to
   feed CachedPSO entries to CreateGraphicsPipelineState was not
   meaningfully faster than rebuilding from the existing shader
   bytecode cache (which stays at ~5 MB).

2) The shader bytecode cache (the ~5 MB d3d12_shaders_sm50.bin)
   is doing the expensive work already - HLSL -> DXBC compilation
   via D3DCompile. That stays in place.

Change
======

  CanUsePipelineCache() returns false unconditionally.

  Open() now also deletes any leftover d3d12_pipelines_sm50.idx /
  .bin files from a previous build that had the per-PSO cache
  enabled. Without this they would sit in the user's system
  directory forever consuming ~75 MB. Self-healing across upgrades
  and downgrades.

Everything else falls out: CompileAndAddPipeline already guarded its
write path on m_pipeline_blob_file being non-null (line 433), so PSO
creation now goes straight through CreateGraphicsPipelineState and
returns without touching disk. InvalidatePipelineCache's recreate
branch is correctly gated on m_use_pipeline_cache so it becomes a
plain clear. GetPipelineState's m_pipeline_index lookup always
misses now and falls through to CompileAndAddPipeline.

Note: the existing m_use_pipeline_cache field is kept (now always
false) because it cleanly gates the open/recreate paths without
needing intrusive changes. A future move to ID3D12PipelineLibrary
(D3D12.1, Windows 10 v1703+, internally dedup'd) would slot in by
flipping the gate back on with a different implementation underneath.

Vulkan side intentionally not touched in the same commit. Vulkan
uses VkPipelineCache - a single driver-managed blob that internally
dedupes shader bytecode across PSOs. User's vulkan_pipelines.bin is
5.7 MB total for a populated session, vs PCSX2's 9.6 MB. The Vulkan
side is already doing the right thing and dropping it would regress
cold-start without any disk-bloat win.

Tangentially noticed
====================

CompileAndAddPipeline line 464 (m_shader_index.emplace(key, data))
adds the pipeline-cache entry to the SHADER index instead of the
pipeline index. With the disk cache off this path is no longer
reached so the latent bug becomes inert. Left as-is for a focused
follow-up to keep this diff minimal.

The batch matrix dimensions in gpu_hw_d3d12.h:193 (template
<2,2,5,9,4,2>) do not match the indexing order in GetBatchPipeline
or the loop bounds in CompilePipelines. Likely a real correctness
issue but again kept out of this diff.

Build verification
==================

  make platform=unix: clean, .so unchanged at 7,905,720 bytes,
  25 retro_ exports preserved (D3D12 TU is Windows-only).
2026-05-15 01:47:44 +02:00
LibretroAdmin
cf05cadb4d core, libretro, common: wire up D3D12 renderer for libretro
Wires the existing D3D12 hardware renderer (src/core/gpu_hw_d3d12.cpp,
src/common/d3d12/*) into the libretro frontend, behind a USE_D3D12=1
gate. The opt-in is because:

  1. retro_hw_render_interface_d3d12 is supported by recent RetroArch
     builds but not all of them - the SET_HW_RENDER environment call
     will fail at runtime where unsupported.
  2. Not every Windows target ships d3d12.lib in its toolchain; the
     gate keeps the existing default Windows build path working.

When USE_D3D12=1 is set on the make command line, the libretro
Makefile pulls in the seven common/d3d12 TUs, gpu_hw_d3d12.cpp, the
new LibretroD3D12HostDisplay class, links against d3d12.lib, and
exposes "D3D12" in the renderer dropdown next to D3D11.

== src/common/d3d12 ==

  D3D12::Context grew a CreateForLibretro(device, command_queue)
  static factory next to its existing Create(dxgi_factory, ...). The
  libretro path adopts the frontend's device + command queue (the
  frontend retains ownership; we just AddRef them via ComPtr) and
  then creates only the resources we own: fence, descriptor heaps,
  command lists, texture upload stream buffer. Feature level is
  pinned at FL11_0; the gpu_hw_d3d12 shader/PSO setup targets that
  baseline. CreateForLibretro still loads d3d12.dll because
  PFN_D3D12_SERIALIZE_ROOT_SIGNATURE is needed by
  Context::SerializeRootSignature, which gpu_hw_d3d12.cpp uses on
  initial root-signature creation.

  Destroy() is unchanged; the borrowed device/queue ComPtrs simply
  release their AddRef in the Context destructor and the frontend
  keeps the underlying objects alive.

== src/core/gpu_hw_d3d12.h, .cpp ==

  Added LibretroD3D12HostDisplay (declaration in the header above
  GPU_HW_D3D12, implementation appended ahead of GPU_HW_D3D12's
  constructor body in the .cpp). The class mirrors
  LibretroD3D11HostDisplay's surface and behaves identically on
  the libretro-API side, with two differences driven by the D3D12
  libretro interface contract:

  1. There is no analogue to ID3D11DeviceContext in D3D12 - work
     is recorded on command lists owned by D3D12::Context. The
     class therefore does not store m_device / m_context members;
     callers that need the device go through
     g_d3d12_context->GetDevice() as the rest of gpu_hw_d3d12.cpp
     already does. GetRenderDevice() returns
     g_d3d12_context->GetDevice() for HostDisplay-API callers;
     GetRenderContext() returns nullptr.

  2. Present is the retro_hw_render_interface_d3d12::set_texture
     callback rather than a swapchain blit. LibretroD3D12HostDisplay
     ::Render() transitions the GPU_HW_D3D12-produced display
     texture into the frontend's required_state, flushes our
     pending command list via ExecuteCommandList(false), calls
     set_texture(frontend_handle, ID3D12Resource*, format), then
     signals the frontend a HW frame is ready via
     g_retro_video_refresh_callback(RETRO_HW_FRAME_BUFFER_VALID,
     width, height, 0). The frame-dupe (NULL) path for runahead /
     fast-forward video skip is identical to the D3D11 and SW
     renderer paths.

  The CreateTexture / BeginSetDisplayPixels / EndSetDisplayPixels
  paths return nullptr / false the same way LibretroHostDisplay
  does. They are not exercised on the libretro D3D12 path - GPU_HW
  _D3D12 owns its own D3D12::Texture instances directly, and the
  SW renderer (which is the only path that would BeginSetDisplay
  Pixels) uses LibretroHostDisplay rather than going through D3D12.

  An m_framebuffer member is reserved on the class for future
  software-cursor / lightgun-crosshair overlay work (which would
  composite over the display texture in an owned RTV before
  set_texture, the way gpu_hw_d3d11.cpp does it). For the initial
  wire-up the present path forwards the GPU_HW_D3D12 display
  texture directly.

  HAVE_D3D12 is #define'd before the libretro_d3d.h include to
  pull in the retro_hw_render_interface_d3d12 struct definition,
  matching the equivalent pattern in gpu_hw_d3d11.cpp.

== src/libretro/libretro_host_interface.cpp ==

  Four switch cases extended, all under #ifdef WIN32 + #ifdef USE
  _D3D12:

  - RetroHwContextToRenderer: maps RETRO_HW_CONTEXT_D3D12 = 9 to
    GPURenderer::HardwareD3D12 so the Auto-renderer path picks D3D12
    when the frontend advertises it via GET_PREFERRED_HW_RENDER.

  - RenderAPIToRenderer: maps HostDisplay::RenderAPI::D3D12 to
    GPURenderer::HardwareD3D12 so reusing an existing hardware
    display across SwitchToHardwareRenderer rebinds correctly.

  - RequestHardwareRendererContext: calls
    LibretroD3D12HostDisplay::RequestHardwareRendererContext
    (sets context_type=RETRO_HW_CONTEXT_D3D12, version_major=12,
    version_minor=0).

  - SwitchToHardwareRenderer: instantiates LibretroD3D12HostDisplay
    when m_hw_render_callback.context_type indicates D3D12.

  Include line added for gpu_hw_d3d12.h alongside the existing
  gpu_hw_d3d11.h include.

== src/libretro/libretro_core_options.h ==

  Renderer dropdown gains {"D3D12", "Hardware (D3D12)"} entry,
  gated USE_D3D12 inside the existing WIN32 block. Settings
  ::ParseRendererName already had D3D12 in its s_gpu_renderer
  _names array (pre-existing), and Settings::GetRendererName
  reads from the same array, so the dropdown selection round-trips
  to/from GPURenderer::HardwareD3D12 correctly.

== Makefile.libretro ==

  Under the existing IS_WINDOWS guard, added a USE_D3D12=1 branch
  that:

  - Adds -DUSE_D3D12=1 to CXXFLAGS so the wiring under #ifdef USE
    _D3D12 in libretro_host_interface.cpp, libretro_core_options.h,
    gpu_hw_d3d12.cpp, and gpu_hw_d3d12.h gets compiled in.

  - Adds -ld3d12 to LDFLAGS so PFN_D3D12_SERIALIZE_ROOT_SIGNATURE
    resolves at link time (Context::SerializeRootSignature uses it).

  - Adds the seven common/d3d12 TUs (context, descriptor_heap_
    manager, shader_cache, staging_texture, stream_buffer, texture,
    util) to SOURCES_CXX.

  - Adds src/core/gpu_hw_d3d12.cpp to SOURCES_CXX in the core
    section.

  Default (no USE_D3D12=1) keeps the existing Windows build
  unchanged. system.cpp's renderer dispatch already had the case
  GPURenderer::HardwareD3D12 case behind #ifdef USE_D3D12 and the
  forward declaration of GPU::CreateHardwareD3D12Renderer() was
  already in gpu.h, so no changes were needed there.

== Build verification ==

Linux libretro build: clean, .so unchanged at 7,905,720 bytes (all
new D3D12 code is gated under WIN32 + USE_D3D12 - no compiled-in
effect on non-Windows targets), 25 retro_ exports preserved.

Windows build with USE_D3D12=1 has not been verified in this
environment - mingw cross-compile tools and the d3d12 SDK headers
aren't available on the build host. Manual test on Windows
required before pushing.

7 files changed, 414 insertions(+).
2026-05-15 01:07:00 +02:00
LibretroAdmin
14c99a347d core: dead-code sweep, round 15
Audit of psf_loader.h, gpu_sw_backend.h's VRAMPixel union, common/gl/,
common/d3d11/, common/d3d12/, cdrom_async_reader.h, system.h, bios.h,
gpu.h, and a few other tertiary areas. Two finds:

== src/core/psf_loader ==

Dropped three dead methods on PSFLoader::File:

  ALWAYS_INLINE const TagMap& GetTagMap() const { return m_tags; }
  std::optional<float> File::GetTagFloat(const char*) const;
  float File::GetTagFloat(const char*, float default_value) const;

  GetTagMap is an inline accessor for the raw tag map - zero
  callers. The PSF file consumers (psf_loader.cpp::Load processes
  the tags during parsing, and the host-interface path queries
  individual tags via GetTagString/GetTagInt) never need the raw
  map.

  GetTagFloat is a complete 2-overload group (a std::optional
  version that parses with std::atof, and a default-value
  convenience overload that wraps it). Zero external callers, and
  the default-value overload only forwards to the std::optional
  one. The only consumer of PSF tags in the source tree is the
  region detection at psf_loader.cpp:135 which uses GetTagInt
  ("_region", 0); no caller asks for a float-valued tag.

  GetTagInt and GetTagString (both overloads each) are kept -
  GetTagInt is used internally at psf_loader.cpp:135, and
  GetTagString variants are used by the host-interface
  console-region detection path.

== src/core/gpu_sw_backend.h ==

Dropped three dead methods on the VRAMPixel union:

  void ClampAndSet(uint8_t r, uint8_t g, uint8_t b, bool c)
  void SetRGB24Dithered(uint32_t x, uint32_t y, ...)
  uint32_t ToRGB24() const

  All three have zero callers anywhere in the source tree. The
  active VRAMPixel surface consists of:
    - the bits field (set via the SetRGB24 overloads)
    - the r/g/b BitFields (read at line 136-138 of
      gpu_sw_backend.cpp during texture/color blending - these are
      consumed via implicit BitField conversion, not via the
      .GetValue() that ToRGB24 was using)
    - the Set() core helper
    - the two SetRGB24 overloads (uint32_t rgb24 and 3x uint8_t)

  The dropped surface looks like leftover from a parallel
  raster/blit path that was either never adopted or replaced by
  the templated DrawTriangle / DrawSpan / ShadePixel functions
  that handle dither and clamp inline via the s_dither_lut table
  and explicit clamp calls. ToRGB24 specifically would have
  produced a 24-bit display readback color, but the actual
  CopyOut24Bit path in gpu_sw.h does that conversion inline with
  a different bit layout.

== Build verification ==

Build clean on Makefile.libretro platform=unix.
swanstation_libretro.so size: 7,910,176 -> 7,905,720 bytes (-4456).
25 retro_* exports preserved.

The 4.4 KB .so reduction is significantly larger than expected for
removing 6 inline methods. The likely explanation is that the
VRAMPixel methods were being instantiated through the SW backend's
heavily-templated draw functions; dropping ClampAndSet,
SetRGB24Dithered, and ToRGB24 lets the linker drop those template
instantiation glue stubs as well as the methods themselves.
Per-template-instantiation overhead in the SW backend is the main
contributor.

== Audited and kept ==

  common/gl/ - all GL::Program, GL::Texture, GL::StreamBuffer,
    GL::ShaderCache APIs heavily used. Notable: Texture::Replace
    has only 1 caller (vram_write replacement upload) and
    BindFragDataIndexed has only 1 caller (gl1/legacy GL path),
    but both are alive.

  common/d3d11/ - audited but Windows-only TUs. The Makefile
    Linux build doesn't compile these so any drops there would be
    syntactically validated only; deferred to a future round
    where a Windows tester can verify.

  common/d3d12/ - not compiled by the libretro Makefile at all
    (only by CMake when USE_D3D12 is set). Skipped.

  Per-arch recompilers (aarch32, aarch64) - unix build uses x64
    CPU_ARCH, so those TUs aren't compiled. Already heavily
    audited via round 11's empty-stub-asymmetry method.

  cdrom_async_reader.h - all API alive.

  system.h - all 30+ entry points alive.

  bios.h - all 4 entry points alive. BIOS_SIZE_PS2/PS3 constants
    are used for input validation in bios.cpp::IsValidBIOS.

  gpu.h - all 30+ public methods alive (each Handle* GP0 command
    has count 3+ which is decl + impl + dispatch-table entry).
    Several private Update*TickEvent helpers are count-3 but each
    is wired through the gpu.cpp event loop.

  GPU_SW_Backend - all live: GetPixel, SetPixel, ShadePixel,
    DrawSpan, DrawTriangle templates and their function-pointer
    accessors GetDrawTriangleFunction etc.

  Controller virtual surface - all alive: GetButtonStateBits,
    GetAnalogInputBytes, GetVibrationMotorStrength, LoadSettings,
    GetSoftwareCursor (now with relative_mode parameter dropped
    in round 14).

  AnalogController save-state-compat fields (m_command_param,
    m_legacy_rumble_unlocked) - explicitly marked 'kept and
    serialized'.

  PSFLoader::File::GetProgramData (1 caller), GetRegion (4),
    GetTagString (4 overloaded uses), GetTagInt (2 - the no-
    default version is called by the default-value version which
    is called once by region detection).

3 files changed, 40 deletions(-).
2026-05-15 00:52:22 +02:00
LibretroAdmin
05bd412de6 core, libretro: dead-code sweep, round 14
Audit of new territory - cheats.h, host_display.h, src/libretro/,
host_interface.h, texture_replacements.h, and the cpu_types.h
constants block.

== Dead-output-parameter chain ==

The headline find: a dead chain anchored on a no-op
HostInterface::SetMouseMode that ran out through
Controller::GetSoftwareCursor's relative_mode parameter.

  void HostInterface::SetMouseMode(bool relative, bool hide_cursor) {}

  Defined as an empty stub in libretro_host_interface.cpp:1013.
  Two callers in host_interface.cpp::UpdateSoftwareCursor (lines
  484 and 504). In a non-libretro frontend (Qt, NoGui in upstream
  DuckStation) this would enable relative-mouse capture when a
  lightgun or PS-Mouse is active; the libretro frontend doesn't
  do explicit mouse capture (the frontend handles cursor mode
  via its own settings) so the stub stayed empty.

Following the dead method back through its arguments:

  hide_cursor: local variable in UpdateSoftwareCursor, set to
  true if any controller returned a software cursor, then handed
  only to SetMouseMode. With SetMouseMode dead, hide_cursor is
  also dead.

  relative_mode: local variable, set by passing &relative_mode to
  Controller::GetSoftwareCursor(image, image_scale, &relative_mode),
  then handed only to SetMouseMode. With SetMouseMode dead,
  relative_mode is also dead - and Controller::GetSoftwareCursor's
  third output-parameter is dead all the way through. The only
  override that writes it (NamcoGunCon::GetSoftwareCursor) sets
  *relative_mode = false, and the base impl returns false without
  touching it.

Full chain dropped:

  src/core/host_interface.h:171 - SetMouseMode decl
  src/libretro/libretro_host_interface.cpp:1013 - SetMouseMode impl
  src/core/host_interface.cpp:484, 504 - 2 SetMouseMode calls
  src/core/host_interface.cpp:491, 492 - relative_mode/hide_cursor
    locals
  src/core/controller.h:49 - GetSoftwareCursor signature
  src/core/controller.cpp:51 - GetSoftwareCursor base impl signature
  src/core/namco_guncon.h:29 - override signature
  src/core/namco_guncon.cpp:215 - override impl signature + dead
    '*relative_mode = false' write

Note: hide_cursor was the simpler write-only-local case from
earlier rounds (set to true and never read after SetMouseMode).
relative_mode is the interesting case - it's an output parameter
written by NamcoGunCon and read into a local that's only used by
the dead SetMouseMode. The dead-parameter chain only becomes
visible after tracing the parameter from the consumer back to the
producers.

== Smaller finds ==

  src/libretro/libretro_game_settings.h - dropped Trait
  DisableAnalogModeForcing. One of 21 entries in the Trait enum;
  zero references in HasTrait() / AddTrait() / ApplySettings().
  All 20 surviving Trait entries have at least one consumer in
  ApplySettings().

  src/core/texture_replacements.h - dropped
  TextureReplacementHash::operator<. The class is keyed in
  std::unordered_map<TextureReplacementHash, std::string>, which
  uses operator== + std::hash specialization - never operator<.
  No std::map<TextureReplacementHash, ...>, no infix usage. Dead.
  Also dropped the now-unused <tuple> include (the operator was
  using std::tie).

  src/core/cpu_types.h - dropped three constants:
    INSTRUCTION_COP_BITS = 0x10
    INSTRUCTION_COP_MASK = 0x3C
    INSTRUCTION_COP_N_MASK = 0x03

  Declared in a single block between the InstructionOp and
  InstructionFunct enums. All three constants have zero
  references anywhere in the source tree. The COP-instruction
  detection logic operates on the InstructionOp enum (cop0/cop1
  /cop2/cop3 + lwc0..lwc3 + swc0..swc3 entries), not on raw bit
  masks of the major-opcode byte, so these never got wired up.

== Methodology note ==

New entry for the running list:

  Dead-output-parameter chains. When auditing a no-op or empty-
  stub function for deletion, follow its parameters back to the
  producers. If a parameter exists only to feed the dead method,
  it - and its writers and the local variables that hold it - are
  also dead. Output parameters (T*) make this especially clear:
  the only purpose of a T* output parameter is to communicate
  back to the caller; if the caller discards it, the output
  parameter is dead surface.

  Identifying these chains requires reading the dead function's
  callers, not just grepping for callers of the function name.
  In this round, SetMouseMode looked like a small lone empty-stub
  drop until the locals revealed the full chain.

== Audited and kept ==

  All CheatCode::InstructionCode enum entries - every one reached
  as a case-label in cheats.cpp's opcode dispatch.

  HostDisplayPixelFormat::Unknown - kept as the value-0 sentinel
  for the s_display_pixel_format_mapping[Count] tables in
  gpu_hw_d3d11/vulkan/opengl. The mapping arrays are indexed by
  static_cast<uint32_t>(format); dropping Unknown would shift all
  other values and break the indexing.

  HostDisplay::RenderAPI::* - all 6 used.

  All other HostDisplay methods.

  All GameSettings::Entry fields - each maps to a g_settings.*
  field with real consumers across system.cpp / gpu.cpp / cdrom.cpp
  / bus.cpp.

  LibretroHostDisplay no-op overrides (CreateTexture returning
  nullptr, etc.) - required by pure-virtual base interface
  HostDisplay; the libretro SW pseudo-display doesn't have GPU
  resources, but the override has to exist.

  AnalogController save-state-compat fields (m_command_param,
  m_legacy_rumble_unlocked) - explicitly marked with the
  'kept and serialized for compatibility' comment.

  All Bus access-time arrays, MEMCTRL state, etc.

  cpu_types.h breakpoint helpers (ExecutionBreakpointsEnabled,
  DataReadBreakpointsEnabled, DataWriteBreakpointsEnabled) -
  count 2 each (decl + use in cpu_core.cpp).

  All GPU public API, including the count-1 Handle* commands that
  go through a dispatch table.

== Build verification ==

Build clean on Makefile.libretro platform=unix.
swanstation_libretro.so size: 7,910,240 -> 7,910,176 bytes (-64).
25 retro_* exports preserved.

The 64-byte reduction comes from the dropped SetMouseMode
function body and the eliminated dead-write at namco_guncon.cpp
:219. The other drops (header constants, enum entry, operator
overload that was inlined and never called) optimize away with
no .so footprint change.

10 files changed, 5 insertions(+), 25 deletions(-).
2026-05-15 00:18:34 +02:00
LibretroAdmin
f44c4bafc8 core, common: dead-code sweep, round 13 (five-angle audit)
A combined audit across five different abstractions, applying the
methodology toolkit accumulated over previous rounds:

  (a) empty-stub-asymmetry hunt across the controller and DMA
      dispatch tables
  (b) gpu_hw.h - the HW renderer common protocol
  (c) common/vulkan/ headers - the Vulkan helper library
  (d) cpu_code_cache.h and the recompiler's block compilation path
  (e) settings.h - the Settings struct

== (a) Empty-stub asymmetry ==

No new finds. The remaining empty '{}' impls in controller.cpp
(Reset, ResetTransferState, SetAxisState, SetButtonState,
LoadSettings) are legitimate base-class default no-ops for
controllers that don't have axes or buttons (e.g. DigitalController
has no axes). The DMA channel switch asymmetry (CDROM/PIO with no
body in DMAWrite, lines 472-476 of dma.cpp) is hardware-spec - those
channels truly don't transfer that direction.

== (b) gpu_hw.h ==

Dropped GPU_HW::EnsureVertexBufferSpace(uint32_t).

Declared in gpu_hw.h:217, impl at gpu_hw.cpp:969 (13 lines). Zero
callers. The replacement specialized form
EnsureVertexBufferSpaceForCurrentCommand (alive, 5 call sites)
switches on the current GPU command's primitive type to compute
required_vertices, then does the same flush-or-map sequence as the
old EnsureVertexBufferSpace. The simpler form was orphaned when
the specialized one was introduced.

== (c) common/vulkan/ ==

Three drops:

  Vulkan::Util::BufferMemoryBarrier - util.h:40, util.cpp:187.
  Generic vkCmdPipelineBarrier wrapper for VkBufferMemoryBarrier.
  Zero callers anywhere in the tree. The Vulkan renderer uses
  vkCmdPipelineBarrier directly with image barriers, and never
  needs the buffer-barrier variant. 19 lines.

  Vulkan::StagingBuffer::GetSize - staging_buffer.h:32. Inline
  accessor returning m_size. Zero callers.

  Vulkan::StagingBuffer::Read / ::Write - staging_buffer.h:49-50,
  staging_buffer.cpp:96-109. Memory-mapped buffer read/write
  helpers. Zero callers - the StagingBuffer is always accessed via
  GetMapPointer() returning the raw char* and the caller does the
  memcpy directly. The Read/Write methods would have made sense for
  a layer-of-abstraction approach that nobody adopted. 15 lines.

Kept (false starts re-verified):
  Vulkan::Texture::IsValid - looked dead because no external callers
  use m_texture.IsValid(). But the .cpp uses unqualified 'IsValid()'
  inside member functions at three sites. Round 6's lesson about
  within-class unqualified calls applies. Restored after build
  failure.

  Vulkan::StagingTexture::IsValid - same pattern. Four internal
  unqualified call sites in staging_texture.cpp.

== (d) cpu_code_cache ==

Six drops:

  CodeBlockKey::operator==, operator!=, operator<

  Three operator overloads on the CodeBlockKey union. The
  BlockMap is std::unordered_map<uint32_t, CodeBlock*> keyed on
  the raw bits, NOT on CodeBlockKey, so the operators are never
  invoked through stdlib container machinery. They're also never
  invoked via infix syntax (no 'key1 == key2' or 'key1 < key2'
  anywhere). Pure dead.

  CodeBlockInstruction::is_load_delay_slot
  CodeBlockInstruction::is_last_instruction
  CodeBlockInstruction::can_trap

  Three write-only bitfields. Each is set in
  cpu_code_cache.cpp::CompileBlock and never read anywhere. The
  recompiler and interpreter use the live flags
  (is_branch_instruction, is_direct_branch_instruction,
  is_unconditional_branch_instruction, is_branch_delay_slot,
  is_load_instruction, is_store_instruction, has_load_delay) but
  not these three.

  The CompileBlock function had three dead writes (lines 602, 609,
  666 before this commit) and a dead tracking local 'bool
  is_load_delay_slot' that fed cbi.is_load_delay_slot. All four
  dead writes plus the comment '// same for load delay' removed.

  Sized as bitfields, each field saved approximately 1 bit in
  CodeBlockInstruction storage - but since the struct holds 10
  bitfields with 6 other flags, the actual struct alignment didn't
  change. The 360-byte .so reduction comes from the eliminated
  setters in CompileBlock and the dropped CodeBlockKey operator
  function bodies (3 inline ALWAYS_INLINE methods with bodies but
  no inlining target callers).

== (e) settings.h ==

Two drops:

  bool bios_patch_tty_enable

  Declared in settings.h:99, default 'false'. Read at one site
  (system.cpp:689) inside an if-block that gates a call to
  BIOS::PatchBIOSEnableTTY. NEVER written anywhere - no Load()
  entry in settings.cpp, no game-settings override in
  libretro_game_settings.cpp, no external setter. The default 'false'
  means the if-branch is always false, so BIOS::PatchBIOSEnableTTY
  is also dead - dropped its decl (bios.h) and impl (bios.cpp).

  The setting was likely added for a debug feature (PS1 BIOS has a
  TTY debug output path that's normally disabled; patching the BIOS
  enables logging through it) but no UI or game-settings entry was
  ever wired up to set it true.

  DEFAULT_DMA_MAX_SLICE_TICKS
  DEFAULT_DMA_HALT_TICKS
  DEFAULT_GPU_FIFO_SIZE
  DEFAULT_GPU_MAX_RUN_AHEAD
  DEFAULT_VRAM_WRITE_DUMP_WIDTH_THRESHOLD
  DEFAULT_VRAM_WRITE_DUMP_HEIGHT_THRESHOLD

  Six static constexpr defaults declared as a compact constant
  block in settings.h:147-149. Zero callers - the actual defaults
  are written inline at the member-init point (e.g.
  'TickCount dma_max_slice_ticks = 1000') and in the GetIntValue
  fallback values inside Load(). The DEFAULT_* constants are a
  separate, redundant copy of those values that nobody consults.

== Methodology refinements ==

Two new entries for the running list:

  Within-class unqualified calls hide from member-access grep.
  When auditing a class method's call sites with
  '\.IsValid(' / '->IsValid(', the matches will miss calls of the
  form 'if (IsValid())' inside the class's own .cpp - because no
  qualifier appears. Always re-grep '\bMethod\b' in the defining
  .cpp before deciding it's dead. This was already in the list
  from round 6 but I had to re-learn it this round when both
  Texture::IsValid and StagingTexture::IsValid had to be restored
  after the build failed.

  Settings fields that are read but never written are dead.
  A Settings struct field has three logical slots: default value,
  setter (Load entry / game settings override), and reader. If the
  setter slot is empty, the field is permanently at its default and
  the reader is dead too - and so is whatever the reader gates.
  bios_patch_tty_enable was an instance of this: dead setter ->
  always-false condition -> dead BIOS::PatchBIOSEnableTTY callee.

== Build verification ==

Build clean on Makefile.libretro platform=unix at the final state.
swanstation_libretro.so size: 7,910,600 -> 7,910,240 bytes (-360).
25 retro_* exports preserved.

The 360-byte .so reduction is real codegen reduction - 64 from the
EnsureVertexBufferSpace impl, 96 from BufferMemoryBarrier impl, 11
from PatchBIOSEnableTTY impl, plus smaller savings from the
CodeBlockKey operator function bodies, the StagingBuffer Read/Write
impls, and eliminated dead-write codegen in CompileBlock.

== Audited and kept ==

(a) Controllers and DMA dispatch: no new finds.
(b) GPU_HW constants (VRAM_UPDATE_TEXTURE_BUFFER_SIZE,
    VERTEX_BUFFER_SIZE, UNIFORM_BUFFER_SIZE,
    MAX_BATCH_VERTEX_COUNTER_IDS, MAX_VERTICES_FOR_RECTANGLE),
    Transparency*/Interlaced* enums, all 19 methods other than
    EnsureVertexBufferSpace.
(c) Vulkan::Util namespace: IsDepthFormat, GetTexelSize,
    GetBlockSize, SafeDestroy* family, SetViewport, SetScissor,
    SetViewportAndScissor, LogVulkanResult (kept alive by
    LOG_VULKAN_ERROR macro with 45 expansions).
    Vulkan::Texture: all methods (IsValid restored as above).
    Vulkan::StagingTexture: all methods (IsValid restored).
    Vulkan::StreamBuffer: all methods - heavily used.
    Vulkan::ShaderCache: GetShaderSPV and GetShaderModule are
    used only internally as building blocks for GetVertexShader
    / GetFragmentShader. Could be made private in a future
    refactor, but visibility-tightening is out of scope for a
    deletion sweep.
    Vulkan::ShaderCompiler::Type::Geometry and ::Compute - reached
    by switch cases in CompileShader; kept as part of the
    type's complete enumeration even though no current caller
    passes those values.
(d) CodeBlockInstruction live flags (is_branch_instruction et al.);
    CodeBlock::GetPC and IsInRAM; FAST_MAP_TABLE_* constants;
    Dispatcher/SingleBlockDispatcher function types.
(e) gpu_pgxp_preserve_proj_fp (game-settings overridden, runtime
    read); display_force_4_3_for_24bit (same pattern);
    gpu_pgxp_tolerance (game-settings overridden, runtime read);
    cdrom_mute_cd_audio (runtime read); controller_enable_rumble
    (read in libretro_host_interface); memory_card_use_playlist_title
    (compared in host_interface for setting-change detection);
    cdrom_load_image_to_ram (referenced from system.cpp);
    log_level (Log::SetFilterLevel target); controller_show_crosshair
    (read in all three HW renderers); enable_8mb_ram (game-settings
    overridden, runtime read in bus.cpp).

12 files changed, 1 insertion(+), 92 deletions(-).
2026-05-15 00:01:04 +02:00
LibretroAdmin
61c08da044 core: dead-code sweep, round 12
Hunting in the smaller subsystems this round - mostly constants and
inline accessors that fell through the cracks of earlier sweeps.
Three finds:

== src/core/cpu_core.h ==

Connected dead-constant chain:

  ICACHE_SLOTS = ICACHE_SIZE / sizeof(uint32_t)
  ICACHE_SLOTS_PER_LINE = ICACHE_SLOTS / ICACHE_LINES

ICACHE_SLOTS_PER_LINE has zero callers anywhere. Its only purpose
was as the divisor in the comment-block describing how the I-cache
is organized. ICACHE_SLOTS in turn was only used by
ICACHE_SLOTS_PER_LINE - so dropping the leaf revealed the
prerequisite is also dead. Both gone.

Plus one dead inline accessor:

  ALWAYS_INLINE Registers& GetRegs()
  {
    return g_state.regs;
  }

Zero callers - the recompiler accesses g_state.regs directly through
the offsetof helpers (State::GPRRegisterOffset / GTERegisterOffset),
and the interpreter accesses g_state.regs through unqualified field
references inside the CPU namespace. The wrapper function was never
called.

The kept ICACHE_* constants are: ICACHE_SIZE, ICACHE_LINE_SIZE,
ICACHE_LINES, ICACHE_TAG_ADDRESS_MASK, ICACHE_INVALID_BITS. These
are all referenced from cpu_core.cpp's icache-fill and icache-lookup
code paths.

== src/core/bus.h ==

  inline constexpr uint32_t RAM_BASE = 0x00000000

Declared with the rest of the PS1 memory-map constants and never
referenced. The RAM region is uniquely identified by its absence in
the address-dispatch ladder (the bus dispatcher checks address <
RAM_MIRROR_END first and falls through to RAM access if no other
region claimed it), so RAM_BASE was never needed - unlike its peers
EXP1_BASE, PAD_BASE, SIO_BASE, etc. which appear in the dispatcher.

All other memory-map constants (EXP1_BASE/SIZE/MASK,
INTERRUPT_CONTROLLER_BASE/SIZE/MASK, DMA_BASE/SIZE/MASK, etc.) ARE
used at exactly one site each in bus.cpp's address ladder. Kept.

== src/core/pad.h ==

  static constexpr uint32_t NUM_SLOTS = 2;

Private constant on the Pad class, declared once at line 40, never
used. Pad uses NUM_CONTROLLER_AND_CARD_PORTS (from controller.h?)
and NUM_MULTITAPS for the actual slot-array sizes - NUM_SLOTS was
an early definition that got replaced and never cleaned up.

Build clean on Makefile.libretro platform=unix at each step.
swanstation_libretro.so size: 7,910,600 -> 7,910,600 bytes (unchanged).
25 retro_* exports preserved.

The size is unchanged because every drop this round was either an
unused constexpr (optimized away by the compiler even when declared)
or an inline accessor whose body was never instantiated. The value
of the round is source clarity.

== Methodology note ==

New pattern: connected dead-constant chains. A constant with a
non-zero grep count can still be dead if every grep hit is inside
the definition of ANOTHER dead constant. When dropping a constant
whose only callers are other constants, always re-grep the entire
chain - the prerequisite may be a leaf in the chain rather than the
root.

For ICACHE_SLOTS the chain was depth-2 (ICACHE_SLOTS_PER_LINE was
the only user, and ICACHE_SLOTS_PER_LINE itself had no users). For
deeper chains the recursion can go further.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7,910,600 -> 7,910,600 bytes (unchanged).
retro_* exports: 25 (unchanged).

3 files changed, 2 insertions(+), 10 deletions(-).
2026-05-14 23:45:00 +02:00
LibretroAdmin
9e37892c07 core: dead-code sweep, round 11 (recompiler)
Audit of the recompiler API in src/core/cpu_recompiler_register_cache.h
and src/core/cpu_recompiler_code_generator.h. Both classes have large
public surfaces (40+ methods on RegisterCache, ~130 on CodeGenerator
including per-arch overrides) which makes them likely candidates for
accumulated dead surface that grew during back-and-forth refactoring.

Two finds:

== src/core/cpu_recompiler_register_cache ==

Five dead methods on RegisterCache - three inline accessors with zero
call sites, and two with non-trivial .cpp implementations and zero
call sites:

  bool IsGuestRegisterCached(Reg guest_reg) const
  bool IsGuestRegisterInHostRegister(Reg guest_reg) const
  std::optional<HostReg> GetHostRegisterForGuestRegister(Reg guest_reg) const

  These three are inline accessors over m_state.guest_reg_state[i].
  All three would be useful for callers that want to query the cache
  state from outside (e.g. a peephole-optimization pass that wants to
  short-circuit instruction emission when the source guest register
  is already live in a host register). No such caller exists in the
  current code-generation pipeline - ReadGuestRegister handles the
  cache-hit fast path internally, and external code never inspects
  the cache state directly. Total grep hits for each: 1 (the decl
  in the header).

  void EnsureHostRegFree(HostReg reg)

  Defined in .cpp at line 198. Iterates the guest-reg-state array
  looking for any guest register currently held in 'reg' and flushes
  it. Looks like a building block for a 'kick a specific host
  register out of the cache' operation - probably planned for a
  fixed-register-allocation path or to satisfy an instruction that
  requires a specific host register for its result. The
  AllocateHostReg(reg, state) overload that ENFORCES a specific
  register exists and is used, but it asserts on conflict rather
  than evicting; EnsureHostRegFree was the planned 'evict and
  retry' helper. Never wired up.

  void ReserveCallerSavedRegisters()

  Defined in .cpp at line 225. Symmetric counterpart to the alive
  ReserveCalleeSavedRegisters - would emit push instructions for
  every caller-saved register and mark them as 'preallocated'. The
  comment 'enabling later use without stack pushes' matches the
  callee-saved pattern. The decision to reserve callee-saved
  registers up-front but NOT caller-saved registers is deliberate
  (callee-saved happens at function prologue, caller-saved happens
  per-call), so the symmetric helper was never wired up.

  Total: 5 methods, 28 header lines + 26 .cpp lines = 54 lines.

== src/core/cpu_recompiler_code_generator ==

Two dead methods on CodeGenerator, present in all three architecture
back-ends:

  void EmitInc(HostReg to_reg, RegSize size)
  void EmitDec(HostReg to_reg, RegSize size)

  Declared in cpu_recompiler_code_generator.h:54-55.

  x64 implementation (cpu_recompiler_code_generator_x64.cpp:773 and
  791) is real - emits inc/dec instructions, dispatched on RegSize_8
  /16/32. 18 lines of switch-on-size per method.

  aarch32 implementation (cpu_recompiler_code_generator_aarch32.cpp
  :461 and 465) is an EMPTY STUB '{}'. The function body is literally
  zero instructions.

  aarch64 implementation (cpu_recompiler_code_generator_aarch64.cpp
  :558 and 562) is also an EMPTY STUB.

  Two of three back-ends are empty stubs, and zero callers exist
  anywhere - the recompiler's integer increment/decrement codegen
  goes through EmitAdd/EmitSub with a constant 1 operand instead.
  EmitInc/EmitDec was likely added during the initial x64 backend
  bring-up and never folded out, then never re-implemented in the
  ARM back-ends because nothing called it.

  Total: 2 methods, 2 header lines + 36 lines x64 impl + 8 lines
  aarch32 stubs + 8 lines aarch64 stubs = 54 lines.

Build clean on Makefile.libretro platform=unix at each step.
swanstation_libretro.so size: 7,910,928 -> 7,910,600 bytes (-328).
25 retro_* exports preserved.

The aarch32/aarch64 changes aren't validated by the unix build
(CPU_ARCH=x64 selects the x64 backend; the other two source files
aren't compiled). The drops there are symmetric to the x64 drop
(same dead method, same dead status), so they're safe and necessary
for consistency - leaving them would leave a defined-but-not-declared
free function in the ARM backends. The aarch32 stubs are also
plain '{}' bodies, which are unambiguously safe to remove.

The 328-byte .so reduction comes from the dropped x64 EmitInc/EmitDec
function bodies (36 lines of switch-on-RegSize plus prologue/epilogue),
the RegisterCache::EnsureHostRegFree and ::ReserveCallerSavedRegisters
implementations, and the eliminated address-table entries.

== Methodology note ==

The empty-stub pattern in the aarch32/aarch64 EmitInc/EmitDec
implementations was the strongest dead-code signal in the whole
sweep series so far - a function declared on a multi-backend
abstract interface where two of three concrete implementations
are literally '{}' indicates the method was added speculatively,
never wired up, and the back-end maintainers correctly refused to
implement what nobody called.

Adding to the running list:

  When auditing a multi-backend abstraction (HW renderer, code
  generator, audio backend, etc.), look for methods whose impls
  diverge sharply in apparent effort - one backend has a full
  implementation, others have empty stubs or one-line forwards
  to no-ops. This is a strong dead-code signal because:
    - If callers really used the method, the empty-stub backend
      would be visibly broken
    - The fact that nobody noticed the empty stub means there is
      no caller
  Always verify with a full-tree grep for callers before dropping,
  but expect this pattern to be load-bearing.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7,910,928 -> 7,910,600 bytes (-328).
retro_* exports: 25 (unchanged).

6 files changed, 108 deletions(-).
2026-05-14 23:04:23 +02:00
LibretroAdmin
c8d417960c common, core: dead-code sweep, round 10
A new pattern this round: dead flag constants where the checks
remain inside the implementing module but no caller passes them.
These look alive on a simple keyword grep because each constant
has 1-2 references, but every reference is inside the function
that checks the flag - never anywhere that SETS it. Result:
unconditional branches in the find loop.

Plus one straightforward file-static helper find.

== src/core/cheats.cpp ==

  static bool IsValidScanAddress(PhysicalMemoryAddress address)

  File-static, defined once at line 18, zero callers anywhere in
  the tree. Looks like a remnant from an old cheat-scan code path
  that's been refactored elsewhere - the cheat engine now resolves
  scan addresses through the standard CPU/Bus address-mapping helpers
  instead.

  19 lines removed.

== src/common/file_system.h flag constants ==

Four flag constants in the FileSystem namespace that no caller in
the tree ever passes:

  FILESYSTEM_FILE_ATTRIBUTE_READ_ONLY  - SET in the Windows FindFiles
    path on FILE_ATTRIBUTE_READONLY but never tested by any consumer
    of FILESYSTEM_FIND_DATA::Attributes.

  FILESYSTEM_FILE_ATTRIBUTE_COMPRESSED - never set, never tested.

  FILESYSTEM_FIND_FOLDERS              - checked in the Windows and
    POSIX directory branches via 'if (!(Flags & FOLDERS))', but the
    only two FindFiles callers in the tree (host_interface.cpp:141
    and texture_replacements.cpp:177) pass FILES, not FOLDERS. The
    directory branch therefore always continues; the
    'outData.Attributes |= DIRECTORY' line was unreachable.

  FILESYSTEM_FIND_KEEP_ARRAY           - checked once to suppress
    the pResults->clear() at the top of FindFiles. Never set.
    pResults is always cleared.

Dropped constants, dropped the matching checks/sets inside
file_system.cpp, simplified the directory branches in both the
Windows and POSIX variants of RecursiveFindFiles to just recurse
(if FIND_RECURSIVE is set) and continue.

The FILESYSTEM_FIND_DATA::Attributes field is now dead too - the
only set was via FILE_ATTRIBUTE_READ_ONLY (dropped) and the unreachable
DIRECTORY assignment (dropped). The two 'outData.Attributes = 0;'
init lines are now dead writes. Dropped the field along with both
inits.

== src/core/texture_replacements.cpp ==

  if (fd.Attributes & FILESYSTEM_FILE_ATTRIBUTE_DIRECTORY)
    continue;

  Defensive check at TextureReplacements::FindTextures was already
  unreachable - the caller passes FILES (not FOLDERS), so FindFiles
  never emits a directory entry. Drop the check (and it'd no longer
  compile after the Attributes field removal anyway).

Build clean on Makefile.libretro platform=unix at each step.
swanstation_libretro.so size: 7,910,928 -> 7,910,928 bytes (unchanged).
25 retro_* exports preserved.

The size is unchanged because both flag constants and dead branches
optimize away to nothing under -O2 anyway. The value of this commit
is source-level clarity: removing 'half-dead' surface that grep
turned up but inspection showed was inert.

== Methodology note ==

New pattern: dead flag constants where the test remains but the
set is missing. The grep signature is:

  CONST: appears N times in the source tree (small N, 1-3)
  Every appearance is either:
    - the declaration itself
    - a check inside the function that consumes the flag

If NO grep hit is on a caller passing the flag in (e.g., as part
of a '|'-joined argument), the constant is dead. The check that
references it always takes the same branch and can be deleted
unconditionally. This compounds: when a now-unconditional branch
drops a write to an output field, the field's other writes need
re-auditing too, since they may now be the only writes - and if
nobody reads the field, it's dead.

Caveat: this pattern trims defensive code that might be helpful
when a future caller wants to use the flag. The trade is source
clarity now vs. having to re-add the branch later. For this
codebase's FindFiles flags, the surface area has been stable
since import and the two callers don't suggest imminent need.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7,910,928 -> 7,910,928 bytes (unchanged).
retro_* exports: 25 (unchanged).

4 files changed, 7 insertions(+), 45 deletions(-).
2026-05-14 22:57:25 +02:00
LibretroAdmin
4f2fac2a53 core: dead-code sweep, round 9
Continuing the pure-virtual hunt from rounds 7 and 8. One large
find this round - a dead pure virtual on the GPU base class with
five subclass overrides:

  GPU::GetRendererType() const = 0

All five overrides are small accessor functions returning a
constant GPURenderer enum value identifying which backend the
subclass implements (Software, HardwareOpenGL, HardwareVulkan,
HardwareD3D11, HardwareD3D12). The method is never called
anywhere in the tree - grep for '->GetRendererType()' and
'.GetRendererType()' across all *.cpp and *.h files returns zero
matches. The renderer-selection logic uses the user-facing
'gpu_renderer' setting directly via Settings::ParseRendererName /
Settings::GetRendererName rather than runtime polymorphic dispatch
on an already-constructed GPU instance.

Dropped per-subclass implementations:

  GPU_SW::GetRendererType()                  gpu_sw.cpp:40
                                             gpu_sw.h:18
  GPU_HW_OpenGL::GetRendererType()           gpu_hw_opengl.cpp:592
                                             gpu_hw_opengl.h:94
  GPU_HW_Vulkan::GetRendererType()           gpu_hw_vulkan.cpp:653
                                             gpu_hw_vulkan.h:100
  GPU_HW_D3D11::GetRendererType()            gpu_hw_d3d11.cpp:443
                                             gpu_hw_d3d11.h:98
  GPU_HW_D3D12::GetRendererType()            gpu_hw_d3d12.cpp:31
                                             gpu_hw_d3d12.h:26

The two Windows-only subclasses (D3D11, D3D12) had override defs
that the unix-build toolchain doesn't compile but which would
break the Windows build if we left them referencing the deleted
pure virtual. Updated those declarations too, per the round 7
methodology note about full-tree grep on multi-backend
interfaces.

Build clean on Makefile.libretro platform=unix at each step.
swanstation_libretro.so size: 7,911,112 -> 7,910,928 bytes (-184).
25 retro_* exports preserved.

The 184-byte reduction reflects five eliminated vtable slots
(one per subclass: GPU_SW + GPU_HW_OpenGL + GPU_HW_Vulkan +
GPU_HW_D3D11 + GPU_HW_D3D12) plus five tiny function bodies that
each compiled to a single MOV + RET. D3D11/D3D12 overrides are
in build-guarded source files not compiled on unix, but their
vtable contribution and override impls are still useful to
clean up for the Windows build's benefit.

== Methodology note ==

The 'dead pure-virtual with all-stub overrides' pattern from
rounds 7-8 now has a name and a recipe. Applied verbatim:

  1. grep 'virtual ... = 0' on the abstract base class header.
  2. For each candidate, find all override defs across all
     subclass *.h and *.cpp files.
  3. Search for ACTUAL CALL SITES - '->GetRendererType()' and
     '.GetRendererType()' patterns, NOT just textual mentions
     of the function name.
  4. If zero call sites exist, the pure virtual is dead.

For GetRendererType, step 3 returned EMPTY. The only matches in
the tree were the override defs themselves and the impls. No
runloop / settings / system / host-interface code ever asks a
constructed GPU* what kind of GPU it is.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7,911,112 -> 7,910,928 bytes (-184).
retro_* exports: 25 (unchanged).

11 files changed, 37 deletions(-).
2026-05-14 22:29:34 +02:00
LibretroAdmin
449c7e4185 core: dead-code sweep, round 8
Another vtable-slot reduction round. Continuing the round 7
methodology of looking for pure virtuals where every override
is a trivial accessor with no external callers.

Three dead pure virtuals on the HostDisplayTexture interface,
plus the per-subclass override implementations, plus the
now-orphaned member fields that only existed to back the
dropped accessors:

  HostDisplayTexture::GetLayers()
  HostDisplayTexture::GetLevels()
  HostDisplayTexture::GetFormat()

All three were declared virtual ... = 0 on the base, implemented
as small constant-or-forwarding accessors on each of the three
subclasses (LibretroD3D11HostDisplayTexture,
LibretroVulkanHostDisplayTexture, LibretroOpenGLHostDisplayTexture),
and never called anywhere outside of the override defs themselves.
The display-pixel-format negotiation and depth/layer queries that
the renderer backends do go through the internal Texture types
directly (m_vram_texture.GetFormat(), m_display_pixels_texture.GetFormat(),
m_downsample_texture.GetLevels(), etc.) rather than through the
abstract HostDisplayTexture* polymorphic interface.

Build clean on Makefile.libretro platform=unix at each step.
swanstation_libretro.so size: 7,911,560 -> 7,911,112 bytes (-448).
25 retro_* exports preserved.

The kept HostDisplayTexture interface is now:
  virtual void* GetHandle() const = 0;    // 6 callers
  virtual uint32_t GetWidth() const = 0;  // alive on HostDisplayTexture*
  virtual uint32_t GetHeight() const = 0; // alive on HostDisplayTexture*
  virtual uint32_t GetSamples() const = 0; // alive on HostDisplayTexture*
                                           // (gpu_hw_vulkan.cpp:767 etc.)

== Per-subclass dropped overrides + fields ==

  LibretroD3D11HostDisplayTexture (gpu_hw_d3d11.cpp)
    GetLayers()    - was returning constant 1
    GetLevels()    - was forwarding to m_texture.GetLevels()
    GetFormat()    - was returning m_format
    ctor signature simplified: dropped HostDisplayPixelFormat format
                               and bool dynamic parameters
    fields dropped: HostDisplayPixelFormat m_format,
                    bool m_dynamic
    m_dynamic was set in ctor but never read - dead beyond the
    virtual it backed.

  LibretroVulkanHostDisplayTexture (gpu_hw_vulkan.cpp)
    GetLayers()    - was forwarding to m_texture.GetLayers()
    GetLevels()    - was forwarding to m_texture.GetLevels()
    GetFormat()    - was returning m_format
    ctor signature simplified: dropped HostDisplayPixelFormat format
    fields dropped: HostDisplayPixelFormat m_format

  LibretroOpenGLHostDisplayTexture (gpu_hw_opengl.cpp)
    GetLayers()    - was returning constant 1
    GetLevels()    - was returning constant 1
    GetFormat()    - was returning m_format
    ctor signature simplified: dropped HostDisplayPixelFormat format
    fields dropped: HostDisplayPixelFormat m_format

  No D3D12 LibretroHostDisplayTexture subclass exists (D3D12 uses
  the LibretroD3D11HostDisplay* path for display - only the emulator
  backend differs).

== Methodology applied ==

This is the methodology from round 7 working again: pure-virtual
audits across multi-backend interfaces yield real codegen reduction.
The pattern is now well-rehearsed:

  1. List pure virtuals on the abstract base class
  2. For each, find all override defs in all subclasses
  3. Look for external callers via base-pointer dispatch
     (htex->X(), texture_handle->X(), or similar
     HostDisplayTexture*->X() patterns)
  4. If zero such callers exist - even when the internal Texture
     subobjects ARE used directly with the same method name -
     the pure virtual is dead.

  The grep that establishes this requires NO file-exclusion - the
  round 7 Windows-build-breaker near-miss showed that filtering by
  the unix-build subset is unsound. Run grep against the full tree
  (--include='*.cpp' --include='*.h' across all of src/) and read
  every match.

For these three virtuals every grep hit was either:
  - Inside the abstract HostDisplayTexture class definition
  - Inside one of the three subclass override defs
  - A direct call on an internal Texture (m_vram_texture, etc.) -
    NOT on a HostDisplayTexture* pointer

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7,911,560 -> 7,911,112 bytes (-448).
retro_* exports: 25 (unchanged).

4 files changed, 9 insertions(+), 26 deletions(-).
2026-05-14 22:03:47 +02:00
LibretroAdmin
6a467bfe2b common, core: dead-code sweep, round 7
Two finds this round. Smaller than rounds 2-6 because the obvious
surface is increasingly exhausted, but both are real:

* A genuine dead pure-virtual interface method on HostDisplay,
  RenderSoftwareCursor(), with four empty-stub overrides across
  all subclasses. This is the first vtable-slot reduction of the
  sweep series - actual codegen change from collapsing the vtable,
  not just removed function bodies.

* A decl-only template helper in common/bitutils.h whose sibling
  (CountLeadingZeros) is alive.

Build clean on Makefile.libretro platform=unix at each step.
swanstation_libretro.so size: 7,911,792 -> 7,911,560 bytes (-232).
25 retro_* exports preserved.

== common/bitutils ==

  template<typename T>
  ALWAYS_INLINE unsigned CountTrailingZeros(T value)
    Inline template + #ifdef _WIN32 platform split (_BitScanForward
    vs __builtin_ctz). Zero callers anywhere - the only bit-scan
    helper actually used is CountLeadingZeros (3 callers, all in
    the recompiler register allocator for choosing the next-free
    host register from the available-register bitmap).

== core/host_display + 4 subclasses ==

  virtual void HostDisplay::RenderSoftwareCursor() = 0
    The pure-virtual no-arg variant. Zero direct call sites anywhere
    in the tree - the actual cursor render path uses the 5-arg
    sibling overload (RenderSoftwareCursor(int32_t left, int32_t top,
    int32_t width, int32_t height, HostDisplayTexture* texture_handle)),
    invoked from gpu_hw_d3d11.cpp:382, gpu_hw_vulkan.cpp:554, and
    gpu_hw_opengl.cpp:541 inside each backend's display-render path.

  Subclass overrides dropped:
    LibretroHostDisplay::RenderSoftwareCursor() {}
      libretro_host_display.h:25, libretro_host_display.cpp:91
    LibretroD3D11HostDisplay::RenderSoftwareCursor() {}
      gpu_hw_d3d11.h:55, gpu_hw_d3d11.cpp:300
    LibretroVulkanHostDisplay::RenderSoftwareCursor() {}
      gpu_hw_vulkan.h:56, gpu_hw_vulkan.cpp:438
    LibretroOpenGLHostDisplay::RenderSoftwareCursor() {}
      gpu_hw_opengl.h:62, gpu_hw_opengl.cpp:462

  All four subclass overrides had empty function bodies '{}' - the
  classic sign of a pure-virtual that was never wired up but had to
  be implemented to satisfy the C++ requirement. There is no
  LibretroD3D12HostDisplay subclass (D3D12 has GPU_HW_D3D12 only,
  no host-display variant), so 4 overrides is the full count.

  The .so size dropped by 232 bytes - removing the vtable slot
  shrinks every subclass's vtable by one pointer entry (8 bytes per
  class on x86-64 = 32 bytes across the 4 subclasses + 8 bytes for
  the base + alignment) and elides 4 empty function bodies (each
  4-12 bytes of prologue/epilogue depending on calling convention).
  This is the first real vtable-slot reduction of the sweep series.

== Audited and kept ==

  HostDisplay::GetRenderDevice() / GetRenderContext()
    Initially LOOKED dead under platform=unix audit - all four
    subclass overrides (Libretro, OpenGL, Vulkan) return nullptr,
    and grep showed no caller in any *.cpp file built on unix.
    REVERTED after spotting that gpu_hw_d3d11.cpp:461-462 actually
    consumes them: LibretroD3D11HostDisplay::GetRenderDevice()
    returns m_device.Get() (real ID3D11Device*), and GPU_HW_D3D11
    upcasts the result to ID3D11Device* during initialization.
    gpu_hw_d3d11.cpp is Windows-only (Makefile.libretro guards it
    behind ifeq (IS_WINDOWS,1)), so the unix-build .so doesn't link
    those call sites and the unix toolchain doesn't fail when the
    interface is removed - but a Windows build would break.

    This is the second methodology pitfall added this round (see
    notes below).

== Methodology notes ==

Two additions to the running list:

* Pure virtuals with all-stub overrides are a high-value find.
  They reduce *both* source lines AND vtable size in every
  subclass. The pattern: 'virtual ... = 0;' declaration where
  every override's body is '{}' and the only callers are inside
  the base class (which never calls them). RenderSoftwareCursor()
  had this exact shape and yielded the first real codegen change
  from a dead-virtual drop in the series. Look for additional
  candidates where the override count equals the subclass count
  and every body is empty.

* Build-guarded subsystems hide real callers from the unix build.
  Helpers like GetRenderDevice() looked dead under a unix-build
  audit because their D3D11-side caller is in a file that
  Makefile.libretro doesn't compile when IS_WINDOWS isn't set.
  The unix .so wouldn't link the caller and the unix compiler
  wouldn't complain when the interface is removed. The drop
  silently compiles on unix and silently breaks Windows.

  Rule: when an interface method exists on the HostDisplay base
  class (or any other multi-backend abstraction), grep the FULL
  source tree, not just the unix-build subset, before declaring
  it dead. The Makefile.libretro guards for D3D11/D3D12 are at:
    ifeq ($(IS_WINDOWS),1)
      SOURCES_CXX += gpu_hw_d3d11.cpp
      SOURCES_CXX += [d3d11 utility files]
    endif
    ifeq ($(IS_WINDOWS),1)
      SOURCES_CXX += gpu_hw_d3d12.cpp
    endif
  Anything inside those guards is invisible to the unix build but
  alive on Windows. Always grep --include='*.cpp' across the WHOLE
  tree (no exclusions) on multi-backend interface candidates.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7,911,792 -> 7,911,560 bytes (-232).
retro_* exports: 25 (unchanged).

10 files changed, 31 deletions(-).
2026-05-14 21:56:43 +02:00
LibretroAdmin
108bb518ab common: dead-code sweep, round 6 (vulkan subsystem)
Round 6 attacks the common/vulkan/ subsystem in one omnibus,
collecting six independent audits. Same approach as rounds 2-5:
zero-caller checks with second-pass verification, then drop. Build
clean on Makefile.libretro platform=unix at each intermediate step.

This round is the largest .so reduction of the series:
swanstation_libretro.so size: 7,922,816 -> 7,911,792 bytes (-11,024).
Most of the codegen reduction comes from the util.cpp drops (4
function bodies including the case-table-driven IsCompressedFormat
and GetLinearFormat plus the small ClampRect2D and GetAlphaBlendFactor
helpers), the StagingBuffer barrier helpers (3 function bodies, each
emitting a vkBufferMemoryBarrier on a !m_coherent guard), the
StagingTexture ReadTexel/WriteTexel singular-variant pair, the
GraphicsPipelineBuilder AddBlendAttachment + SetLineWidth pair, and
the DescriptorSetUpdateBuilder AddImageDescriptorWrite +
AddSamplerDescriptorWrite pair. The Context inline-accessor drops
yield zero codegen change but improve header clarity by surfacing
which queries the rest of the codebase actually exercises.

25 retro_* exports preserved.

== common/vulkan/util ==

Six dead helpers dropped:

  bool IsCompressedFormat(VkFormat format)
    Decl + 14-line case-table impl returning true for BC1/BC2/BC3/BC7
    UNORM blocks. Zero callers anywhere - swanstation doesn't deal
    with compressed texture uploads (PSX VRAM is 16bpp raw); this
    must be Dolphin/DuckStation-inherited surface.

  VkFormat GetLinearFormat(VkFormat format)
    Decl + 14-line case-table impl mapping SRGB formats to their
    UNORM equivalents (R8_SRGB -> R8_UNORM, etc.). Zero callers
    anywhere - all Vulkan texture creations in swanstation use UNORM
    or _SFLOAT formats directly; no SRGB-textured render targets.

  VkRect2D ClampRect2D(const VkRect2D&, uint32_t, uint32_t)
    Decl + 9-line impl. Clamps a VkRect2D against a width/height
    bound using std::clamp + std::min. Zero callers - the rectangle
    clamping in gpu_hw_vulkan.cpp is done inline with manual
    std::min/std::max sequences (in the rect-rendering and blit
    paths), not via this helper.

  VkBlendFactor GetAlphaBlendFactor(VkBlendFactor)
    Decl + 14-line case-table impl mapping SRC/DST_COLOR factors
    to SRC/DST_ALPHA. Zero callers - the blend mode logic in
    gpu_hw_vulkan.cpp builds VkPipelineColorBlendAttachmentState
    inline with the correct alpha factor chosen at the call site,
    rather than transforming color factors after the fact.

  void SafeDestroyShaderModule(VkShaderModule&)
    Decl + 8-line impl. Two textual references in gpu_hw_vulkan.h:161
    and :262, but both are inside comments describing past behavior;
    no live call exists. The actual shader-module teardown in
    gpu_hw_vulkan.cpp uses vkDestroyShaderModule directly within
    DestroyShaders.

  void SafeDestroySemaphore(VkSemaphore&)
    Decl + 8-line impl. Zero callers - swanstation doesn't manage
    its own semaphores; the swapchain/present-image-acquire semaphores
    live entirely inside the libretro hardware-renderer harness, which
    handles them via the retro_hw_render_interface_vulkan callbacks.

  LogVulkanResult stays (alive via the LOG_VULKAN_ERROR macro - 7
  callsites in shader_cache.cpp).

== common/vulkan/context ==

Nine dead pieces dropped:

  ALWAYS_INLINE VkInstance Context::GetVulkanInstance() const
  ALWAYS_INLINE const VkQueueFamilyProperties&
    Context::GetGraphicsQueueProperties() const
  ALWAYS_INLINE bool Context::SupportsGeometryShaders() const
  ALWAYS_INLINE bool Context::SupportsDualSourceBlend() const
  ALWAYS_INLINE VkDescriptorPool Context::GetGlobalDescriptorPool() const
  ALWAYS_INLINE VkDescriptorPool Context::GetCurrentDescriptorPool() const
  ALWAYS_INLINE VkFence Context::GetCurrentCommandBufferFence() const
    All seven decl-only inline accessors. Zero callers each. The
    Context fields they exposed are still used internally
    (m_instance is used at vkDestroyInstance time, the descriptor
    pool fields are used by AllocateDescriptorSet/AllocateGlobal-
    DescriptorSet, m_graphics_queue_properties is dead - see below).

  void Context::DeferBufferViewDestruction(VkBufferView)
    Decl + 5-line impl. Zero callers. swanstation creates
    VkBufferViews for the texture-stream-buffer texel-buffer-view
    (gpu_hw_vulkan.cpp:1434 via bvbuilder); those are torn down
    synchronously, not via this deferred-destruction queue.

  void Context::DeferPipelineDestruction(VkPipeline)
    Decl + 5-line impl. Zero callers. Pipeline teardown happens
    through SafeDestroyPipeline (which calls vkDestroyPipeline
    on the current device synchronously); no deferred path needed.

  VkQueueFamilyProperties m_graphics_queue_properties = {}
    Member field on Context. Set during Initialize but read only by
    the dropped GetGraphicsQueueProperties() accessor. Now dead.

  EnableDebugUtils/DisableDebugUtils stay (called from Context's own
  initialization and shutdown paths). The Context's other inline
  accessors stay (GetPhysicalDevice/GetDevice/etc. have 1+ callers).

== common/vulkan/builders ==

Five zero-caller pipeline-builder helpers dropped:

  GraphicsPipelineBuilder::SetGeometryShader(VkShaderModule)
    Decl only. Zero callers - swanstation has no geometry shader
    in any rendering path. (The D3D12 SetGeometryShader is alive
    at d3d12/util.h:105/109 but is a separate class.)

  GraphicsPipelineBuilder::SetLineWidth(float)
    Decl + 4-line impl. Zero callers - swanstation rasterizes
    polygons and rectangles via triangle lists; line primitives go
    through the same path with VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
    not LINE_LIST. The pipeline state never customizes lineWidth
    from its default 1.0f.

  GraphicsPipelineBuilder::AddBlendAttachment(...)
    Decl + 18-line impl. Zero callers - the codebase uses the
    sibling SetBlendAttachment(uint32_t attachment, ...) variant
    (4 callers in gpu_hw_vulkan.cpp), which lets the caller place
    state at a specific attachment index rather than appending.

  DescriptorSetUpdateBuilder::AddImageDescriptorWrite(set, binding,
    view, layout)
  DescriptorSetUpdateBuilder::AddSamplerDescriptorWrite(set, binding,
    sampler)
    Both decl + 17-line impls. Zero callers - swanstation never
    binds sampled-images or samplers separately; everything uses
    AddCombinedImageSamplerDescriptorWrite (9 callers in
    gpu_hw_vulkan.cpp + others). The separate-image-and-sampler
    descriptor-write helpers were unused infrastructure.

  ClearBlendAttachments stays (used internally at builders.cpp:323),
  AddDynamicState stays (used at builders.cpp:340 inside
  SetDynamicViewportAndScissorState), SetViewport / SetScissorRect /
  SetMultisamples (the VkSampleCountFlagBits overload) all stay
  (used internally during pipeline-builder reset at builders.cpp:146-148).

== common/vulkan/staging_buffer ==

Six dead pieces dropped:

  ALWAYS_INLINE VkDeviceSize StagingBuffer::GetMapOffset() const
  ALWAYS_INLINE VkDeviceSize StagingBuffer::GetMapSize() const
  ALWAYS_INLINE bool StagingBuffer::IsCoherent() const
    Decl-only inline accessors. Zero callers - the map-tracking
    fields are read internally during Read/Write/InvalidateCPUCache,
    not via these public accessors. The coherency flag is read via
    direct member access (m_coherent) at all 4 internal sites.

  void StagingBuffer::InvalidateGPUCache(VkCommandBuffer, ...)
  void StagingBuffer::PrepareForGPUWrite(VkCommandBuffer, ...)
  void StagingBuffer::FlushGPUCache(VkCommandBuffer, ...)
    Three decl + 9-line impls. Each issues a vkBufferMemoryBarrier
    via Util::BufferMemoryBarrier on the !m_coherent path. Zero
    callers - swanstation's staging-buffer usage is upload-only
    via Read/Write (which handle their own cache invalidation
    inline), not the more general 4-step upload/readback dance
    these helpers were designed for.

  Map, Unmap, FlushCPUCache, InvalidateCPUCache, Read, Write, Create,
  Destroy, AllocateBuffer all stay (used by the upload path).

== common/vulkan/staging_texture ==

Three dead pieces dropped:

  ALWAYS_INLINE bool StagingTexture::IsMapped() const
    Decl-only inline that forwards to m_staging_buffer.IsMapped().
    Zero callers - staging textures stay persistently mapped after
    Create(), so this query is never needed.

  void StagingTexture::ReadTexel(uint32_t, uint32_t, void*)
  void StagingTexture::WriteTexel(uint32_t, uint32_t, const void*)
    Both decl + 5-line impls. Zero callers - the plural-form
    ReadTexels (1 caller at gpu_hw_vulkan.cpp:2387 for VRAM
    readback) and WriteTexels (1 caller at gpu_hw_vulkan.cpp:103
    for the texture-replacement upload path) are the only forms
    actually used. The singular variants were never called.

== common/vulkan/texture ==

Two dead inline accessors dropped:

  ALWAYS_INLINE bool Texture::IsOwned() const
    Returns m_device_memory != VK_NULL_HANDLE. Zero callers - the
    distinction between owned and wrapped images mattered when
    Vulkan textures could be constructed from raw VkImage handles
    (e.g. for swapchain back-buffers), but swanstation's libretro
    hardware-renderer harness doesn't expose its swapchain to the
    core directly. All Texture instances in swanstation are owned.

  ALWAYS_INLINE VkImageViewType Texture::GetViewType() const
    Returns m_view_type. Zero callers - the view type is set at
    Create() time and not interrogated thereafter; swanstation
    uses VK_IMAGE_VIEW_TYPE_2D exclusively and the few _CUBE/_3D
    queries that would need this don't exist.

  IsValid, GetWidth, GetHeight, GetLevels, GetLayers, GetMipWidth/
  GetMipHeight, GetFormat, GetSamples, GetLayout, GetImage, GetView
  all stay (1+ callers each).

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7,922,816 -> 7,911,792 bytes (-11,024).
retro_* exports: 25 (unchanged).

== Methodology notes ==

This round added two cases to the running list of methodology pitfalls:

* Perfect-forwarding wrappers (added in round 5 after the BatchVertex
  near-miss) caught again here. None tripped this round - all the
  vulkan builder/context helpers are direct-call sites.

* The 'exclude the defining file' grep filter caught me on StreamBuffer:
  GetCurrentSize and GetCurrentSpace looked zero-call when I excluded
  src/common/vulkan/stream_buffer.* (the standard rule), but they are
  in fact used at gpu_hw_vulkan.cpp:879,1425,1434 - the second-pass
  grep without exclusion found them. The fix: when the grep returns 0
  on the exclude pass, always re-run without any exclusion to verify
  before committing to a drop. Added to the methodology list.

* Comment-only references caught one: SafeDestroyShaderModule has two
  textual mentions inside comments at gpu_hw_vulkan.h:161,262 but no
  live call. The grep count was 2 with exclusion, which initially
  looked alive. Inspecting the matches showed both were comments
  explaining past behavior, not live code. Drop applied. The pattern
  to watch: low single-digit hit counts (1-3) outside the defining
  file are not automatically 'alive' - inspect each.

11 files changed, 265 deletions(-).
2026-05-14 21:34:28 +02:00
LibretroAdmin
64e22faf7f common, core: dead-code sweep, round 5
Four small zero-caller drops, all decl-only inlines / decl-only
function prototypes / decl-only constants. No codegen change
expected, and indeed the .so size is unchanged at 7,922,816
bytes. Build clean on Makefile.libretro platform=unix.

Smaller than rounds 2-4 because the obvious decl-level finds in
core/ headers are largely exhausted; what remains is either
already-deleted, hardware-register documentation that should not
be touched (e.g. IRQ7/SIO/IRQ10 enum values, DMADirection enum,
GPUSTAT bitfields), tightly self-coupled (recompiler subsystem
where every helper has 4+ internal callers), or under build
guards (D3D11/D3D12 not compiled on platform=unix).

25 retro_* exports preserved.

== core/gpu ==

  static constexpr uint32_t GPU::MAX_RESOLUTION_SCALE = 32
    One of four constants in a comma-separated declaration on
    gpu.h:41. Zero callers anywhere in the tree. The actual
    resolution-scale cap flows through Settings::gpu_resolution_scale
    (clamped against display capabilities, not against this
    constant). MAX_FIFO_SIZE (HeapFIFOQueue template parameter,
    1 use at gpu.h:490), DOT_TIMER_INDEX (4 callers), and
    HBLANK_TIMER_INDEX (9 callers) all stay.

== core/gpu_types ==

  ALWAYS_INLINE void GPUBackendDrawPolygonCommand::Vertex::Set(
      int32_t x_, int32_t y_, uint32_t color_, uint16_t texcoord_)
    Decl-only inline. Zero callers - the polygon-vertex fill site
    in gpu_hw.cpp:NewDrawPolygonCommand assigns vert->x, vert->y,
    vert->texcoord, vert->color directly via the per-vertex
    field accesses rather than through this Set() helper. The
    sibling GPUBackendDrawLineCommand::Vertex::Set(x, y, color)
    stays (4 callers in gpu_hw.cpp), and GPU_HW::BatchVertex::Set
    (the 8-arg packed_texcoord overload AND the 9-arg separate-u/v
    overload) both stay - the 9-arg one is exercised by
    AddNewVertex<Args...> perfect-forwarding (6 callers at
    gpu_hw.cpp:703-709).

== core/cpu_core_private ==

Two zero-caller inline helpers:

  ALWAYS_INLINE uint32_t GetICacheFillTagForAddress(
      VirtualMemoryAddress address)
    Decl-only inline returning
    GetICacheTagForAddress(address) | invalid_bits[(address >> 2) & 0x03u].
    Zero callers. The icache-fill path uses CheckAndUpdateICacheTags
    (in cpu_core.cpp) which writes the tag-with-invalid-bits
    pattern via its own local code; this helper was never used.
    Sibling icache helpers (GetICacheTagForAddress, GetICacheLine,
    GetICacheLineOffset, GetICacheTagMaskForAddress,
    CompareICacheTag) all stay.

  ALWAYS_INLINE VirtualMemoryAddress PhysicalAddressToVirtual(
      PhysicalMemoryAddress address, Segment segment)
    Decl-only inline that ORs the physical address with a
    segment base (0x00000000 / 0x80000000 / 0xA0000000 / 0xE0000000)
    from a 4-element std::array. Zero callers. The reverse
    direction (VirtualAddressToPhysical) is alive at 3 callers,
    used by the cache hot path. Going the other way (turning a
    physical address back into a virtual one) never came up.
    The Segment enum survives (used by GetSegmentForAddress and
    by cpu_recompiler_code_generator_{x64,aarch32,aarch64}.cpp at
    one site each).

== core/cpu_recompiler_thunks ==

  void Recompiler::Thunks::CheckAndUpdateICache(uint32_t pc, uint32_t line_count)
    Decl only, no impl, no callers. The actual JIT-side icache
    handling goes through EmitICacheCheckAndUpdate (a code-emitter
    method, not a thunk) which performs the check-and-update
    inline; the trampoline declared here was either never written
    or removed at the same time as its caller.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7922816 -> 7922816 bytes (unchanged).
retro_* exports: 25 (unchanged).

4 files changed, 1 insertion(+), 21 deletions(-).
2026-05-14 21:14:59 +02:00
LibretroAdmin
11b777e4a6 common, core: dead-code sweep, round 4
Eight independent audits collected into one omnibus, same shape as
rounds 2 and 3. Build clean on Makefile.libretro platform=unix at
each intermediate step.

swanstation_libretro.so size: 7927960 -> 7922816 bytes (-5144).
Most of the codegen reduction comes from three sources: the two
shadergen drops (GenerateFillFragmentShader / GenerateSampleFragmentShader
remove ~30 lines of std::stringstream-emitting body each), the
CDROMAsyncReader::WaitForIdle drop (a real function body with a
mutex acquisition and cv wait), the texture_replacements
GetVRAMWriteDumpFilename drop (a large function body with path
manipulation, mkdir, and string formatting), and the
HostDisplay::CalculateSoftwareCursorDrawRect pair drop (two
function bodies). The remaining drops are decl-only inline
accessors whose removal yields zero codegen change but improves
header clarity.

25 retro_* exports preserved.

== core/cdrom_async_reader ==

Three zero-caller methods:

  uint32_t CDROMAsyncReader::GetBufferedSectorCount() const
  bool     CDROMAsyncReader::HasBufferedSectors() const
    Both decl-only inline accessors returning m_buffer_count.load()
    or a comparison against zero. Zero callers anywhere - the
    readahead/readback code paths use HasMedia, GetSectorBuffer,
    GetLastReadSector, and WaitForReadToComplete to coordinate
    sector flow; the buffer occupancy is internal state only.

  void CDROMAsyncReader::WaitForIdle()
    Decl + 8-line impl. Zero callers. The shutdown path uses
    StopThread which handles join + idle waiting; nothing else
    asks the async reader to drain without tearing down the worker.

== core/gpu_sw_backend ==

Both GetPixelPtr overloads dropped:

  const uint16_t* GPU_SW_Backend::GetPixelPtr(uint32_t x, uint32_t y) const
  uint16_t*       GPU_SW_Backend::GetPixelPtr(uint32_t x, uint32_t y)
    Two decl-only inline accessors returning &m_vram[VRAM_WIDTH * y + x].
    Zero callers anywhere - the rasterizer reads pixels via GetPixel
    (value, not pointer) and writes via SetPixel (also value). No
    code path needs a raw pointer into the VRAM array; bulk VRAM
    access goes through the m_vram member directly within
    GPU_SW_Backend.

  GetPixel and SetPixel survive at 16+ and 1+ callers respectively.

== core/shadergen ==

Two unused fragment-shader generators dropped:

  std::string ShaderGen::GenerateFillFragmentShader()
    Decl + 15-line impl. Returns GLSL/HLSL that writes u_fill_color
    to o_col0 and o_depth. Zero callers - GPU_HW_ShaderGen has its
    own GenerateVRAMFillFragmentShader for VRAM fills, and the
    display copy path uses GenerateCopyFragmentShader. No callers
    of the ShaderGen-base version exist; it was likely sibling-
    referenced once from a different backend that has since
    consolidated.

  std::string ShaderGen::GenerateSampleFragmentShader()
    Decl + 13-line impl. Returns GLSL/HLSL that samples samp0 at
    v_tex0 into o_col0. Zero callers - the actual sampling shaders
    are produced by GPU_HW_ShaderGen specializations, not via this
    generic helper. Apparent vestige of an earlier generic pipeline
    where the ShaderGen base could be used directly.

  GenerateCopyFragmentShader stays (2 callers).

== core/host_display ==

Both CalculateSoftwareCursorDrawRect overloads dropped:

  std::tuple<int32_t, int32_t, int32_t, int32_t>
    HostDisplay::CalculateSoftwareCursorDrawRect() const
  std::tuple<int32_t, int32_t, int32_t, int32_t>
    HostDisplay::CalculateSoftwareCursorDrawRect(int32_t cursor_x, int32_t cursor_y) const

  The no-arg version forwarded to the 2-arg one using
  m_mouse_position_{x,y}. The 2-arg one computed an axis-aligned
  bounding box around the cursor texture centered at the given
  cursor coordinates. Both decl + impl, zero callers. The cursor
  draw paths in each renderer backend compute the cursor rect
  inline using CalculateDrawRect and m_cursor_texture, not via
  this helper.

  HasSoftwareCursor (the bool predicate driving those paths) and
  HasDisplayTexture stay (3+ callers each).

== core/gpu_hw_opengl ==

  std::tuple<int32_t, int32_t>
    GPU_HW_OpenGL::ConvertToFramebufferCoordinates(int32_t x, int32_t y)
    Decl + 4-line impl: returns std::make_tuple(x, VRAM_HEIGHT - y).
    Zero callers. A leftover Y-flip helper from an earlier rendering
    path. The current GL pipeline does its Y-flip in shaders or
    when computing rectangle bounds for blits, not via this helper.

== core/bios ==

  ALWAYS_INLINE bool BIOS::Hash::operator!=(const Hash& bh) const
    Decl-only inline. Zero callers - the only Hash comparison site
    is bios.cpp:112 ("if (ii.hash == hash)" inside
    GetImageInfoForHash) using operator==. The != overload was
    speculative API; nothing exercised it.

  operator== stays.

== core/texture_replacements ==

Four pieces of zero-caller surface in this subsystem:

  bool TextureReplacementHash::operator!=(const TextureReplacementHash& rhs) const
    Decl-only inline. Zero callers - the unordered_map keying uses
    operator==, std::map uses operator<. Both survive.

  struct TextureReplacements::ReplacementHashMapHash {
    size_t operator()(const TextureReplacementHash& hash);
  }
    Private nested struct with one operator() method, declared but
    never defined and never used. The unordered_map declaration
    references std::hash<TextureReplacementHash> (the namespace-std
    specialization at the top of the header), not this nested
    struct. Vestige of an earlier hash-functor design.

  const std::string TextureReplacements::GetGameID() const
    Decl-only inline. Zero callers. The game ID flows in via
    SetGameID and is consumed internally; nothing reads it back
    from outside.

  void TextureReplacements::DumpVRAMWrite(uint32_t, uint32_t, const void*)
    Decl only, no impl. Zero callers. Was apparently going to dump
    VRAM-write replacements to disk for debugging, but the impl
    never landed and the call site that would have driven it never
    appeared.

  std::string TextureReplacements::GetVRAMWriteDumpFilename(...) const
    Decl + 23-line impl that builds a dump-output path from the
    cache folder and game id, with mkdir, path validation, and
    string concatenation. Was the helper that DumpVRAMWrite would
    have used; with DumpVRAMWrite gone (and never having existed
    in implementation form), this is unreachable.

  TextureReplacementHash::operator==, operator<, ToString, ParseString
  stay; SetGameID, Reload, GetVRAMWriteReplacement, Shutdown stay;
  GetVRAMWriteHash stays.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7927960 -> 7922816 bytes (-5144).
retro_* exports: 25 (unchanged).

12 files changed, 112 deletions(-).
2026-05-14 21:01:03 +02:00
LibretroAdmin
291765a987 common, core: dead-code sweep, round 3
Six independent audits collapsed into one omnibus commit, the same
shape as round 2. Build clean on Makefile.libretro platform=unix
at each intermediate step.

swanstation_libretro.so size: 7932552 -> 7927960 bytes (-4592).
Most of the codegen reduction comes from the bus.cpp SearchMemory
cluster (4 helpers, a static range table, and the helper they
delegate to); the inline accessor drops in common/state_wrapper,
core/cpu_core, core/interrupt_controller, core/pad and core/settings
yield zero codegen change since none of the dropped methods were
ever instantiated. 25 retro_* exports preserved.

== core/bus: SearchMemory cluster ==

Bus::SearchMemory(start, pattern, mask, len) and everything it
transitively depends on, all zero-caller:

  std::optional<PhysicalMemoryAddress>
    SearchMemory(PhysicalMemoryAddress start_address,
                 const uint8_t* pattern,
                 const uint8_t* mask,
                 uint32_t pattern_length)
    Decl + def, zero callers. Scans physical memory regions for
    a masked byte-pattern match. Almost certainly inherited from
    DuckStation's debugger UI which has no swanstation equivalent.

With SearchMemory gone, these become unreferenced and go with it:

  static MaskedMemoryCompare(pattern, mask, len, mem)
    Static helper, only fed by SearchMemory. Memcmp-with-mask
    bytewise compare.

  std::optional<MemoryRegion>
    GetMemoryRegionForAddress(PhysicalMemoryAddress address)
  PhysicalMemoryAddress GetMemoryRegionStart(MemoryRegion region)
  PhysicalMemoryAddress GetMemoryRegionEnd(MemoryRegion region)
  uint8_t* GetMemoryRegionPointer(MemoryRegion region)
    The four region-introspection helpers. Each had zero callers
    outside SearchMemory, which has now been removed.

  static constexpr std::array<std::pair<PhysicalMemoryAddress,
                                        PhysicalMemoryAddress>,
                              static_cast<uint32_t>(MemoryRegion::Count)>
    s_code_region_ranges
    Static range table feeding GetMemoryRegionStart / End.

  enum class MemoryRegion { RAM, RAMMirror1..3, EXP1, Scratchpad,
                            BIOS, Count }
    The enum used by all of the above. No external uses anywhere
    after the helpers go.

bus.h: drop the enum + 5 decls (19 lines).
bus.cpp: drop the 6 function bodies + the static array (125 lines).

== core/gpu: dead UnpackColorRGB24 ==

  static constexpr std::tuple<uint8_t, uint8_t, uint8_t>
    GPU::UnpackColorRGB24(uint32_t rgb24)

Inline static helper on GPU base class. Zero callers - the only
extant caller (gpu_sw_backend.cpp:224) resolves to the LOCAL
GPU_SW_Backend::UnpackColorRGB24 at gpu_sw_backend.h:82, not the
GPU:: one (GPU_SW_Backend does not inherit from GPU, it's a
sibling renderer). GPU::UnpackTexcoord which has the same shape
stays alive because GPU_HW : public GPU does inherit it and
calls it bare from gpu_hw.cpp.

== core/cpu_core: dead InKernelMode ==

  ALWAYS_INLINE bool CPU::InKernelMode()

Decl-only inline (returns !KUc, complement of InUserMode which
has 2 callers). Zero callers. Decision points in the codebase
that care about CPU mode all phrase the check as InUserMode().

== core/interrupt_controller: dead GetIRQLineState ==

  ALWAYS_INLINE bool InterruptController::GetIRQLineState() const

Decl-only inline. Zero callers. The IRQ-line state propagates
to the CPU via InterruptRequest()->UpdateCPUInterruptRequest()
which sets/clears CAUSE.IP directly; nothing else queries the
aggregate line state from outside the class.

== core/pad: dead RemoveMemoryCard ==

  std::unique_ptr<MemoryCard> Pad::RemoveMemoryCard(uint32_t slot)

Decl + 5-line impl. Zero callers. Memory cards are managed via
SetMemoryCard() which takes a unique_ptr and replaces the slot;
the previous occupant is destroyed by the unique_ptr move
assignment without any caller needing to recover the old
instance. The Reset() call inside RemoveMemoryCard would be
moot anyway since the returned card is about to be destroyed
or repurposed by whatever called the (nonexistent) caller.

== common/state_wrapper: dead GetMode ==

  Mode StateWrapper::GetMode() const

Decl-only inline. Zero callers. The reading/writing distinction
is queried via IsReading() / IsWriting() (both 1+ callers); the
explicit GetMode() was a third way to ask the same question
that nobody used.

== core/settings: dead PGXP and runahead accessors ==

  ALWAYS_INLINE bool Settings::IsRunaheadEnabled() const
    Returns (runahead_frames > 0). Zero callers anywhere -
    runahead control flows through runahead_frames directly,
    not through this predicate.

  ALWAYS_INLINE PGXPMode Settings::GetPGXPMode()
    Returns PGXPMode::CPU | Memory | Disabled depending on
    gpu_pgxp_enable + gpu_pgxp_cpu. Zero callers - the PGXPMode
    enum is consumed elsewhere as a template parameter
    (cpu_code_cache.h:143/146 templated on PGXPMode), with
    template-argument selection via runtime branching on
    g_settings.gpu_pgxp_enable / gpu_pgxp_cpu booleans
    directly. The mode-bundled return value was speculative.

  ALWAYS_INLINE float Settings::GetPGXPDepthClearThreshold() const
    Returns gpu_pgxp_depth_clear_threshold * 4096.0f. Zero
    callers - the threshold is consumed in *4096 form by GPU_HW
    code which does the multiplication at its own use site.
    SetPGXPDepthClearThreshold (the inverse setter) survives at
    1 caller (LoadSettings reads the config file).

  PGXPMode enum and SetPGXPDepthClearThreshold stay.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7932552 -> 7927960 bytes (-4592).
retro_* exports: 25 (unchanged).

9 files changed, 173 deletions(-).
2026-05-14 20:28:51 +02:00
LibretroAdmin
8d360296c9 core: drop dead SPU::GetRAM accessors and Controller vibration-motor surface
Two independent dead-code drops collected together since they're
all in core/ and were caught in the same audit pass.

== SPU::GetRAM (both overloads) ==

  const std::array<uint8_t, RAM_SIZE>& GetRAM() const
  std::array<uint8_t, RAM_SIZE>& GetRAM()

Two inline accessors returning &m_ram. Zero callers anywhere in
the tree. The SPU RAM is mutated internally via WriteRegister /
DMAWrite, queried internally via ReadRegister / DMARead /
GeneratePendingSamples; no external code reads or writes m_ram
directly. The const and non-const overloads were both audit-only
accessors that nothing ever needed.

== Controller vibration-motor counting surface ==

A coordinated drop across 9 files: the entire static aggregator +
its 7 per-class delegates + the virtual instance accessor + its
2 overrides all turned out to be zero-caller surface.

  static uint32_t Controller::GetVibrationMotorCount(ControllerType type)
    A switch over ControllerType that delegates to each
    subclass's static helper. Zero callers - nothing in the tree
    asks 'how many motors does a controller of this type have'.

  static uint32_t DigitalController::StaticGetVibrationMotorCount()
  static uint32_t AnalogController::StaticGetVibrationMotorCount()
  static uint32_t AnalogJoystick::StaticGetVibrationMotorCount()
  static uint32_t NamcoGunCon::StaticGetVibrationMotorCount()
  static uint32_t PlayStationMouse::StaticGetVibrationMotorCount()
  static uint32_t NeGcon::StaticGetVibrationMotorCount()
  static uint32_t NeGconRumble::StaticGetVibrationMotorCount()
    Each had exactly one caller - the dead aggregator above. With
    the aggregator gone, all 7 delegates become unreferenced. The
    bodies are all one-liners returning 0 or NUM_MOTORS (only
    AnalogController and NeGconRumble return non-zero); no logic
    is lost.

  virtual uint32_t Controller::GetVibrationMotorCount() const
  uint32_t AnalogController::GetVibrationMotorCount() const override
  uint32_t NeGconRumble::GetVibrationMotorCount() const override
    The instance-virtual mirror of the static surface, also zero
    callers. Draw and input paths never ask a controller instance
    for its motor count; the rumble path uses
    GetVibrationMotorStrength(uint32_t motor) directly with motor
    indices 0 / 1, hard-coded in input_driver.c / pad.cpp
    forwarders. The count never participates in routing.

GetVibrationMotorStrength itself stays - it's the live API on
both classes, with NUM_MOTORS internal to each subclass keeping
the motor-state array sizes consistent.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7937464 -> 7932552 bytes (-4912:
the static aggregator body, 7 per-class static helper bodies,
3 instance-virtual bodies, plus all 11 corresponding dynsym
entries).
retro_* exports: 25 (unchanged).

17 files changed, 97 deletions(-).
2026-05-14 20:11:34 +02:00
LibretroAdmin
a7ee3aefe7 common, core, libretro: dead-code sweep, round 2
Nine independent audits collapsed into one commit. All
mechanically distinct and individually verified at build
time; landing them together rather than as separate commits
since each cleanup is small and they touch independent files
or independent surfaces within the same file. Build clean at
every intermediate step on Makefile.libretro platform=unix.

swanstation_libretro.so cumulative size delta:
7949736 -> 7937464 bytes (-12272, ~0.15%). The reductions
come almost entirely from removed dynsym entries plus the
larger drops in common/gl/program (36 Uniform method
bodies) and common/byte_stream (5 SeekRelative overrides);
the template-method dead surface in heap_array / bitfield /
rectangle / types / page_fault_handler / iso_reader yielded
zero codegen change since the templates were never
instantiated. 25 retro_* exports preserved.

== common/gl/program: 36 dead Uniform overloads and BindDefaultAttributes ==

GL::Program declared 42 Uniform setter overloads - 21 by-index
and 21 by-name. Only three are called by gpu_hw_opengl.cpp:

  Uniform1i(int, int32_t)              4 callsites
  Uniform1i(const char*, int32_t)      7 callsites (samp0 binds)
  Uniform4f(int, float, float, float, float)
                                       2 callsites (cursor/display
                                       quad transforms at lines
                                       477 / 562)

The other 39 overloads are decl + def with zero call sites
anywhere. BindDefaultAttributes() (a three-line wrapper around
BindAttribute) likewise has zero callers - every gpu_hw_opengl
shader binds attributes by name directly.

program.h:   105 -> 64  lines
program.cpp: 600 -> 332 lines
.so: -6392 bytes

== common: dead CacheIndexKey::operator!= in all four shader_cache backends ==

All four ShaderCache implementations (GL, D3D11, D3D12, Vulkan)
declare both operator== and operator!= on their CacheIndexKey
structs. The keys are stored in std::unordered_map<CacheIndexKey,
CacheIndexData, CacheIndexEntryHasher> which uses operator== for
collision resolution and never operator!=. No caller in src/
compares two cache keys with != either. Drop the decl from each
header and the body from each cpp.

d3d11 and d3d12 only build on Windows under the Makefile.libretro
win32 guard, so the platform=unix build verifies GL and Vulkan
only. The d3d drops are mechanically symmetric with the verified
ones.

8 files, 32 deletions. .so: -4240 bytes.

== common: ByteStream::SeekRelative, FIFOQueue accessors, FileSystem::rferror ==

ByteStream::SeekRelative was a pure-virtual base method with
five concrete overrides (FileByteStream Windows + POSIX, plus
the three memory subclasses). Zero callers anywhere. Save/load
paths use SeekAbsolute exclusively, CD-image readers use their
own buffered position tracking, and cheat / texture-replacement
serializers rewind via SeekAbsolute(0). Drop the base virtual
and all five overrides.

FIFOQueue::GetDataPointer (both const and non-const overloads)
and GetCapacity() - three inline accessors with zero callers.
Real consumers go through Push / Pop / Peek / PushRange /
PopRange / GetReadPointer / GetWritePointer.

FileSystem::rferror - thin extern "C" wrapper around
filestream_error(). Decl + def with zero callers; nothing in
the libretro core has ever queried a file-stream error state
through this. The other r*-family wrappers stay.

.so: -296 bytes.

== common/heap_array: dead methods AND broken copy paths ==

Of the dozen methods on HeapArray<T, SIZE>, only data() (both
overloads), size(), operator[], and fill() have callers. The
rest are inline accessors with zero call sites: capacity, empty,
begin, end, cbegin, cend, front (both), back (both).

The copy ctor and operator=(const this_type&) were defined but
silently broken: both wrote through rhs.cbegin() (a
const_pointer destination), which would fail to compile if any
caller invoked them. The six relational operators expanded by
the RELATIONAL_OPERATOR macro all had a missing 'return true'
on the loop-success path - falling off a non-void function is
UB if invoked. All seven of these dead methods would have
crashed or miscompiled the first time anyone tried to use them;
the absence of any caller is the only reason this code survived.

Replace the copy ctor and copy operator= with '= delete' so any
future attempt to copy a HeapArray fails at compile time rather
than silently corrupts.

heap_array.h: 102 -> 60 lines.

== common/rectangle: dead relational and arithmetic operators ==

Common::Rectangle<T> had 6 relational operators (==, !=, <, <=,
>, >=) and 19 arithmetic operators (10 compound and 9
non-compound, generated by the ARITHMETIC_OPERATOR macro for
+, -, *, /, %, >>, <<, |, &, ^). Of all these, exactly one is
called: operator*(T amount), used by every gpu_hw_* backend
once per VRAM readback to scale m_vram_dirty_rect by
m_resolution_scale. The other 24 operators have zero callers.

Bonus: the compound 'operator op##=' bodies in the macro never
'return *this;' - same UB-if-invoked pattern as HeapArray.

Also dropped:
  Include(T x, T y)         the 2-arg point-include form; all
                            dirty-rect growth uses the 4-arg form
  Clamp(x1, y1, x2, y2)     in-place; callers use Clamped()
                            (returns-new) instead

Keep operator*(const T amount) as a standalone constexpr member
with a comment explaining why it survives.

rectangle.h: 155 -> 95 lines.

== common/bitfield: dead ++, --, *= and >>= operators ==

Walked all 319 BitField field declarations in src/core/*.h
through grep for each compound op. The full list of dead
operators on BitField<...>:

  operator++()           0 hits across all 319 fields
  operator++(int)        0 hits
  operator--()           0 hits
  operator--(int)        0 hits
  operator*=             0 hits
  operator>>=            0 hits

The other compound ops (+=, -=, /=, &=, |=, ^=, <<=) all have
real callers and stay.

bitfield.h: 143 -> 99 lines.

== common/types: dead operator^ and operator^= in enum bitwise macro ==

IMPLEMENT_ENUM_CLASS_BITWISE_OPERATORS is instantiated four
times (CDImage::OpenFlags, HostRegState, ValueFlags,
GPUTextureMode). Of the seven operators the macro generates,
six have real callers (&, |, ~, &=, |=) but operator^ and
operator^= have zero hits across all four enums. XOR is just
not part of the way these flag-style enums are used: callers
union with |, subtract with & ~, or test with single-bit &.

types.h: 125 -> 115 lines.

== common, libretro: small finds in four files ==

CDSubChannelReplacement::AddReplacementSubChannelQ
  Zero callers. The replacement map is populated by LoadSBI()
  reading the .sbi file directly into emplace().

CDSubChannelReplacement::GetReplacementSubChannelQ(uint8_t,
                                                   uint8_t,
                                                   uint8_t, ...)
  Zero external callers; only forwarded into by its sibling
  LBA-keyed overload. All ten cd_image_* backends call the
  LBA-keyed variant directly with start_lba_on_disc + lba_in_index.

PageFaultHandler::Handle  decl-only alias, never named.

ISOReader::GetImage()     one-line inline accessor, zero
                          callers. ISO consumers in system.cpp
                          use GetPVD() and Open() only.

LibretroSettingsInterface::GetStringList()
  Builds a one-element vector from a comma-less string variable.
  Zero callers - the settings load path uses GetBoolValue /
  GetIntValue / GetFloatValue / GetStringValue at libretro_host_
  interface.cpp:1017,1236. Dropped decl, impl, and the <vector>
  include in the header.

.so: -1056 bytes.

== common, core: CDImage::Seek(const Position&), RegisterCache helpers ==

CDImage::Seek(const Position& pos)
  Single-arg MSF-Seek overload. Decl + def only, zero callers.
  Anyone wanting MSF-keyed seek can write Seek(p.ToLBA()).

  Found-but-kept: the two-arg Seek(uint32_t track, const Position&)
  initially looked dead but the eight cd_image_* backends call it
  as bare Seek(1, Position{0,0,0}) from inside their own subclass
  Open() methods. Build flagged the mistake immediately.

RegisterCache::IsUsableHostReg(HostReg)         0 callers
RegisterCache::GetUsedHostRegisters()           0 callers
RegisterCache::GetFreeHostRegisters()           0 callers
  Stat-counting helpers. Codegen never asks for a count; it
  checks whether a specific register is in use
  (IsHostRegInUse) or whether the free pool is non-empty
  (HasFreeHostRegister).

  Found-but-kept: Value::FromScratch(...) initially looked
  dead, but build flagged three internal callers via bare
  FromScratch(...) member-context calls. Reverted that drop.

.so: -304 bytes.
2026-05-14 19:13:49 +02:00
LibretroAdmin
fe33746cc1 common, core: dead-code and access-tightening sweep
Eleven small audits collapsed into one commit. All independent;
each fixes a different file or concern. Build clean at every
intermediate step. swanstation_libretro.so cumulative size
delta: 7965960 -> 7949736 bytes (-16224, ~0.2%). 25 retro_*
exports preserved.

== Dead struct / method removal ==

core/settings: drop dead SettingInfo struct
  Entire SettingInfo struct (Type enum + 8 fields + 10 helper
  methods StringDefaultValue / BooleanDefaultValue / Integer
  {Default,Min,Max,Step}Value / Float{Default,Min,Max,Step}
  Value). Qt-frontend settings-page metadata plumbing - the
  libretro core advertises its options via retro_variable
  instead, no SettingInfo needed. Zero external references.
  settings.h: 290 -> 257 lines. settings.cpp: 652 -> 595 lines.

core/settings: drop 11 dead Parse/Get helpers and translation arrays
  Six Get*DisplayName methods (CPUExecutionMode, CPUFastmemMode,
  Renderer, TextureFilter, DownsampleMode, DisplayCropMode),
  the CPU-overclock-percent quartet (SetCPUOverclockPercent +
  GetCPUOverclockPercent + CPUOverclockFractionToPercent +
  the orphan GetDownsampleModeDisplayName declaration without
  an implementation), ParseDiscRegionName, ParseControllerType
  Name / GetControllerTypeName, plus five dead translation-
  string arrays. The retained Parse*Name / Get*Name pairs each
  have at least one caller in the settings Load path or in
  libretro_host_interface's option-setup path.

common/byte_stream: drop dead BYTESTREAM_OPEN_* flags and branches
  Three constants set by nobody: BYTESTREAM_OPEN_APPEND (= 4),
  BYTESTREAM_OPEN_CREATE_PATH (= 32), BYTESTREAM_OPEN_SEEKABLE
  (= 128). The cpp had ~100 lines of mkdir-p logic gated on
  CREATE_PATH (two blocks - Windows fopen path and POSIX fopen
  path) and a small SEEKABLE branch appending 'R' to fopen
  modes; all unreachable. Drive-by: stale 'open stream for
  writing' per-line comments on the remaining flags also dropped.
  byte_stream.cpp: 1069 -> 963 lines. byte_stream.h: 175 -> 167.

core/system: drop dead GetMediaSubImageIndexForTitle
  Title-based playlist search. Libretro disc-switching navigates
  by index, never by title - the function was leftover Qt
  scaffolding. Zero callers anywhere. -19 lines, .so -4208 bytes
  (the GetSubImageMetadata virtual dispatch and the std::string_
  view interop the call site was pulling in falling out, even
  though GetSubImageMetadata itself stays - other system.cpp
  callers still use it).

common: drop dead inline accessors in cue_parser and iso_reader
  CueParser::Track::RemoveFlag (inverse of SetFlag - cue-sheet
  parser only ever sets flags, never clears them). ISOReader::
  GetTrackNumber (the m_track_number field is kept - read
  internally by the iso_reader.cpp Seek calls).

common/string: drop dead overloads on String and StackString
  Compare(const String&), StartsWith(char*+bool) and
  StartsWith(String&+bool), EndsWith(char*+bool) and
  EndsWith(String&+bool), AppendString(std::string&) and
  AppendString(std::string_view&), Assign(std::string&) and
  Assign(std::string_view&). The four operator= overloads
  on String and StackString that forwarded to the dead Assigns
  cascaded - the inline bodies refused to compile after the
  Assigns were dropped, so dropped together.

common: drop dead Image methods and prune string.h's <string>
  Common::Image::SetPixel, GetPixel, Invalidate (zero callers).
  After the previous string overload sweep the only std::string-
  named reference in string.h was the include itself; drop it.
  <string_view> stays.

common/error: drop dead Type enum, m_error union, copy ctor and operators
  The typed-error scaffolding on Common::Error - Type::None /
  Type::User enum, paired m_error int union, Type m_type field,
  copy ctor, operator=, operator== / operator!= - all unused
  externally. Every caller of Error uses it the same way:
  default-construct, SetMessage / SetFormattedMessage from an
  &error out param, read back via GetCodeAndMessage. After the
  cut Error is just a (code_string, message) pair with
  formatting helpers. error.h: 45 -> 27 lines, error.cpp:
  102 -> 46 lines.

== Access-level tightening ==

core/host_interface: move internal-only methods to private
  FindBIOSImageInDirectory (only called from GetBIOSImage at
  two BIOS-directory probes), RecreateSystem (only from
  CheckForSettingsChanges when a renderer change requires
  recreation), UpdateSoftwareCursor (5 internal callers in
  the controller-change / OSD / settings paths). Zero
  subclasses of HostInterface exist - safe to private.

core/system: file-localize four internal-only helpers
  GetExecutableNameForImage(CDImage*), ReadExecutableFromImage
  (CDImage*), GetGameHashCodeForImage, UpdatePerGameMemoryCards
  all moved from external linkage to static. Forward
  declarations added to the existing static-decl block at the
  top of the System namespace. .so -312 bytes (dynsym entries
  + a few exposed-call indirections collapsing into direct
  calls now that the linker sees all callers).

core/cdrom: move IsMediaPS1Disc and DoesMediaRegionMatchConsole to private
  Both predicates exposed in the public section but called only
  inside cdrom.cpp (three sites each - the ReadSector CD-DA
  branch and the two disc-spinup completion branches). Moved
  to the existing private: block.
2026-05-14 17:30:11 +02:00
LibretroAdmin
3dc3f3d3c0 core/mdec: preserve the bit-15 mask flag in Old 15bpp output packing
The 15bpp Old packing branch in CopyOutBlock applied an extra '<< 15'
to 'a' on the way into color15a/color15b. Since 'a' was already
pre-shifted to bit 15 of a uint16_t (i.e. either 0x0000 or 0x8000),
the second shift moves the mask bit out of the type's representable
range and the narrowing back to uint16_t silently drops it. Every
15bpp MDEC pixel emitted through the Old path therefore had its
data_output_bit15 mask cleared, regardless of what the game told
the MDEC command to set it to.

In games that only use MDEC for full-screen FMV (most PS1 titles)
the lost mask bit is invisible: the FMV is presented straight to
the framebuffer with nothing composited on top. Oddworld: Abe's
Oddysee and Abe's Exoddus, however, decode their gameplay
backgrounds through MDEC into VRAM with bit 15 set, then draw
character sprites and UI on top using the PS1 GPU's per-pixel
draw-mask / semi-transparency rules. With the mask bit cleared on
every background pixel, those subsequent draws blend against the
wrong source flag and produce the high-contrast noise around the
title-screen dial and the cyan/mis-tinted character sprite in
gameplay reported in issue #127.

Drop the spurious '<< 15' and OR 'a' in directly, matching what the
New path's analogous line already does. Verified via the
SS_MDEC_VERIFY shadow-pack comparator: with the fix, the Old and
New 15bpp packing branches produce bit-identical output on every
captured macroblock of an Abe frame.

Fixes libretro/swanstation#127.
2026-05-14 17:28:36 +02:00
LibretroAdmin
24a822f036 core/gpu: drop dead IsHardwareRenderer and ComputeHorizontalFrequency
Two members declared in gpu.h with definitions in gpu.cpp and
zero callers anywhere in src/.

  bool IsHardwareRenderer()
    - returned (GetRendererType() != GPURenderer::Software).
      Every caller that wants this check does it directly
      against the renderer setting in g_settings rather than
      going through GPU itself, so the method was never wired up.

  float ComputeHorizontalFrequency() const
    - peer to ComputeVerticalFrequency. The vertical variant is
      used at gpu.cpp:579 to feed System::SetThrottleFrequency.
      The horizontal one has no caller; nothing in the
      libretro path consumes hsync frequency.

Drop the declarations from gpu.h and the bodies from gpu.cpp.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965760 -> 7957448 bytes
(-8312). Larger than the function bodies themselves; the diff
is the SystemTicksToCRTCTicks helper and its callees getting
re-inlined / collapsed once one of the two call sites is gone.
retro_* exports: 25 (unchanged).
2026-05-14 16:27:35 +02:00
LibretroAdmin
94b1e372d6 common/cd_image: drop dead accessors and the m_position_in_track field
Six accessors had no callers anywhere in src/:

  GetMSFPositionOnDisc      Position::FromLBA(m_position_on_disc)
  GetPositionInTrack        m_position_in_track
  GetMSFPositionInTrack     Position::FromLBA(m_position_in_track)
  GetIndexNumber            m_current_index->index_number
  GetTrackIndexPosition     linear scan over m_indices
  GetTrackIndexLength       linear scan over m_indices

The two GetTrackIndex* ones were not inline; their bodies in
cd_image.cpp go too.

With GetPositionInTrack and GetMSFPositionInTrack gone, the
m_position_in_track member also has no remaining readers - it
was being written by Seek (line 122), incremented by ReadRawSector
(line 233), and zeroed by ClearTOC/CopyTOC (lines 292, 303),
but the value was never consumed by anything inside or outside
the class. Drop the field and the four bookkeeping sites that
maintained it.

m_position_in_index (next to it in the header) stays - it has
real readers in CDImage::Read and ReadRawSector at lines 191,
202, and 224, where it indexes the current sector being read
from within the active index.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965888 -> 7965760 bytes (-128,
the two GetTrackIndex* method bodies plus the four
m_position_in_track bookkeeping ops collapsing into nothing
under -O3).
retro_* exports: 25 (unchanged).
2026-05-14 16:27:30 +02:00
LibretroAdmin
7f38dc457e core/memory_card_image: drop dead UI scaffolding
The header was carrying scaffolding for a save-file browser UI
that does not exist in the libretro build, plus a handful of
constants that nothing actually consumed.

Removed from memory_card_image.h:

  struct IconFrame { uint32_t pixels[ICON_WIDTH * ICON_HEIGHT]; }
    - zero references anywhere
  struct FileInfo { filename, title, size, first_block,
                    num_blocks, deleted, icon_frames }
    - zero references anywhere; the save-state file browser
      would have used this
  bool IsValid(const DataArray&)
    - zero references anywhere; no caller checks save-card
      validity through this API (the 'MC' magic check is only
      relevant when listing files in a UI we do not have)
  Constants: NUM_FRAMES, FRAMES_PER_BLOCK, NUM_BLOCKS,
             ICON_WIDTH, ICON_HEIGHT
    - all zero references in src/ outside this header

Kept: DATA_SIZE, BLOCK_SIZE, FRAME_SIZE (used by the actual
emulation - DATA_SIZE in DataArray's std::array size,
FRAME_SIZE in memory_card.cpp's per-frame offset arithmetic,
BLOCK_SIZE in this TU's free-block scan).

Five includes drop with the dead surface:

  common/bitfield.h   never used a BitField in this header
  controller.h        Controller was never referenced
  <memory>            no unique_ptr / shared_ptr in this header
  <string>            only used inside the dead FileInfo struct
  <string_view>       not used at all
  <vector>            only used inside the dead FileInfo struct

The IsValid implementation goes with its declaration; nothing
else in memory_card_image.cpp called it either. The internal
file-static helpers GetFramePtr and GetChecksum stay -
GetFramePtr is used by Format, GetChecksum is used by Format.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965960 -> 7965888 bytes (-72,
the IsValid body and a couple of dynsym entries falling out).
retro_* exports: 25 (unchanged).

src/core/memory_card_image.h: 41 -> 17 lines (-58%)
2026-05-14 16:27:26 +02:00
LibretroAdmin
80202aa5d2 core/controller: drop dead AxisType enum and ButtonList/AxisList/SettingList aliases
These four declarations exist for a controller-binding UI that
the libretro frontend doesn't have, and nothing in the tree
consumes them.

Removed from controller.h:

  enum class AxisType { Full, Half }
    - zero references anywhere in src/
  using ButtonList = std::vector<std::pair<std::string, int32_t>>
  using AxisList   = std::vector<std::tuple<std::string, int32_t, AxisType>>
  using SettingList = std::vector<SettingInfo>
    - the three list aliases that the controller manager UI in
      the Qt frontend (which we don't build) populates. Subclasses
      in src/core/{analog_controller,digital_controller,...}
      never override or return these types - input is mapped
      directly via SetButtonState / SetAxisState which take
      bare int32_t codes.

Three includes drop with them:

  <string>      only used by std::string inside the aliases
  <string_view> not used at all (likely a header copy-paste)
  <vector>      only used by std::vector inside the aliases
  <tuple> is not removed because it was never included to
  begin with - std::tuple was reaching the header transitively
  through one of the other includes, and dropping the only
  consumer takes the requirement with it.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965960 bytes (unchanged).
2026-05-14 16:27:22 +02:00
LibretroAdmin
30fc39e705 core/gpu_backend: tighten access on internals nothing outside touches
Six members were exposed wider than they needed to be:

  RunGPULoop          public,    used only by m_gpu_thread (via std::thread ctor)
  AllocateCommand     protected, used only by the New*Command helpers
  GetPendingCommandSize protected, used only by PushCommand
  WakeGPUThread       protected, used only by PushCommand and Sync
  StartGPUThread      protected, used only by Initialize / UpdateSettings
  StopGPUThread       protected, used only by Shutdown / UpdateSettings / dtor

Verified via grep across src/ that no caller outside
gpu_backend.cpp references any of these. There are also no
subclasses of GPUBackend that touch them - GPU_SW_Backend and
GPU_HW_Backend only override the pure-virtual draw / fill /
copy hooks, none of these worker-thread helpers.

Move them all to private. The protected: block now contains
just the draw/fill/copy pure virtuals, HandleCommand (which
subclasses do override), and the shared member data the
subclasses actually read - the m_drawing_area /
m_command_fifo_data / m_vram_ptr storage that
HandleCommand and the draw hooks operate on.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965960 bytes (unchanged).
retro_* exports: 25 (unchanged).
2026-05-14 16:27:18 +02:00
LibretroAdmin
f576e9b025 common/string_util: drop dead StartsWith helper and prune unused includes
Three small things, none of them functional.

1. StringUtil::StartsWith is dead - it has no callers anywhere
   in src/. EndsWith next to it has one caller (file_system
   pattern matching) and stays. The two helpers were added as
   pre-C++20 polyfills for std::string_view::starts_with /
   ends_with, but the prefix variant never got picked up by
   any caller. Drop the body.

2. The <vector> include in string_util.h is unused - no
   std::vector appears anywhere in the header or its callers'
   needs.

3. The conditional <sstream> block in string_util.h is
   pointless. The header already #include <sstream>
   unconditionally a few lines up, and then re-includes it
   under '#if __has_include(<charconv>)' / '#ifndef _WIN32'
   nests below. Collapse to a single unconditional <sstream>
   plus a clean '#if __has_include(<charconv>)' guard for
   the <charconv> include alone.

4. string_util.cpp included <codecvt> (deprecated since C++17,
   removed in C++26 drafts) and <sstream>, neither of which
   the .cpp body uses. The functions there are
   StdStringFromFormat / StdStringFromFormatV (vsnprintf
   based, uses <cstdio> + <cstdarg> from the header) and
   WildcardMatch (plain const char* iteration with
   std::tolower from <cctype>). Drop both unused includes.

Found while reviewing string_util.cpp: WildcardMatch has its
case_sensitive=true / case_sensitive=false branches swapped -
the 'case_sensitive=true' path uses std::tolower for case-
insensitive comparison and the 'case_sensitive=false' path
uses plain ==. Both callers in file_system.cpp pass the
default true, so file-pattern matching has been silently
case-insensitive everywhere. Out of scope for this hygiene
commit; mentioning it here so it does not get lost.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965960 bytes (unchanged).
2026-05-14 16:27:15 +02:00
LibretroAdmin
355d5a768a core/gpu_sw_backend: fix include set in the header
The header included <memory> and <vector> but uses neither
(no unique_ptr / shared_ptr / make_unique, no std::vector
anywhere - the m_vram field is a std::array, not a vector).

It uses std::min and std::clamp in the Color::Set saturation
helper at lines 43 / 61-63, which need <algorithm>, and
std::tuple / std::make_tuple in UnpackTexcoord and
UnpackColorRGB24 at lines 77-85, which need <tuple>. Both
were reaching the TU only because gpu_backend.h's include
chain happened to drag them in transitively. Add <algorithm>
and <tuple> directly so the header is self-contained for the
names it actually uses, and drop the two unused includes.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965960 bytes (unchanged).
2026-05-14 16:27:11 +02:00
LibretroAdmin
8220b3c2a8 common/fifo_queue: include <cstdlib> and <utility> directly
Two latent IWYU issues, both papered over by transitive
inclusions on libstdc++ + glibc but fragile elsewhere.

1. std::move is used in the Pop / Pop(out_data) paths (line
   115 / 127 / 140) but <utility> was never included. <algorithm>
   pulls <utility> in for std::swap on libstdc++, which masked
   the issue, but that is not a guaranteed standard relationship.

2. The HeapFIFOQueue::Reset path uses std::malloc for the
   ALIGNMENT == 0 branch (line 194). The header used to include
   <malloc.h> for _aligned_malloc on Windows and <stdlib.h> for
   posix_memalign on POSIX. Neither header is guaranteed to
   provide the std::malloc qualified name - on Windows in
   particular, <malloc.h> only exposes the global ::malloc.

   Replace the POSIX-specific <stdlib.h> guard with an
   unconditional <cstdlib>, which provides std::malloc,
   std::free, and posix_memalign through the C++ standard
   library wrapper. <malloc.h> is still needed on Windows for
   the _aligned_malloc intrinsic.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 7965960 bytes (unchanged).
retro_* exports: 25 (unchanged).
2026-05-14 16:27:07 +02:00
LibretroAdmin
6acddfd1d8 core/cheats: remove dead code unreachable from the libretro frontend
This file was forked from Duckstation, which has a full Qt+ImGui
cheat-manager UI (file-format loaders, a memory scanner, a
watch list, type/activation name tables, code groups, master
enable, etc.). swanstation only exposes cheats through the
libretro retro_cheat_set / retro_cheat_reset entry points, and
that flow needs a much smaller surface area than the
Qt-targeted API supplies. The unused code never reaches a
caller in this tree.

Audited the entire src/ directory; the libretro-reachable cheat
API is exactly:

  CheatList()                              ctor   from libretro_host_interface
  ~CheatList()                             dtor   from libretro_host_interface
  CheatList::SetCode(uint32_t, CheatCode)         from libretro_host_interface:981
  CheatList::Apply()                              from system.cpp:1188
  CheatList::ParseLibretroCheat(...)       static from libretro_host_interface:978
  CheatList::ResetSharedScratchRegisters() static from system.cpp
  CheatCode::Apply()                              from CheatList::Apply (internal)
  CheatCode::GetNextNonConditionalInstruction()   from CheatCode::Apply (internal)
  CheatCode::Valid()                              kept (cheap, plausible future use)

Removed from cheats.h:

  CheatCode::Type enum + value Gameshark
  CheatCode::Activation enum + values Manual/EndFrame
  CheatCode fields:  group, comments, type, activation
  CheatCode methods: IsManuallyActivated,
                     GetInstructionsAsString,
                     SetInstructionsFromString,
                     ApplyOnDisable,
                     GetTypeName/GetTypeDisplayName/ParseTypeName,
                     GetActivationName/GetActivationDisplayName/ParseActivationName
  CheatList::Format enum + values Autodetect/PCSXR/Libretro/EPSXe/Count
  CheatList methods: GetCode (both overloads),
                     GetCodeCount, IsCodeEnabled,
                     GetMasterEnable, SetMasterEnable,
                     FindCode (both overloads),
                     AddCode, RemoveCode,
                     GetEnabledCodeCount, GetCodeGroups,
                     EnableCode, DisableCode, SetCodeEnabled,
                     LoadFromPCSXRString,
                     LoadFromLibretroString,
                     LoadFromEPSXeString,
                     ApplyCode,
                     MergeList
  CheatList field:   m_master_enable
  Classes:           MemoryScan (entire class, including
                     Operator enum, Result struct, ResultVector
                     alias, accessors and search/update methods)
                     MemoryWatchList (entire class, including
                     Entry struct, EntryVector alias, accessors,
                     entry mutation, and freeze handling)
  Include:           <optional> (was only needed for
                     ParseTypeName / ParseActivationName
                     return types)

Removed from cheats.cpp:

  static helpers:    IsHexCharacter, SignedCharToInt, FindKey,
                     KeyValuePairVector alias - all three were
                     only used by the format-loader methods above
  CheatList method bodies for everything dropped from cheats.h
  CheatCode method bodies for everything dropped from cheats.h
  m_master_enable check inside Apply() (the field had no
  setter outside the now-dead SetMasterEnable accessor, so
  default-true was the only value it ever held and the
  'if (!m_master_enable) return;' guard was a constant-false
  branch)
  Static arrays:     s_cheat_code_type_names,
                     s_cheat_code_type_display_names,
                     s_cheat_code_activation_names,
                     s_cheat_code_activation_display_names
                     and their TRANSLATABLE wrappers - all four
                     only fed the Get*Name methods that are gone
  MemoryScan and MemoryScan::Result method bodies
  MemoryWatchList method bodies
  Unused includes:   common/byte_stream.h
                     common/string.h
                     common/string_util.h
                     core/host_interface.h
                     <cctype>
                     <iomanip>
                     <sstream>

Behaviour preserved:
  - retro_cheat_set / retro_cheat_reset paths unchanged.
  - System::Shutdown still calls CheatList::ResetSharedScratchRegisters
    via the unique_ptr<CheatList> path; the static cht_register
    array and its fill(0) are unchanged.
  - CheatCode::Apply and GetNextNonConditionalInstruction (the
    GameShark interpreter, ~1200 lines including the giant
    instruction switch) are completely untouched.

Diff:
  src/core/cheats.h:   315 -> 127 lines (-188, -60%)
  src/core/cheats.cpp: 3011 -> 1942 lines (-1069, -35%)
  Total:              -1257 lines

Build: Makefile.libretro platform=unix - clean, no warnings.
swanstation_libretro.so size: 8020336 -> 7965960 bytes
(-54376, roughly the eight removed static name/display-name
tables, the MemoryScan / MemoryWatchList method bodies, the
file-format loaders and their stringstream machinery, and the
inlined dead branches that survive in -O3 builds).
retro_* exports: 25 (unchanged).
2026-05-14 15:42:17 +02:00
LibretroAdmin
8b8d2cca15 common/state_wrapper: include <array> directly
state_wrapper.h uses std::array (in Do(std::array<T, N>* data)
template overload around line 80) but did not include <array>
itself. It compiled because <array> was reaching the TU
transitively through one of the other headers (likely <deque>
on libstdc++, which pulls <array> in for std::array deduction
helpers in some configurations - a fragile dependency to rely
on).

Add the include directly. No behaviour change, but the header
is now IWYU-clean for std::array.

Build: Makefile.libretro platform=unix - clean. .so size and
exports unchanged from prior commit.
2026-05-14 15:42:13 +02:00
LibretroAdmin
a96e66a86e common/file_system: make GetFileNameFromPath file-local
GetFileNameFromPath has only two callers and both are inside
file_system.cpp itself (GetDisplayNameFromPath at line 218 and
GetFileTitleFromPath at line 232). No code outside the TU
references it. Mark it static and drop the header declaration -
the rest of the tree never needed to see this symbol.

GetLastSeperatorPosition next to it (line 196) is already a
file-local static for exactly the same reason, so this matches
the surrounding style.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 8020440 -> 8020336 bytes (-104,
one fewer entry in dynsym).
retro_* exports: 25 (unchanged).
2026-05-14 15:42:10 +02:00
LibretroAdmin
46f4d9228d common/types: drop UNREFERENCED_VARIABLE macro, inline its two callers
The header defined a UNREFERENCED_VARIABLE macro that expands to
'(void)(P)' on GCC/Clang and '(P)' on MSVC (which is the same
thing in practice - both suppress -Wunused-{variable,parameter}).
Only two TUs in the tree used it:

  src/core/gpu_backend.cpp: a deliberately-unused
    'const uint32_t new_write_ptr = m_command_fifo_write_ptr.fetch_add(...) + ...;'
    that's only there for the side effect of the atomic increment.

  src/core/cdrom.cpp: a 'right' channel sample variable that's
    only read inside 'if constexpr (STEREO)' branches; the
    'if constexpr (!STEREO)' branch marks it unused.

Plain '(void)x;' does the same job in one fewer token and one
less layer of indirection, and is the idiom every other piece
of C++ I work with already uses. Convert both sites and drop
the macro from types.h.

Build: Makefile.libretro platform=unix - clean.
swanstation_libretro.so size: 8020440 bytes (unchanged).
retro_* exports: 25 (unchanged).
3 files, -11 lines.
2026-05-14 15:13:26 +02:00