From 960e0761c50cea58618f55a424f2d0a46dd5ea38 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 24 Sep 2023 19:28:35 +0200 Subject: [PATCH] Improve trimming in D2D1PixelShader.LoadBytecode() --- .../Shaders/Interop/D2D1PixelShader.cs | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs index ae24b737..473af757 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs @@ -29,7 +29,18 @@ public static class D2D1PixelShader public static ReadOnlyMemory LoadBytecode() where T : unmanaged, ID2D1PixelShader { - return LoadOrCompileBytecode(null, null, out _, out _); + Unsafe.SkipInit(out T shader); + + // This method is the one used by the built-in ID2D1Effect, so it has special optimization + // to help both performance and especially trimming. That is, we first check whether the + // HLSL code is already available, which should get completely inlined when using the + // generated code. This allows the entire fallback path below to be trimmed out. + if (shader.HlslBytecode is ReadOnlyMemory { Length: > 0 } hlslBytecode) + { + return hlslBytecode; + } + + return CompileBytecode(null, null, out _, out _); } /// @@ -234,7 +245,6 @@ public static class D2D1PixelShader /// The effective shader profile that was used to get the shader bytecode. /// The effective compile options that were used to get the shader bytecode. /// A instance with the resulting shader bytecode. - /// Thrown if the input shader has not been precompiled. private static unsafe ReadOnlyMemory LoadOrCompileBytecode( D2D1ShaderProfile? requestedShaderProfile, D2D1CompileOptions? requestedCompileOptions, @@ -255,19 +265,8 @@ public static class D2D1PixelShader return hlslBytecode; } - string hlslSource = shader.HlslSource; - - // Set the effective profile and option to the requested ones or the default values - effectiveShaderProfile = requestedShaderProfile ?? shader.ShaderProfile; - effectiveCompileOptions = requestedCompileOptions ?? shader.CompileOptions; - - // Compile the shader with the current settings - using ComPtr dynamicBytecode = D3DCompiler.Compile(hlslSource.AsSpan(), effectiveShaderProfile, effectiveCompileOptions); - - byte* bytecodePtr = (byte*)dynamicBytecode.Get()->GetBufferPointer(); - int bytecodeSize = (int)dynamicBytecode.Get()->GetBufferSize(); - - return new ReadOnlySpan(bytecodePtr, bytecodeSize).ToArray(); + // Fallback path just compiling the HLSL code on the fly + return CompileBytecode(requestedShaderProfile, requestedCompileOptions, out effectiveShaderProfile, out effectiveCompileOptions); } ///