From fb3439556c06abaa3bc09868985c4f25375539c4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 13 Dec 2023 13:13:26 +0100 Subject: [PATCH] Use forward declarations wherever possible --- ...xelShaderDescriptorGenerator.HlslSource.cs | 34 +++++++++++---- .../HlslDefinitionsSyntaxProcessor.cs | 43 +++++++++++++++---- ...uteShaderDescriptorGenerator.HlslSource.cs | 42 ++++++++++++++---- .../ComputeSharp.Tests/ShaderCompilerTests.cs | 12 +++--- 4 files changed, 99 insertions(+), 32 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index eb99986f..93b2f1d9 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -97,12 +97,14 @@ partial class D2DPixelShaderDescriptorGenerator token.ThrowIfCancellationRequested(); // Process the discovered types and constants - ImmutableArray declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( + HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods, - constructors); + constructors, + out ImmutableArray typeDeclarations, + out ImmutableArray typeMethodDeclarations); token.ThrowIfCancellationRequested(); @@ -125,11 +127,12 @@ partial class D2DPixelShaderDescriptorGenerator // Get the HLSL source return GetHlslSource( definedConstants, - declaredTypes, valueFields, resourceTextureFields, staticFields, processedMethods, + typeDeclarations, + typeMethodDeclarations, entryPoint, inputCount, inputSimpleIndices, @@ -449,11 +452,12 @@ partial class D2DPixelShaderDescriptorGenerator /// Produces the series of statements to build the current HLSL source. /// /// The sequence of defined constants for the shader. - /// The sequence of declared types used by the shader. /// The sequence of value instance fields for the current shader. /// The sequence of captured resource textures for the current shader. /// The sequence of static fields referenced by the shader. /// The sequence of processed methods used by the shader. + /// The collection of declarations of all custom types. + /// The collection of implementations of all methods in all custom types. /// The body of the entry point of the shader. /// The number of shader inputs to declare. /// The indicess of the simple shader inputs. @@ -462,11 +466,12 @@ partial class D2DPixelShaderDescriptorGenerator /// The series of statements to build the HLSL source to compile to execute the current shader. private static string GetHlslSource( ImmutableArray definedConstants, - ImmutableArray declaredTypes, ImmutableArray valueFields, ImmutableArray resourceTextureFields, ImmutableArray staticFields, ImmutableArray processedMethods, + ImmutableArray typeDeclarations, + ImmutableArray typeMethodDeclarations, string executeMethod, int inputCount, ImmutableArray inputSimpleIndices, @@ -513,6 +518,15 @@ partial class D2DPixelShaderDescriptorGenerator writer.WriteLine(skipIfPresent: true); + // Forward declarations of shader/static methods + foreach (HlslMethod method in processedMethods) + { + writer.WriteLine(skipIfPresent: true); + writer.WriteLine(method.Signature); + } + + writer.WriteLine(skipIfPresent: true); + // Static fields foreach (HlslStaticField field in staticFields) { @@ -526,8 +540,10 @@ partial class D2DPixelShaderDescriptorGenerator } } + writer.WriteLine(skipIfPresent: true); + // Declared types - foreach (HlslUserType userType in declaredTypes) + foreach (HlslUserType userType in typeDeclarations) { writer.WriteLine(skipIfPresent: true); writer.WriteLine(userType.Definition); @@ -549,11 +565,11 @@ partial class D2DPixelShaderDescriptorGenerator writer.WriteLine($"SamplerState __sampler__{field.Name} : register(s{field.Index});"); } - // Forward declarations - foreach (HlslMethod method in processedMethods) + // Method declarations for discovered types + foreach (string method in typeMethodDeclarations) { writer.WriteLine(skipIfPresent: true); - writer.WriteLine(method.Signature); + writer.WriteLine(method); } // Captured methods diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 0e9cab64..f1d10d04 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -143,15 +143,19 @@ internal static class HlslDefinitionsSyntaxProcessor /// The sequence of discovered custom types. /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. - /// A sequence of custom type definitions to add to the shader source. - public static ImmutableArray GetDeclaredTypes( + /// The collection of declarations of all custom types. + /// The collection of implementations of all methods in all custom types. + public static void GetDeclaredTypes( ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, IEnumerable types, IReadOnlyDictionary instanceMethods, - IReadOnlyDictionary constructors) + IReadOnlyDictionary constructors, + out ImmutableArray typeDeclarations, + out ImmutableArray methodDeclarations) { - using ImmutableArrayBuilder builder = new(); + using ImmutableArrayBuilder typeDeclarationsBuilder = new(); + using ImmutableArrayBuilder methodDeclarationsBuilder = new(); IReadOnlyCollection invalidTypes; @@ -223,11 +227,33 @@ internal static class HlslDefinitionsSyntaxProcessor } } - // Declare the methods of the current type - structDeclaration = structDeclaration.WithMembers(structDeclaration.Members.AddRange(GatherInstanceMethods(type, instanceMethods, constructors))); + using (ImmutableArrayBuilder methodDefinitions = new()) + { + // Forward declarations for all methods, and implementations. + // We need these to ensure things work with arbitrary ordering. + foreach (MethodDeclarationSyntax methodDeclaration in GatherInstanceMethods(type, instanceMethods, constructors)) + { + methodDefinitions.Add(methodDeclaration.AsDefinition()); + + // We need to normalize the whitespaces here, as this methhod declaration will not be added to + // the list of members for the struct declaration, but rather it will be written directly into + // the resulting HLSL source (as the implementation of this forward declaration). For the same + // reason, we also need to change the identifier to also include the containing type with '::'. + string methodImplementation = + methodDeclaration + .WithIdentifier(Identifier($"{structType}::{methodDeclaration.Identifier.Text}")) + .NormalizeWhitespace(eol: "\n") + .ToFullString(); + + methodDeclarationsBuilder.Add(methodImplementation); + } + + // Add all method forward declarations to the current type + structDeclaration = structDeclaration.WithMembers(structDeclaration.Members.AddRange(methodDefinitions.AsEnumerable())); + } // Insert the trailing ; right after the closing bracket (after normalization) - builder.Add(( + typeDeclarationsBuilder.Add(( structType, structDeclaration .NormalizeWhitespace(eol: "\n") @@ -241,7 +267,8 @@ internal static class HlslDefinitionsSyntaxProcessor diagnostics.Add(InvalidDiscoveredType, structDeclarationSymbol, structDeclarationSymbol, invalidType); } - return builder.ToImmutable(); + typeDeclarations = typeDeclarationsBuilder.ToImmutable(); + methodDeclarations = methodDeclarationsBuilder.ToImmutable(); } /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index 7a442894..4ae2df24 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -114,12 +114,14 @@ partial class ComputeShaderDescriptorGenerator token.ThrowIfCancellationRequested(); // Process the discovered types and constants - ImmutableArray declaredTypes = HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( + HlslDefinitionsSyntaxProcessor.GetDeclaredTypes( diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods, - constructors); + constructors, + out ImmutableArray typeDeclarations, + out ImmutableArray typeMethodDeclarations); token.ThrowIfCancellationRequested(); @@ -136,12 +138,13 @@ partial class ComputeShaderDescriptorGenerator threadsY, threadsZ, definedConstants, - declaredTypes, resourceFields, valueFields, staticFields, sharedBuffers, processedMethods, + typeDeclarations, + typeMethodDeclarations, isComputeShader, implicitTextureType, isSamplerUsed, @@ -487,12 +490,13 @@ partial class ComputeShaderDescriptorGenerator /// The thread ids value for the Y axis. /// The thread ids value for the Z axis. /// The sequence of defined constants for the shader. - /// The sequence of declared types used by the shader. /// The sequence of resource instance fields for the current shader. /// The sequence of value instance fields for the current shader. /// The sequence of static fields referenced by the shader. /// The sequence of shared buffers declared by the shader. /// The sequence of processed methods used by the shader. + /// The collection of declarations of all custom types. + /// The collection of implementations of all methods in all custom types. /// Whether or not the current shader type is a compute shader. /// The type of the implicit target texture, if present. /// Whether the static sampler is used by the shader. @@ -503,12 +507,13 @@ partial class ComputeShaderDescriptorGenerator int threadsY, int threadsZ, ImmutableArray definedConstants, - ImmutableArray declaredTypes, ImmutableArray resourceFields, ImmutableArray valueFields, ImmutableArray staticFields, ImmutableArray sharedBuffers, ImmutableArray processedMethods, + ImmutableArray typeDeclarations, + ImmutableArray typeMethodDeclarations, bool isComputeShader, string? implicitTextureType, bool isSamplerUsed, @@ -539,6 +544,23 @@ partial class ComputeShaderDescriptorGenerator writer.WriteLine(skipIfPresent: true); + // Forward declarations of discovered types + foreach (HlslUserType userType in typeDeclarations) + { + writer.WriteLine($"struct {userType.Name};"); + } + + writer.WriteLine(skipIfPresent: true); + + // Forward declarations of shader/static methods + foreach (HlslMethod method in processedMethods) + { + writer.WriteLine(skipIfPresent: true); + writer.WriteLine(method.Signature); + } + + writer.WriteLine(skipIfPresent: true); + // Static fields foreach (HlslStaticField field in staticFields) { @@ -552,8 +574,10 @@ partial class ComputeShaderDescriptorGenerator } } + writer.WriteLine(skipIfPresent: true); + // Declared types - foreach (HlslUserType userType in declaredTypes) + foreach (HlslUserType userType in typeDeclarations) { writer.WriteLine(skipIfPresent: true); writer.WriteLine(userType.Definition); @@ -621,11 +645,11 @@ partial class ComputeShaderDescriptorGenerator writer.WriteLine($"groupshared {buffer.Type} {buffer.Name} [{count}];"); } - // Forward declarations - foreach (HlslMethod method in processedMethods) + // Method declarations for discovered types + foreach (string method in typeMethodDeclarations) { writer.WriteLine(skipIfPresent: true); - writer.WriteLine(method.Signature); + writer.WriteLine(method); } // Captured methods diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 3041b053..3d44b4df 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -722,6 +722,10 @@ namespace ComputeSharp.Tests #define __GroupSize__get_Y 1 #define __GroupSize__get_Z 1 + static void Foo(in int a, in int b, inout int c, out int d); + + static void Bar(in int a, in int b, inout int c, out int d); + cbuffer _ : register(b0) { uint __x; @@ -731,10 +735,6 @@ namespace ComputeSharp.Tests RWStructuredBuffer __reserved__buffer : register(u0); - static void Foo(in int a, in int b, inout int c, out int d); - - static void Bar(in int a, in int b, inout int c, out int d); - static void Foo(in int a, in int b, inout int c, out int d) { d = 0; @@ -805,6 +805,8 @@ namespace ComputeSharp.Tests #define __GroupSize__get_Z 1 #define __ComputeSharp_Tests_ShaderCompilerTests_ShaderWithPartialDeclarations__a 2 + static int Sum(int x, int y); + static const int b = 4; cbuffer _ : register(b0) @@ -816,8 +818,6 @@ namespace ComputeSharp.Tests RWStructuredBuffer __reserved__buffer : register(u0); - static int Sum(int x, int y); - static int Sum(int x, int y) { return x + y;