From 2e020a1524cdb215b6905648f0a068eedafd2faa Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 13 Oct 2023 11:22:11 +0200 Subject: [PATCH] Remove checks for dynamic shader in source generator --- .../Translation/__Internals/ShaderCompiler.cs | 38 --------- ...ator.CreateBuildHlslSourceMethod.Syntax.cs | 3 +- ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 84 ++----------------- .../IShaderGenerator.cs | 27 +++--- .../Interfaces/__Internals/IBytecodeLoader.cs | 8 -- .../Dispatching/ShaderBytecodeLoader.cs | 14 +--- 6 files changed, 19 insertions(+), 155 deletions(-) delete mode 100644 src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs diff --git a/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs b/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs deleted file mode 100644 index 709314f8..00000000 --- a/src/ComputeSharp.Dynamic/Shaders/Translation/__Internals/ShaderCompiler.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; - -namespace ComputeSharp.__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 ShaderCompiler -{ - /// - /// Compiles a new HLSL shader from the input source code. - /// - /// The type of bytecode loader being used. - /// The type of shader being dispatched. - /// The instance to use to load the bytecode. - /// The number of threads in each thread group for the X axis. - /// The number of threads in each thread group for the Y axis. - /// The number of threads in each thread group for the Z axis. - /// The input instance representing the compute shader to run. - public static unsafe void LoadDynamicBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ, in T shader) - where TLoader : struct, IBytecodeLoader - where T : struct, IShader - { - Unsafe.AsRef(in shader).BuildHlslSource(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ); - - using ComPtr dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(builder.WrittenSpan); - - builder.Dispose(); - - loader.LoadDynamicBytecode((IntPtr)dxcBlobBytecode.Get()); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index e41f96a7..610a3f83 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -22,10 +22,9 @@ partial class IShaderGenerator /// Creates a instance for the BuildHlslSource method. /// /// The input instance to use. - /// Indicates whether or not dynamic shaders are supported. /// The depth of the hierarchy for this type (used to calculate the right indentation). /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, bool supportsDynamicShaders, int hierarchyDepth) + public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) { // Generate the necessary body statements depending on whether dynamic shaders are supported ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 81b8bd06..9538ffb4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -23,12 +23,11 @@ partial class IShaderGenerator /// Creates a instance for the TryGetBytecode method. /// /// The input instance. - /// Indicates whether or not dynamic shaders are supported. /// An opaque instance to transform the final tree into text. /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, bool supportsDynamicShaders, out Func fixup) + public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) { - BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, supportsDynamicShaders, out string? bytecodeLiterals); + BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); if (bytecodeLiterals is not null) { @@ -66,25 +65,16 @@ partial class IShaderGenerator /// Gets a instance with the logic to try to get a compiled shader bytecode. /// /// The input instance. - /// Indicates whether or not dynamic shaders are supported. /// The resulting bytecode literals to insert into the final source code. /// The instance trying to retrieve the precompiled shader. - private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, bool supportsDynamicShaders, out string? bytecodeLiterals) + private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) { if (bytecodeInfo.Bytecode.IsEmpty) { bytecodeLiterals = null; - if (supportsDynamicShaders) - { - // Return the dynamic compilation path - return Block(GetDynamicCompilationStatement()); - } - else - { - // Faulting path - return Block(GetDynamicCompilationFaultingBlock()); - } + // Faulting path + return Block(); } bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan()); @@ -142,70 +132,8 @@ partial class IShaderGenerator IdentifierName("LoadEmbeddedBytecode"))) .AddArgumentListArguments(Argument(IdentifierName("bytecode")))))); - // If dynamic shaders are supported, return the combined block - if (supportsDynamicShaders) - { - return Block(embeddedBranch.WithElse(ElseClause(Block(GetDynamicCompilationStatement())))); - } - // If there is no dynamic shader support, add the faulting path after the branch - return Block(embeddedBranch.WithElse(ElseClause(Block(GetDynamicCompilationFaultingBlock())))); - } - - /// - /// The cached tree of dynamic statements. - /// - private static StatementSyntax? dynamicStatement; - - /// - /// Returns the instance to create a new dynamic shader. - /// - /// The instance to create a new dynamic shader. - private static StatementSyntax GetDynamicCompilationStatement() - { - // This code produces a method declaration as follows: - // - // ComputeSharp.__Internals.ShaderCompiler.LoadDynamicBytecode(ref loader, threadsX, threadsY, threadsZ, in this); - return dynamicStatement ??= - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("ComputeSharp.__Internals.ShaderCompiler"), - IdentifierName("LoadDynamicBytecode"))) - .AddArgumentListArguments( - Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), - Argument(IdentifierName("threadsX")), - Argument(IdentifierName("threadsY")), - Argument(IdentifierName("threadsZ")), - Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)))); - } - - /// - /// The cached tree of dynamic fault statement. - /// - private static ExpressionStatementSyntax? dynamicFaultStatement; - - /// - /// Returns a instances to perform a faulting call to LoadDynamicBytecode(IntPtr). - /// - /// A instances to perform a faulting call to LoadDynamicBytecode(IntPtr). - private static ExpressionStatementSyntax GetDynamicCompilationFaultingBlock() - { - // This code produces a faulting call as follows: - // - // loader.LoadDynamicBytecode(default); - return dynamicFaultStatement ??= - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadDynamicBytecode"))) - .AddArgumentListArguments( - Argument(LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword))))); + return Block(embeddedBranch.WithElse(ElseClause(Block()))); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 20698149..29d98041 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -22,11 +22,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { - // Check whether or not dynamic shaders are supported - IncrementalValueProvider supportsDynamicShaders = - context.CompilationProvider - .Select(static (compilation, _) => false); - // Discover all shader types and extract all the necessary info from each of them IncrementalValuesProvider shaderInfoWithErrors = context.SyntaxProvider @@ -130,18 +125,17 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator }); // Get the BuildHlslSource info (hierarchy, HLSL source and parsing options) - IncrementalValuesProvider<((HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource) Left, bool SupportsDynamicShaders)> hlslSourceInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource)> hlslSourceInfo = shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)) - .Combine(supportsDynamicShaders); + .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)); // Generate the BuildHlslSource() methods context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => { - MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.HlslShaderSource, item.SupportsDynamicShaders, item.Left.Hierarchy.Hierarchy.Length); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true); + MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslShaderSource, item.Hierarchy.Hierarchy.Length); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true); - context.AddSource($"{item.Left.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); // Get the LoadDispatchMetadata() info (hierarchy and dispatch metadata info) @@ -198,19 +192,18 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator context.ReportDiagnostics(embeddedBytecodeDiagnostics); // Get the TryGetBytecode() info (hierarchy and compiled bytecode) - IncrementalValuesProvider<((HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode) Info, bool SupportsDynamicShaders)> embeddedBytecodeInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode)> embeddedBytecodeInfo = embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode)) - .Combine(supportsDynamicShaders); + .Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode)); // Generate the TryGetBytecode() methods context.RegisterSourceOutput(embeddedBytecodeInfo, static (context, item) => { - MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Info.EmbeddedBytecode, item.SupportsDynamicShaders, out Func fixup); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false); + MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.EmbeddedBytecode, out Func fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false); SourceText text = fixup(compilationUnit); - context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text); + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text); }); } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs index e3dbc4b3..7521536c 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IBytecodeLoader.cs @@ -10,14 +10,6 @@ namespace ComputeSharp.__Internals; [Obsolete("This interface is not intended to be used directly by user code")] public interface IBytecodeLoader { - /// - /// Loads a dynamic shader bytecode. - /// - /// An opaque handle to the shader bytecode. - /// Thrown if the shader has already been initialized. - /// Thrown if is (indicating an unsupported configuration). - void LoadDynamicBytecode(IntPtr handle); - /// /// Loads the embedded shader bytecode for the shader being dispatched. /// diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs index 345473de..c9a60a5b 100644 --- a/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs +++ b/src/ComputeSharp/Shaders/Dispatching/ShaderBytecodeLoader.cs @@ -2,7 +2,6 @@ using System; using System.Runtime.CompilerServices; using ComputeSharp.__Internals; using ComputeSharp.Shaders.Models; -using TerraFX.Interop.DirectX; #pragma warning disable CS0618 @@ -22,24 +21,15 @@ internal struct ShaderBytecodeLoader : IBytecodeLoader /// Gets the current cached shader instance. /// /// The current instance. - /// Thrown if the shader has not been initialized. + /// Thrown if the HLSL bytecode is not available. [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ICachedShader GetCachedShader() { - default(InvalidOperationException).ThrowIf(this.cachedShader is null); + default(NotSupportedException).ThrowIf(this.cachedShader is null); return this.cachedShader; } - /// - public unsafe void LoadDynamicBytecode(IntPtr handle) - { - default(InvalidOperationException).ThrowIf(this.cachedShader is not null); - default(NotSupportedException).ThrowIf(handle == IntPtr.Zero); - - this.cachedShader = new ICachedShader.Dynamic((IDxcBlob*)handle); - } - /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void LoadEmbeddedBytecode(ReadOnlySpan bytecode)