From c1e795129ecf2d18ec5ebc05cfd1e93eabd7cfae Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Apr 2022 16:33:26 +0200 Subject: [PATCH] Implement dynamic D2D1 compilation generation --- ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 135 +++++++++--------- .../__Internals/ID2D1BytecodeLoader.cs | 4 +- .../__Internals/ID2D1DispatchDataLoader.cs | 2 +- .../Interfaces/__Internals/ID2D1Shader.cs | 1 - .../D2D1ByteArrayDispatchDataLoader.cs | 2 +- .../D2D1DrawInfoDispatchDataLoader.cs | 2 +- .../Dispatching/D2D1ShaderBytecodeLoader.cs | 4 +- .../Shaders/Interop/D2D1InteropServices.cs | 11 +- .../Shaders/Interop/D2D1ReflectionServices.cs | 6 +- .../__Internals/D2D1ShaderCompiler.cs | 38 +++++ ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 4 +- 11 files changed, 126 insertions(+), 83 deletions(-) create mode 100644 src/ComputeSharp.D2D1Interop/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs diff --git a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 767c3cae..77f5e977 100644 --- a/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1Interop.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -39,7 +39,7 @@ partial class ID2D1ShaderGenerator // This code produces a method declaration as follows: // - // readonly void global::ComputeSharp.D2D1Interop.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, global::ComputeSharp.D2D1Interop.D2D1ShaderProfile? shaderProfile, out string hlslSource) + // readonly void global::ComputeSharp.D2D1Interop.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, global::ComputeSharp.D2D1Interop.D2D1ShaderProfile? shaderProfile) // { // // } @@ -52,8 +52,7 @@ partial class ID2D1ShaderGenerator .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) .AddParameterListParameters( Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")), - Parameter(Identifier("shaderProfile")).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1Interop.D2D1ShaderProfile"))), - Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword)))) + Parameter(Identifier("shaderProfile")).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1Interop.D2D1ShaderProfile")))) .WithBody(block); } @@ -65,79 +64,83 @@ partial class ID2D1ShaderGenerator /// The instance trying to retrieve the precompiled shader. private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) { - ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); - - // This code produces a branch as follows: + // This code produces a method declaration as follows: // - // hlslSource = ; - statements.Add( + // ComputeSharp.D2D1Interop.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, in this, shaderProfile, ); + ExpressionStatementSyntax dynamicLoadingStatement = ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("hlslSource"), - LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal(bytecodeInfo.HlslSource))))); + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("ComputeSharp.D2D1Interop.__Internals.D2D1ShaderCompiler"), + IdentifierName("LoadDynamicBytecode"))) + .AddArgumentListArguments( + Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), + Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)), + Argument(IdentifierName("shaderProfile")), + Argument(LiteralExpression(SyntaxKind.TrueLiteralExpression)))); - // Load the bytecode literals, if available, otherwise emit the dynamic loading code - if (bytecodeInfo.Bytecode.IsEmpty) + // If there is no precompiled bytecode, just return the dynamic path + if (bytecodeInfo.Bytecode.IsDefaultOrEmpty) { bytecodeLiterals = null; - // This code produces a method declaration as follows: - // - // ComputeSharp.D2D1Interop.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, hlslSource); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.D2D1Interop.__Internals.D2D1ShaderCompiler"), - IdentifierName("LoadDynamicBytecode"))) - .AddArgumentListArguments( - Argument(IdentifierName("loader")).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), - Argument(IdentifierName("hlslSource"))))); + return Block(dynamicLoadingStatement); } - else - { - bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); - // This code produces the following statements: - // - // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; - // - // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string - // is created by the generator. This greatly speeds up the code generation, as it avoids - // having to create/parse tens of thousands of literal expression nodes for every shader. - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("bytecode")) - .WithInitializer( - EqualsValueClause( - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + + // This code produces a branch as follows: + // + // if (shaderProfile is null or ) + // { + // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // loader.LoadEmbeddedBytecode(bytecode); + // } + // + // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string + // is created by the generator. This greatly speeds up the code generation, as it avoids + // having to create/parse tens of thousands of literal expression nodes for every shader. + IfStatementSyntax embeddedBranch = + IfStatement( + IsPatternExpression( + IdentifierName("shaderProfile"), + BinaryPattern( + SyntaxKind.OrPattern, + ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)), + ConstantPattern( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(D2D1ShaderProfile)), + IdentifierName(D2D1ShaderProfile.PixelShader50.ToString()))))), + Block( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("bytecode")) .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE"))))))))); + EqualsValueClause( + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))), + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadEmbeddedBytecode"))) + .AddArgumentListArguments(Argument(IdentifierName("bytecode")))))); - // loader.LoadEmbeddedBytecode(bytecode); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadEmbeddedBytecode"))) - .AddArgumentListArguments(Argument(IdentifierName("bytecode"))))); - } - - return Block(statements); + // Return the combined block + return Block(embeddedBranch.WithElse(ElseClause(Block(dynamicLoadingStatement)))); } /// diff --git a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1BytecodeLoader.cs b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1BytecodeLoader.cs index 93a23f45..44ba0862 100644 --- a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1BytecodeLoader.cs +++ b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1BytecodeLoader.cs @@ -1,7 +1,7 @@ using System; using System.ComponentModel; -namespace ComputeSharp.__Internals; +namespace ComputeSharp.D2D1Interop.__Internals; /// /// A base representing a bytecode loader for a D2D1 shader. @@ -14,7 +14,7 @@ public interface ID2D1BytecodeLoader /// Loads a dynamic shader bytecode. /// /// An opaque handle to the shader bytecode. - /// Thrown if the shader has already been initialized or a precompiled bytecode was requested when not available.. + /// Thrown if the shader has already been initialized or a precompiled bytecode was requested when not available. void LoadDynamicBytecode(IntPtr handle); /// diff --git a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1DispatchDataLoader.cs b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1DispatchDataLoader.cs index 22e4c8c6..6593d706 100644 --- a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1DispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1DispatchDataLoader.cs @@ -1,7 +1,7 @@ using System; using System.ComponentModel; -namespace ComputeSharp.__Internals; +namespace ComputeSharp.D2D1Interop.__Internals; /// /// A base representing a data loader for a D2D1 shader being dispatched. diff --git a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs index 1f9666c2..ff16fac8 100644 --- a/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1Interop/Interfaces/__Internals/ID2D1Shader.cs @@ -1,6 +1,5 @@ using System; using System.ComponentModel; -using ComputeSharp.__Internals; namespace ComputeSharp.D2D1Interop.__Internals; diff --git a/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs b/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs index 539ba916..cc701968 100644 --- a/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ByteArrayDispatchDataLoader.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ComputeSharp.__Internals; +using ComputeSharp.D2D1Interop.__Internals; using TerraFX.Interop.DirectX; #pragma warning disable CS0618 diff --git a/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs b/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs index b7152cd3..0c473b1d 100644 --- a/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs +++ b/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1DrawInfoDispatchDataLoader.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ComputeSharp.__Internals; +using ComputeSharp.D2D1Interop.__Internals; using TerraFX.Interop.DirectX; #pragma warning disable CS0618 diff --git a/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs b/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs index 115d5dab..31773a15 100644 --- a/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs +++ b/src/ComputeSharp.D2D1Interop/Shaders/Dispatching/D2D1ShaderBytecodeLoader.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using ComputeSharp.__Internals; +using ComputeSharp.D2D1Interop.__Internals; using ComputeSharp.D2D1Interop.Extensions; using ComputeSharp.D2D1Interop.Helpers; using TerraFX.Interop.DirectX; @@ -9,7 +9,7 @@ using TerraFX.Interop.Windows; #pragma warning disable CS0618 -namespace ComputeSharp.Shaders.Dispatching; +namespace ComputeSharp.D2D1Interop.Shaders.Dispatching; /// /// A bytecode loader for D2D1 shaders. diff --git a/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1InteropServices.cs b/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1InteropServices.cs index 54cb44e9..40138ed6 100644 --- a/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1InteropServices.cs +++ b/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1InteropServices.cs @@ -2,7 +2,6 @@ using System.Runtime.CompilerServices; using ComputeSharp.D2D1Interop.Shaders.Dispatching; using ComputeSharp.D2D1Interop.Shaders.Interop.Buffers; -using ComputeSharp.Shaders.Dispatching; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -20,10 +19,12 @@ public static unsafe class D2D1InteropServices /// /// The type of D2D1 pixel shader to load the bytecode for. /// A instance with the resulting shader bytecode. - /// Thrown if the input shader has not been precompiled. /// - /// This method will only run correctly if the input shader has been precompiled, or it will throw an exception. - /// The returned instance will wrap a pinned memory buffer (from the PE section). + /// This method will only compile the shader using if no precompiled shader is available. + /// + /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section). + /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. + /// /// public static ReadOnlyMemory LoadShaderBytecode() where T : unmanaged, ID2D1PixelShader @@ -59,7 +60,7 @@ public static unsafe class D2D1InteropServices { D2D1ShaderBytecodeLoader bytecodeLoader = default; - Unsafe.NullRef().LoadBytecode(ref bytecodeLoader, shaderProfile, out _); + Unsafe.NullRef().LoadBytecode(ref bytecodeLoader, shaderProfile ?? D2D1ShaderProfile.PixelShader50); using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode); diff --git a/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1ReflectionServices.cs b/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1ReflectionServices.cs index 64e1c5f5..5c3e7d70 100644 --- a/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1ReflectionServices.cs +++ b/src/ComputeSharp.D2D1Interop/Shaders/Interop/D2D1ReflectionServices.cs @@ -2,7 +2,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.D2D1Interop.Extensions; -using ComputeSharp.Shaders.Dispatching; +using ComputeSharp.D2D1Interop.Shaders.Dispatching; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -23,9 +23,11 @@ public static class D2D1ReflectionServices public static unsafe D2D1ShaderInfo GetShaderInfo() where T : struct, ID2D1PixelShader { + Unsafe.NullRef().BuildHlslSource(out string hlslSource); + D2D1ShaderBytecodeLoader bytecodeLoader = default; - Unsafe.NullRef().LoadBytecode(ref bytecodeLoader, D2D1ShaderProfile.PixelShader50, out string hlslSource); + Unsafe.NullRef().LoadBytecode(ref bytecodeLoader, D2D1ShaderProfile.PixelShader50); using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode); diff --git a/src/ComputeSharp.D2D1Interop/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs b/src/ComputeSharp.D2D1Interop/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs new file mode 100644 index 00000000..4ff2dd9d --- /dev/null +++ b/src/ComputeSharp.D2D1Interop/Shaders/Translation/__Internals/D2D1ShaderCompiler.cs @@ -0,0 +1,38 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1Interop.__Internals; + +/// +/// A that uses the DXC APIs to compile compute shaders. +/// +[EditorBrowsable(EditorBrowsableState.Never)] +[Obsolete("This type is not intended to be used directly by user code")] +public static class D2D1ShaderCompiler +{ + /// + /// Compiles a new HLSL shader from the input source code. + /// + /// The type of bytecode loader being used. + /// The type of D2D1 shader being dispatched. + /// The instance to use to load the bytecode. + /// The input instance representing the D2D1 shader to run. + /// The shader profile to use to compile the shader. + /// Whether to enable linking support for the shader. + public static unsafe void LoadDynamicBytecode(ref TLoader loader, in T shader, D2D1ShaderProfile? shaderProfile, bool enableLinkingSupport) + where TLoader : struct, ID2D1BytecodeLoader + where T : struct, ID2D1Shader + { + Unsafe.AsRef(in shader).BuildHlslSource(out string hlslSource); + + using ComPtr d3DBlobBytecode = Shaders.Translation.D2D1ShaderCompiler.Compile( + hlslSource.AsSpan(), + shaderProfile ?? D2D1ShaderProfile.PixelShader50, + enableLinkingSupport); + + loader.LoadDynamicBytecode((IntPtr)d3DBlobBytecode.Get()); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index a49da76d..d7d13f57 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -171,11 +171,11 @@ public sealed partial class IShaderGenerator IdentifierName("ComputeSharp.__Internals.ShaderCompiler"), IdentifierName("LoadDynamicBytecode"))) .AddArgumentListArguments( - Argument(IdentifierName("loader")).WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword)), + Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), Argument(IdentifierName("threadsX")), Argument(IdentifierName("threadsY")), Argument(IdentifierName("threadsZ")), - Argument(ThisExpression()).WithRefOrOutKeyword(Token(SyntaxKind.InKeyword)))); + Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)))); } ///