From bcc336440330d6dc8294d271ca09a763f84100df Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 7 Jul 2021 14:10:38 +0200 Subject: [PATCH 01/37] Switched hashcode generator to use IShader.GetDispatchId() --- .../IComputeShaderHashCodeGenerator.cs | 197 ++++++++++++------ .../Interfaces/__Internals/IShader{TSelf}.cs | 23 ++ 2 files changed, 160 insertions(+), 60 deletions(-) create mode 100644 src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index c6e5b676..b4f63129 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -1,6 +1,7 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics.Contracts; +using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; @@ -10,6 +11,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; namespace ComputeSharp.SourceGenerators { @@ -34,9 +36,15 @@ namespace ComputeSharp.SourceGenerators return; } - // Type attributes + // Method attributes AttributeListSyntax[] attributes = new[] { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), AttributeList(SingletonSeparatedList( Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), @@ -44,14 +52,14 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( AttributeArgument(LiteralExpression( SyntaxKind.StringLiteralExpression, - Literal("This type is not intended to be used directly by user code")))))) + Literal("This method is not intended to be used directly by user code")))))) }; foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) { try { - OnExecute(context, item.StructDeclaration, item.StructSymbol, ref attributes); + OnExecute(context, item.StructDeclaration, item.StructSymbol, attributes); } catch { @@ -66,90 +74,159 @@ namespace ComputeSharp.SourceGenerators /// The input instance to use. /// The node to process. /// The for . - /// The list of instances to append to the first copy of the partial class being generated. - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes) + /// The list of instances to append to the generated method. + private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, AttributeListSyntax[] attributes) { - TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol)); + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; - if (block.Statements.Count == 1) return; + // Create the partial shader type declaration with the hashcode interface method implementation. + // This code produces a struct declaration as follows: + // + // public struct ShaderType : IShader + // { + // [GeneratedCode("...", "...")] + // [DebuggerNonUserCode] + // [ExcludeFromCodeCoverage] + // [EditorBrowsable(EditorBrowsableState.Never)] + // [Obsolete("This method is not intended to be called directly by user code")] + // public int GetDispatchId() + // { + // + // } + // } + var structDeclarationSyntax = + StructDeclaration(structName).WithModifiers(structModifiers) + .AddBaseListTypes(SimpleBaseType( + GenericName(Identifier("IShader")) + .AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .AddAttributeLists(attributes) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(structDeclarationSymbol))); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (var parentType in structDeclaration.Ancestors().OfType()) + { + typeDeclarationSyntax = parentType + .WithMembers(SingletonList(typeDeclarationSyntax)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithAttributeLists(List()) + .WithoutTrivia(); + } // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: // // using System; + // using System.CodeDom.Compiler; // using System.ComponentModel; + // using System.Diagnostics; + // using System.Diagnostics.CodeAnalysis; + // using ComputeSharp.__Internals; // - // namespace ComputeSharp.__Internals + // #pragma warning disable + // + // namespace // { - // internal static partial class HashCodeProvider - // { - // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] - // [System.Obsolete("This method is not intended to be called directly by user code")] - // public static int CombineHashCode(int hash, in ShaderType shader) - // { - // return ...; - // } - // } + // // } var source = CompilationUnit().AddUsings( UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers( - NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( - ClassDeclaration("HashCodeProvider").AddModifiers( - Token(SyntaxKind.InternalKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("CombineHash")).AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( - Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType)) - .WithBody(block)))) + UsingDirective(IdentifierName("System.CodeDom.Compiler")), + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Diagnostics")), + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), + UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace() .ToFullString(); - // Clear the attribute list to avoid duplicates - attributes = Array.Empty(); - // Add the method source attribute context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); } /// - /// Gets a sequence of statements to process the hashcode of the captured delegates. + /// Gets a instance with the logic to compute the hashcode of a given shader type. /// /// The input instance to process. - /// The sequence of instances to hash the captured delegates. + /// The instance to hash the input shader. [Pure] - private static IEnumerable GetDelegateHashCodeStatements(INamedTypeSymbol structDeclarationSymbol) + private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol) { - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + var delegateFields = structDeclarationSymbol + .GetMembers() + .OfType() + .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) + .ToImmutableArray(); + + if (delegateFields.Length == 0) { - if (fieldSymbol.Type is not INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false } typeSymbol) - { - continue; - } - - // hash += hash << 5; - yield return ExpressionStatement(ParseExpression($"hash += hash << 5")); - - // hash += shader.Field[#i].Method.GetHashCode(); - yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldSymbol.Name}.Method.GetHashCode()")); + // return HashCode.Combine(typeof(T)); + return + Block(ReturnStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("HashCode"), + IdentifierName("Combine"))) + .AddArgumentListArguments(Argument(TypeOfExpression(IdentifierName(structDeclarationSymbol.Name)))))); } - yield return ReturnStatement(IdentifierName("hash")); + List blockStatements = new(4); + + // HashCode hashCode = default; + blockStatements.Add(LocalDeclarationStatement( + VariableDeclaration(IdentifierName("HashCode")) + .AddVariables( + VariableDeclarator(Identifier("hashCode")) + .WithInitializer(EqualsValueClause( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword))))))); + + // hashCode.Add(typeof(T)); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument(TypeOfExpression(IdentifierName(structDeclarationSymbol.Name)))))); + + foreach (IFieldSymbol fieldSymbol in delegateFields) + { + // hashCode.Add(delegateField.Method); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("foo"), + IdentifierName("Method")))))); + } + + // return hashCode.ToHashCode(); + blockStatements.Add(ReturnStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("ToHashCode"))))); + + return Block(blockStatements); } } } diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs new file mode 100644 index 00000000..51af2bbf --- /dev/null +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs @@ -0,0 +1,23 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// A base representing a given shader that can be dispatched. + /// + /// The type of shader. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public interface IShader + where TSelf : struct, IShader + { + /// + /// Gets a unique dispatch identifier for the shader. + /// + /// The unique dispatch identifier for the shader. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + int GetDispatchId(); + } +} From ae0738441765d86e008ad82b909a4a2d62f2e8ec Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 7 Jul 2021 14:20:52 +0200 Subject: [PATCH 02/37] Removed ShaderHashCodeProvider, switched to interface method --- .../GraphicsDeviceExtensions.Dispatching.cs | 20 +++-- src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 6 +- .../Translation/ShaderHashCodeProvider.cs | 75 ------------------- .../ComputeSharp.Tests/ShaderMembersTests.cs | 1 - 4 files changed, 12 insertions(+), 90 deletions(-) delete mode 100644 src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 543ec018..25b55a2b 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -1,9 +1,7 @@ -using System; -using System.Diagnostics.Contracts; +using ComputeSharp.Shaders; using ComputeSharp.__Internals; -using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Resources; -using ComputeSharp.Shaders; + +#pragma warning disable CS0618 namespace ComputeSharp { @@ -20,7 +18,7 @@ namespace ComputeSharp /// The number of iterations to run on the X axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, 1, 1, in shader); } @@ -34,7 +32,7 @@ namespace ComputeSharp /// The number of iterations to run on the Y axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, y, 1, in shader); } @@ -49,7 +47,7 @@ namespace ComputeSharp /// The number of iterations to run on the Z axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, int z, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, y, z, in shader); } @@ -67,7 +65,7 @@ namespace ComputeSharp /// The number of threads in each thread group for the Z axis. /// The input instance representing the compute shader to run. public static void For(this GraphicsDevice device, int x, int y, int z, int threadsX, int threadsY, int threadsZ, in T shader) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, in shader); } @@ -80,7 +78,7 @@ namespace ComputeSharp /// The to use to run the shader. /// The target texture to apply the pixel shader to. public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { ShaderRunner.Run(device, texture, default); @@ -95,7 +93,7 @@ namespace ComputeSharp /// The target texture to apply the pixel shader to. /// The input instance representing the pixel shader to run. public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture, in T shader) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { ShaderRunner.Run(device, texture, in shader); diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 220b2c2c..40538161 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -23,7 +23,7 @@ namespace ComputeSharp.Shaders /// /// The type of compute shader to run. internal static class ShaderRunner - where T : struct + where T : struct, IShader { /// /// The mapping used to cache and reuse compiled shaders. @@ -131,7 +131,7 @@ namespace ComputeSharp.Shaders Guard.IsBetweenOrEqualTo(groupsZ, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); // Create the shader key - ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, threadsZ); + ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ); CachedShader shaderData; PipelineData? pipelineData; @@ -202,7 +202,7 @@ namespace ComputeSharp.Shaders Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); // Create the shader key - ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, 1); + ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, 1); CachedShader shaderData; PipelineData? pipelineData; diff --git a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs deleted file mode 100644 index 2304eba6..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A that handles the cache system for the generated shaders. - /// - internal static class ShaderHashCodeProvider - { - /// - /// A type containing static info for a given shader type . - /// - /// The type of compute shader currently in use. - private static class TypeInfo - where T : struct - { - /// - /// The id of the compute shader type in use. - /// - public static readonly int Id; - - /// - /// The optional instance, if needed. - /// - public static readonly Hasher? Hasher; - - /// - /// Initializes the static members of the type. - /// - static TypeInfo() - { - Id = HashCode.Combine(typeof(T)); - - // Get the generated hasher, if one if present - if (typeof(T).Assembly.GetType("ComputeSharp.__Internals.HashCodeProvider") is Type type && - type.GetMethod("CombineHash", new[] { typeof(int), typeof(T).MakeByRefType() }) is MethodInfo method) - { - Hasher = method.CreateDelegate>(); - } - } - } - - /// - /// Gets a unique hashcode for the input compute shader instance. - /// - /// The type of compute shader currently in use. - /// The input instance representing the shader to run. - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int GetHashCode(in T shader) - where T : struct - { - int hash = TypeInfo.Id; - - Hasher? hasher = TypeInfo.Hasher; - - if (hasher != null) hash = hasher(hash, in shader); - - return hash; - } - - /// - /// A that represents an aggregate hash function for a given instance. - /// - /// The type of compute shader currently in use. - /// The initial hash value. - /// The compute shader instance to use to compute the final hash value. - /// The final hash value for the input closure. - private delegate int Hasher(int hash, in T shader) - where T : struct; - } -} diff --git a/tests/ComputeSharp.Tests/ShaderMembersTests.cs b/tests/ComputeSharp.Tests/ShaderMembersTests.cs index cff85204..00d40cf7 100644 --- a/tests/ComputeSharp.Tests/ShaderMembersTests.cs +++ b/tests/ComputeSharp.Tests/ShaderMembersTests.cs @@ -1,4 +1,3 @@ -using System; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; From 2d579758cdad61d3495192650006938c0f7b4127 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 7 Jul 2021 21:13:36 +0200 Subject: [PATCH 03/37] Removed unnecessary hashcode computation --- .../IComputeShaderHashCodeGenerator.cs | 20 ++++--------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index b4f63129..20500ae1 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -170,15 +170,12 @@ namespace ComputeSharp.SourceGenerators if (delegateFields.Length == 0) { - // return HashCode.Combine(typeof(T)); + // return 0; return Block(ReturnStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("HashCode"), - IdentifierName("Combine"))) - .AddArgumentListArguments(Argument(TypeOfExpression(IdentifierName(structDeclarationSymbol.Name)))))); + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); } List blockStatements = new(4); @@ -193,15 +190,6 @@ namespace ComputeSharp.SourceGenerators SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword))))))); - // hashCode.Add(typeof(T)); - blockStatements.Add(ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument(TypeOfExpression(IdentifierName(structDeclarationSymbol.Name)))))); - foreach (IFieldSymbol fieldSymbol in delegateFields) { // hashCode.Add(delegateField.Method); From 8aa02ea0cc16882cab4ddc4cb00134c0f98b628d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Jul 2021 13:06:04 +0200 Subject: [PATCH 04/37] Added IDispatchDataLoader and compute shader loader --- .../__Internals/IDispatchDataLoader.cs | 29 ++++++++++ .../Interfaces/__Internals/IShader{TSelf}.cs | 14 +++++ .../ComputeShaderDispatchDataLoader.cs | 57 +++++++++++++++++++ src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 22 ++----- 4 files changed, 104 insertions(+), 18 deletions(-) create mode 100644 src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs create mode 100644 src/ComputeSharp/Shaders/Dispatching/ComputeShaderDispatchDataLoader.cs diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs new file mode 100644 index 00000000..c74fc4a7 --- /dev/null +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs @@ -0,0 +1,29 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// A base representing a data loader for a shader being dispatched. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public interface IDispatchDataLoader + { + /// + /// Loads the captured values used by the shader to be dispatched. + /// + /// The sequence of serialized captured values. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadCapturedValues(ReadOnlySpan data); + + /// + /// Loads the captured resources used by the shader to be dispatched. + /// + /// The sequence of serialized resources. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadCapturedResources(ReadOnlySpan data); + } +} diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs index 51af2bbf..d3389bf0 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs @@ -19,5 +19,19 @@ namespace ComputeSharp.__Internals [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This interface is not intended to be used directly by user code")] int GetDispatchId(); + + /// + /// Loads the dispatch data for the shader. + /// + /// The type of data loader being used. + /// The instance to use to load the data. + /// The device the shader is being dispatched on. + /// The number of iterations to run on the X axis. + /// The number of iterations to run on the Y axis. + /// The number of iterations to run on the Z axis. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadDispatchData(in TDataLoader dataLoader, GraphicsDevice device, int x, int y, int z) + where TDataLoader : struct, IDispatchDataLoader; } } diff --git a/src/ComputeSharp/Shaders/Dispatching/ComputeShaderDispatchDataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ComputeShaderDispatchDataLoader.cs new file mode 100644 index 00000000..86bc33f6 --- /dev/null +++ b/src/ComputeSharp/Shaders/Dispatching/ComputeShaderDispatchDataLoader.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.__Internals; +using TerraFX.Interop; +using System.Runtime.InteropServices; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Shaders.Dispatching +{ + /// + /// A data loader for compute shaders. + /// + internal readonly unsafe struct ComputeShaderDispatchDataLoader : IDispatchDataLoader + { + /// + /// The object in use. + /// + private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ComputeShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) + { + this.d3D12GraphicsCommandList = d3D12GraphicsCommandList; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void LoadCapturedValues(ReadOnlySpan data) + { + this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data); + } + + /// + public void LoadCapturedResources(ReadOnlySpan data) + { + ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList; + ref ulong resourcesRef = ref MemoryMarshal.GetReference(data); + ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As(ref resourcesRef); + ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length); + uint offset = 1; + + while (Unsafe.IsAddressLessThan(ref startRef, ref endRef)) + { + d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef); + + startRef = ref Unsafe.Add(ref startRef, 1); + offset++; + } + } + } +} diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 40538161..a9cee52b 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -13,6 +13,7 @@ using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; +using ComputeSharp.Shaders.Dispatching; #pragma warning disable CS0618 @@ -120,7 +121,6 @@ namespace ComputeSharp.Shaders Guard.IsBetweenOrEqualTo(threadsZ, 1, 64, nameof(threadsZ)); Guard.IsLessThanOrEqualTo(threadsX * threadsY * threadsZ, 1024, "threadsXYZ"); - // Calculate the dispatch values int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1), groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1), @@ -130,15 +130,13 @@ namespace ComputeSharp.Shaders Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); Guard.IsBetweenOrEqualTo(groupsZ, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); - // Create the shader key ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ); - CachedShader shaderData; PipelineData? pipelineData; lock (ShadersCache) { // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out shaderData)) + if (!ShadersCache.TryGetValue(key, out CachedShader shaderData)) { LoadShader(threadsX, threadsY, threadsZ, in shader, out shaderData); @@ -153,27 +151,15 @@ namespace ComputeSharp.Shaders } } - // Create the commands list and set the pipeline state using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState); - // Extract the dispatch data for the shader invocation - using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, z); + ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); - // Initialize the loop targets and the captured values - commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables); + shader.LoadDispatchData(in dataLoader, device, x, y, z); - ReadOnlySpan resources = dispatchData.Resources; - - for (int i = 0; i < resources.Length; i++) - { - // Load the captured buffers - commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 1, resources[i]); - } - - // Dispatch and wait for completion commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, (uint)groupsZ); commandList.ExecuteAndWaitForCompletion(); } From 7e86a23d7690465f2043fe9a13d93ba75e0b5e42 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Jul 2021 15:14:22 +0200 Subject: [PATCH 05/37] Updated IComputeShaderDataLoaderGenerator to use IShader --- .../IComputeShaderDataLoaderGenerator.cs | 279 ++++++++++++++---- .../IComputeShaderHashCodeGenerator.cs | 2 +- 2 files changed, 217 insertions(+), 64 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index dea57d54..1445d993 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -14,6 +14,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; #pragma warning disable CS0618 @@ -40,9 +41,15 @@ namespace ComputeSharp.SourceGenerators return; } - // Type attributes + // Method attributes AttributeListSyntax[] attributes = new[] { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), AttributeList(SingletonSeparatedList( Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), @@ -50,14 +57,14 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( AttributeArgument(LiteralExpression( SyntaxKind.StringLiteralExpression, - Literal("This type is not intended to be used directly by user code")))))) + Literal("This method is not intended to be used directly by user code")))))) }; foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) { try { - OnExecute(context, item.StructDeclaration, item.StructSymbol, ref attributes); + OnExecute(context, item.StructDeclaration, item.StructSymbol, attributes); } catch { @@ -72,72 +79,107 @@ namespace ComputeSharp.SourceGenerators /// The input instance to use. /// The node to process. /// The for . - /// The list of instances to append to the first copy of the partial class being generated. - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, ref AttributeListSyntax[] attributes) + /// The list of instances to append to the generated method. + private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, AttributeListSyntax[] attributes) { - TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out int root32BitConstantsCount)); + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; + IEnumerable blockStatements = GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out int root32BitConstantsCount); + + // Create the partial shader type declaration with the hashcode interface method implementation. + // This code produces a struct declaration as follows: + // + // public struct ShaderType : IShader + // { + // [GeneratedCode("...", "...")] + // [DebuggerNonUserCode] + // [ExcludeFromCodeCoverage] + // [EditorBrowsable(EditorBrowsableState.Never)] + // [Obsolete("This method is not intended to be called directly by user code")] + // [return: ComputeRoot32BitConstants(42)] + // public readonly void LoadDispatchData(in TDataLoader dataLoader, GraphicsDevice device, int x, int y, int z) + // where TDataLoader : struct, IDispatchDataLoader + // { + // + // } + // } + var structDeclarationSyntax = + StructDeclaration(structName).WithModifiers(structModifiers) + .AddBaseListTypes(SimpleBaseType( + GenericName(Identifier("IShader")) + .AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchData")) + .AddAttributeLists(attributes) + .AddAttributeLists(AttributeList(SingletonSeparatedList( + Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", ""))) + .AddArgumentListArguments(AttributeArgument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(root32BitConstantsCount)))))) + .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword)))) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("dataLoader")) + .AddModifiers(Token(SyntaxKind.InKeyword)) + .WithType(IdentifierName("TDataLoader")), + Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")), + Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .AddConstraintClauses( + TypeParameterConstraintClause(IdentifierName("TDataLoader")) + .AddConstraints( + ClassOrStructConstraint(SyntaxKind.StructConstraint), + TypeConstraint(IdentifierName("IDispatchDataLoader")))) + .WithBody(Block(blockStatements))); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (var parentType in structDeclaration.Ancestors().OfType()) + { + typeDeclarationSyntax = parentType + .WithMembers(SingletonList(typeDeclarationSyntax)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithAttributeLists(List()) + .WithoutTrivia(); + } // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: // // using System; + // using System.CodeDom.Compiler; // using System.ComponentModel; + // using System.Diagnostics; + // using System.Diagnostics.CodeAnalysis; + // using System.Runtime.CompilerServices; + // using ComputeSharp.__Internals; // - // namespace ComputeSharp.__Internals + // #pragma warning disable + // + // namespace // { - // internal static partial class DispatchDataLoader - // { - // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] - // [System.Obsolete("This method is not intended to be called directly by user code")] - // [return: ComputeRoot32BitConstants(42)] - // public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) - // { - // ... - // } - // } + // // } var source = CompilationUnit().AddUsings( UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.CodeDom.Compiler")), UsingDirective(IdentifierName("System.ComponentModel")), - UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers( - NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( - ClassDeclaration("DispatchDataLoader").AddModifiers( - Token(SyntaxKind.InternalKeyword), - Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("LoadDispatchData")).AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be called directly by user code")))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", ""))) - .AddArgumentListArguments(AttributeArgument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(root32BitConstantsCount)))))) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword)))).AddModifiers( - Token(SyntaxKind.PublicKeyword), - Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( - Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")), - Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType), - Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))), - Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .WithBody(block))) + UsingDirective(IdentifierName("System.Diagnostics")), + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), + UsingDirective(IdentifierName("System.Runtime.CompilerServices")), + UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace() .ToFullString(); - // Clear the attribute list to avoid duplicates - attributes = Array.Empty(); - // Add the method source attribute context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); } @@ -160,6 +202,39 @@ namespace ComputeSharp.SourceGenerators resourceOffset = 0, rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); + // Append the statements for the dispatch ranges: + // + // span0[0] = (uint)x; + // span0[1] = (uint)y; + // span0[2] = (uint)z; + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); + + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); + + if (isComputeShader) + { + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); + } + + // Append the statements to load all fields (both resources and other captured values) AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, statements); // After all the captured fields have been processed, ansure the reported byte size for @@ -167,9 +242,6 @@ namespace ComputeSharp.SourceGenerators // enable loading all the dispatch data after reinterpreting it to a sequence of values // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int)); - - statements.Add(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)))); - count = rawDataOffset / sizeof(int); // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. @@ -187,6 +259,87 @@ namespace ComputeSharp.SourceGenerators context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); } + // Span span0 = stackalloc uint[]; + statements.Insert(0, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(count))))))))))); + + // ref uint r0 = ref span0[0]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // dataLoader.LoadCapturedValues(span0); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("dataLoader"), + IdentifierName("LoadCapturedValues"))) + .AddArgumentListArguments(Argument(IdentifierName("span0"))))); + + if (resourceOffset > 0) + { + // Span span1 = stackalloc ulong[]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset))))))))))); + + // ref ulong r1 = ref span1[0]; + statements.Insert(3, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // dataLoader.LoadCapturedResources(span1); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("dataLoader"), + IdentifierName("LoadCapturedResources"))) + .AddArgumentListArguments(Argument(IdentifierName("span1"))))); + } + return statements; } @@ -224,8 +377,8 @@ namespace ComputeSharp.SourceGenerators statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"), - ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")))); + ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"), + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldSymbol.Name}, device)")))); } else if (HlslKnownTypes.IsKnownHlslType(typeName)) { @@ -261,14 +414,14 @@ namespace ComputeSharp.SourceGenerators rowTypeName = $"ComputeSharp.{elementName}{columns}", rowLocalName = $"__{string.Join("_", fieldPath)}__row0"; - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in shader.{string.Join(".", fieldPath)}));")); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));")); // Generate the loading code for each individual row, with proper alignment. // This will result in the following (assuming Float2x3 m): // - // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in shader.m)); - // Unsafe.As(ref Unsafe.Add(ref r1, rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0); - // Unsafe.As(ref Unsafe.Add(ref r1, rawDataOffset + 16)) = Unsafe.Add(ref __m__row0, 1); + // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in m)); + // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0); + // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1); for (int j = 0; j < rows; j++) { rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); @@ -276,7 +429,7 @@ namespace ComputeSharp.SourceGenerators statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.Add(ref r1, {rawDataOffset}))"), + ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})")))); rawDataOffset += fieldPack * columns; @@ -296,8 +449,8 @@ namespace ComputeSharp.SourceGenerators statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.Add(ref r1, {rawDataOffset}))"), - ParseExpression($"shader.{string.Join(".", fieldPath)}")))); + ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), + ParseExpression($"{string.Join(".", fieldPath)}")))); rawDataOffset += fieldSize; } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index 20500ae1..d8d1abeb 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -91,7 +91,7 @@ namespace ComputeSharp.SourceGenerators // [ExcludeFromCodeCoverage] // [EditorBrowsable(EditorBrowsableState.Never)] // [Obsolete("This method is not intended to be called directly by user code")] - // public int GetDispatchId() + // public readonly int GetDispatchId() // { // // } From b386c237420d431de6d30398e2c23c2950b8f117 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Jul 2021 15:43:44 +0200 Subject: [PATCH 06/37] Switched library code to use new data loader pattern --- .../Backend/SwapChainApplication{T}.cs | 5 +- .../PixelShaderDispatchDataLoader.cs | 61 ++++++++++++ .../Shaders/Interop/ReflectionServices.cs | 13 ++- src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 22 +---- .../Translation/Models/CachedShader{T}.cs | 5 +- .../Translation/Models/DispatchData.cs | 87 ----------------- .../ShaderLoader{T}.DispatchData.cs | 97 ------------------- .../Shaders/Translation/ShaderLoader{T}.cs | 16 +-- 8 files changed, 89 insertions(+), 217 deletions(-) create mode 100644 src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs index 26f4f0cf..c6c501f3 100644 --- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs +++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs @@ -1,12 +1,15 @@ using System; +using ComputeSharp.__Internals; using ComputeSharp.Interop; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.SwapChain.Backend { internal sealed class SwapChainApplication : Win32Application - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader { /// /// The instance used to create shaders to run. diff --git a/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs new file mode 100644 index 00000000..43fa5455 --- /dev/null +++ b/src/ComputeSharp/Shaders/Dispatching/PixelShaderDispatchDataLoader.cs @@ -0,0 +1,61 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.__Internals; +using TerraFX.Interop; +using System.Runtime.InteropServices; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Shaders.Dispatching +{ + /// + /// A data loader for pixel shaders. + /// + internal readonly unsafe struct PixelShaderDispatchDataLoader : IDispatchDataLoader + { + /// + /// The object in use. + /// + private readonly ID3D12GraphicsCommandList* d3D12GraphicsCommandList; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal PixelShaderDispatchDataLoader(ID3D12GraphicsCommandList* d3D12GraphicsCommandList) + { + this.d3D12GraphicsCommandList = d3D12GraphicsCommandList; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void LoadCapturedValues(ReadOnlySpan data) + { + this.d3D12GraphicsCommandList->SetComputeRoot32BitConstants(data); + } + + /// + public void LoadCapturedResources(ReadOnlySpan data) + { + ID3D12GraphicsCommandList* d3D12GraphicsCommandList = this.d3D12GraphicsCommandList; + ref ulong resourcesRef = ref MemoryMarshal.GetReference(data); + ref D3D12_GPU_DESCRIPTOR_HANDLE startRef = ref Unsafe.As(ref resourcesRef); + ref D3D12_GPU_DESCRIPTOR_HANDLE endRef = ref Unsafe.Add(ref startRef, data.Length); + uint offset = 2; + + // Skip the first target resource, as that is loaded explicitly by the shader runner using the + // target texture passed in by the user, which is not actually captured by the shader itself. + // The target root descriptor table index is therefore 2 in this case, as it needs to skip not + // only the this implicit texture to draw on, but also the constant buffer with capture values. + while (Unsafe.IsAddressLessThan(ref startRef, ref endRef)) + { + d3D12GraphicsCommandList->SetComputeRootDescriptorTable(offset, startRef); + + startRef = ref Unsafe.Add(ref startRef, 1); + offset++; + } + } + } +} diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs index 3a83b4f0..cdc099c0 100644 --- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs @@ -1,11 +1,14 @@ using System; using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Core.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.Interop { /// @@ -28,7 +31,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static void GetShaderInfo(out ShaderInfo shaderInfo) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { GetNonGenericShaderInfo(default(T), out shaderInfo); } @@ -45,7 +48,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { GetNonGenericShaderInfo(in shader, out shaderInfo); } @@ -66,7 +69,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static void GetShaderInfo(out ShaderInfo shaderInfo) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { GetNonGenericShaderInfo(default(T), out shaderInfo); @@ -85,7 +88,7 @@ namespace ComputeSharp.Interop /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. /// public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader where TPixel : unmanaged { GetNonGenericShaderInfo(in shader, out shaderInfo); @@ -98,7 +101,7 @@ namespace ComputeSharp.Interop /// The input shader to retrieve info for. /// The resulting instance. private static unsafe void GetNonGenericShaderInfo(in T shader, out ShaderInfo shaderInfo) - where T : struct + where T : struct, IShader { ShaderLoader shaderLoader = ShaderLoader.Load(in shader); diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index a9cee52b..99bbd3aa 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Commands; -using ComputeSharp.Graphics.Extensions; using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; @@ -189,13 +188,12 @@ namespace ComputeSharp.Shaders // Create the shader key ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, 1); - CachedShader shaderData; PipelineData? pipelineData; lock (ShadersCache) { // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out shaderData)) + if (!ShadersCache.TryGetValue(key, out CachedShader shaderData)) { LoadShader(threadsX, threadsY, 1, in shader, out shaderData); @@ -216,29 +214,15 @@ namespace ComputeSharp.Shaders commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState); - // Extract the dispatch data for the shader invocation - using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, 1); + ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); - // Initialize the loop targets and the captured values - commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables); + shader.LoadDispatchData(in dataLoader, device, x, y, 1); // Load the implicit output texture commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable( 1, ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(device)); - // Skip the last (missing) resource, as the internal counter is exceeding the number of explicit - // resources that the shader has actually captured (since it includes the target texture too). - // For the same reason, the target root descriptor table index is also offset by 2, as it needs - // to skip not only the constant buffer with capture values, but the implicit texture as well. - ReadOnlySpan resources = dispatchData.Resources[..^1]; - - for (int i = 0; i < resources.Length; i++) - { - // Load the captured buffers - commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 2, resources[i]); - } - // Dispatch and wait for completion commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1); commandList.ExecuteAndWaitForCompletion(); diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs index 39558fb1..8a616cb5 100644 --- a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs @@ -1,7 +1,10 @@ using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Graphics.Commands; using ComputeSharp.Shaders.Translation.Interop; +#pragma warning disable CS0618 + namespace ComputeSharp.Shaders.Translation.Models { /// @@ -9,7 +12,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// The type of compute shader in use. internal readonly struct CachedShader - where T : struct + where T : struct, IShader { /// /// The instance with the shader metadata. diff --git a/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs deleted file mode 100644 index 249a3279..00000000 --- a/src/ComputeSharp/Shaders/Translation/Models/DispatchData.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Buffers; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using TerraFX.Interop; - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains all the captured data to dispatch a shader. - /// - internal readonly ref struct DispatchData - { - /// - /// The array (actually values) with the captured buffers. - /// - private readonly ulong[] resourcesArray; - - /// - /// The number of values in . - /// - private readonly int resourcesCount; - - /// - /// The array with all the captured variables, with proper padding. - /// - private readonly byte[] variablesArray; - - /// - /// The actual size in bytes to use from . - /// - private readonly int variablesByteSize; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The array with the captured buffers. - /// The number of instances in . - /// The array with all the captured variables, with proper padding. - /// The actual size in bytes to use from . - public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) - { - this.resourcesArray = resourcesArray; - this.variablesArray = variablesArray; - this.resourcesCount = resourcesCount; - this.variablesByteSize = variablesByteSize; - } - - /// - /// Gets a with all the captured buffers. - /// - public ReadOnlySpan Resources - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); - ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); - - return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); - } - } - - /// - /// Gets a with the padded data representing all the captured variables. - /// - public unsafe ReadOnlySpan Variables - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); - ref uint r1 = ref Unsafe.As(ref r0); - int length = (int)((uint)this.variablesByteSize / sizeof(uint)); - - return MemoryMarshal.CreateReadOnlySpan(ref r1, length); - } - } - - /// - public void Dispose() - { - ArrayPool.Shared.Return(this.resourcesArray); - ArrayPool.Shared.Return(this.variablesArray); - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs deleted file mode 100644 index 95c80c19..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Translation.Models; -using TerraFX.Interop; - -#pragma warning disable CS0419, CS0618 - -namespace ComputeSharp.Shaders.Translation -{ - /// - internal sealed partial class ShaderLoader - { - /// - /// A that loads all the captured members from a shader instance. - /// - /// The to use to run the shader. - /// The shader instance to load the data from. - /// - /// A reference to the buffer with all the captured instances. - /// This is just represented as a reference, to avoid exposing the type publicly. - /// - /// A reference to the buffer to use to store all the captured value types. - /// The returned value indicates the total number of written bytes into . - private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1); - - /// - /// The number of captured graphics resources (buffers). - /// - private int totalResourceCount; - - /// - /// The cached instance to load dispatch data before execution. - /// - private DispatchDataLoader? dispatchDataLoader; - - /// - /// The of instances mapping the captured variables in the current shader. - /// - private readonly List capturedFields = new(); - - /// - /// Gets a new instance with all the captured data for the current shader instance. - /// - /// The to use to run the shader. - /// The input instance representing the compute shader to run. - /// The number of iterations to run on the X axis. - /// The number of iterations to run on the Y axis. - /// The number of iterations to run on the Z axis. - [Pure] - public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z) - { - // Resources and variables buffers - ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(256); - - ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); - ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); - - // Set the x, y and (optionally) z counters - Unsafe.As(ref r1) = x; - Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; - - if (IsComputeShader) - { - Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; - } - - // Invoke the dynamic method to extract the captured data - int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1); - - return new(resources, this.totalResourceCount, variables, totalVariablesByteSize); - } - - /// - /// Initializes the instance that loads the dispatch data for the current shader type. - /// - private void InitializeDispatchDataLoader() - { - // Get the generated data loader - Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() }; - Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!; - MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!; - - // Extract the computed count of 32 bit root constants to load - D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)method.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; - - // Create a delegate from the generated shader data loader - this.dispatchDataLoader = method.CreateDelegate(); - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index a13586e1..39434980 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -19,13 +19,18 @@ namespace ComputeSharp.Shaders.Translation /// /// The type of compute shader currently in use. internal sealed partial class ShaderLoader : IShaderLoader - where T : struct + where T : struct, IShader { /// /// The associated instance for the current shader type. /// private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); + /// + /// The of instances mapping the captured variables in the current shader. + /// + private readonly List capturedFields = new(); + /// /// The number of constant buffers to define in the shader. /// @@ -151,8 +156,6 @@ namespace ComputeSharp.Shaders.Translation // the input shader once to avoid allocating it multiple times while processing the shader. @this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader); - @this.InitializeDispatchDataLoader(); - return @this; } @@ -173,6 +176,9 @@ namespace ComputeSharp.Shaders.Translation { this.definesInfo.Add(pair.Key, pair.Value); } + + // Extract the computed count of 32 bit root constants to load + D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)typeof(T).GetMethod(nameof(IShader.LoadDispatchData))!.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; } /// @@ -200,7 +206,6 @@ namespace ComputeSharp.Shaders.Translation (string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value; this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - this.totalResourceCount++; break; } @@ -251,7 +256,6 @@ namespace ComputeSharp.Shaders.Translation this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); - this.totalResourceCount++; } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { @@ -259,7 +263,6 @@ namespace ComputeSharp.Shaders.Translation this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); - this.totalResourceCount++; } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { @@ -267,7 +270,6 @@ namespace ComputeSharp.Shaders.Translation this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - this.totalResourceCount++; } else if (fieldInfo.GetValue(shader) is Delegate func) { From 2d200db5ba18b3a63067c1082e3480cf86fa8528 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Jul 2021 16:39:06 +0200 Subject: [PATCH 07/37] Fixed unit test build errors --- .../IComputeShaderHashCodeGenerator.cs | 2 +- .../Helpers/DebugDispatchDataLoader.cs | 56 ++++ .../ShaderDataLoaderTests.cs | 283 ++++++++++-------- .../ShaderHashCodeTests.cs | 21 +- tests/ComputeSharp.Tests/ShadersTests.cs | 11 +- 5 files changed, 235 insertions(+), 138 deletions(-) create mode 100644 tests/ComputeSharp.Tests.Internals/Helpers/DebugDispatchDataLoader.cs diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index d8d1abeb..ff0663f9 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -202,7 +202,7 @@ namespace ComputeSharp.SourceGenerators .AddArgumentListArguments(Argument( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("foo"), + IdentifierName(fieldSymbol.Name), IdentifierName("Method")))))); } diff --git a/tests/ComputeSharp.Tests.Internals/Helpers/DebugDispatchDataLoader.cs b/tests/ComputeSharp.Tests.Internals/Helpers/DebugDispatchDataLoader.cs new file mode 100644 index 00000000..60d1ded4 --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals/Helpers/DebugDispatchDataLoader.cs @@ -0,0 +1,56 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Tests.Internals.Helpers +{ + /// + /// A debug data loader for generic shaders. + /// + internal readonly unsafe struct DebugDispatchDataLoader : IDispatchDataLoader + { + /// + /// The backing, mutable data for and . + /// + private readonly StrongBox<(uint[] Values, ulong[] Resources)> data; + + /// + /// Gets the captured values. + /// + public uint[] Values => this.data.Value.Values; + + /// + /// Gets the captured resources. + /// + public ulong[] Resources => this.data.Value.Resources; + + /// + /// Creates a new instance. + /// + /// A new instance to use. + [Pure] + public static DebugDispatchDataLoader Create() + { + DebugDispatchDataLoader @this = default; + + Unsafe.AsRef(in @this.data) = new StrongBox<(uint[], ulong[])>((Array.Empty(), Array.Empty())); + + return @this; + } + + /// + public void LoadCapturedValues(ReadOnlySpan data) + { + this.data.Value.Values = data.ToArray(); + } + + /// + public void LoadCapturedResources(ReadOnlySpan data) + { + this.data.Value.Resources = data.ToArray(); + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs index f6b11808..830e5ba9 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs @@ -1,4 +1,4 @@ -using ComputeSharp.__Internals; +using ComputeSharp.Tests.Internals.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; #pragma warning disable CS0618 @@ -22,16 +22,19 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void CapturedResource() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new CapturedResourceShader(buffer), ref *p0, ref *p1); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - Assert.AreEqual(12, size); + new CapturedResourceShader(buffer).LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(3, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); + + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); } [AutoConstructor] @@ -51,22 +54,24 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadMultipleResourcesAndPrimitives() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer0 = Gpu.Default.AllocateReadWriteBuffer(16); using ReadWriteBuffer buffer1 = Gpu.Default.AllocateReadWriteBuffer(16); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77), ref *p0, ref *p1); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - Assert.AreEqual(24, size); + new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77).LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(p0[0], buffer0.D3D12GpuDescriptorHandle.ptr); - Assert.AreEqual(p0[1], buffer1.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(6, dataLoader.Values.Length); + Assert.AreEqual(2, dataLoader.Resources.Length); - Assert.AreEqual(1, *(int*)&p1[12]); - Assert.AreEqual(22, *(int*)&p1[16]); - Assert.AreEqual(77, *(int*)&p1[20]); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); + Assert.AreEqual(1, (int)dataLoader.Values[3]); + Assert.AreEqual(22, (int)dataLoader.Values[4]); + Assert.AreEqual(77, (int)dataLoader.Values[5]); + Assert.AreEqual(buffer0.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + Assert.AreEqual(buffer1.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[1]); } [AutoConstructor] @@ -88,28 +93,36 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadScalarAndVectorTypes() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); ScalarAndVectorTypesShader shader = new(buffer, new(55, 44, 888), 22, 77, new(3.14, 6.28), 42, 9999); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(72, size); + Assert.AreEqual(18, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(55, *(float*)&p1[16]); - Assert.AreEqual(44, *(float*)&p1[20]); - Assert.AreEqual(888, *(float*)&p1[24]); - Assert.AreEqual(22, *(int*)&p1[28]); - Assert.AreEqual(77, *(int*)&p1[32]); - Assert.AreEqual(3.14, *(double*)&p1[48]); - Assert.AreEqual(6.28, *(double*)&p1[56]); - Assert.AreEqual(42, *(int*)&p1[64]); - Assert.AreEqual(9999, *(int*)&p1[68]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(55, *(float*)&p1[16]); + Assert.AreEqual(44, *(float*)&p1[20]); + Assert.AreEqual(888, *(float*)&p1[24]); + Assert.AreEqual(22, *(int*)&p1[28]); + Assert.AreEqual(77, *(int*)&p1[32]); + Assert.AreEqual(3.14, *(double*)&p1[48]); + Assert.AreEqual(6.28, *(double*)&p1[56]); + Assert.AreEqual(42, *(int*)&p1[64]); + Assert.AreEqual(9999, *(int*)&p1[68]); + } } [AutoConstructor] @@ -133,11 +146,9 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadScalarVectorAndMatrixTypes() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); ScalarVectorAndMatrixTypesShader shader = new( buffer, f2x3: new(55, 44, 888, 111, 222, 333), @@ -149,32 +160,42 @@ namespace ComputeSharp.Tests.Internals i2x2: new(11, 22, 33, 44), d: 9999); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(124, size); + Assert.AreEqual(31, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(55, *(float*)&p1[16]); - Assert.AreEqual(44, *(float*)&p1[20]); - Assert.AreEqual(888, *(float*)&p1[24]); - Assert.AreEqual(111, *(float*)&p1[32]); - Assert.AreEqual(222, *(float*)&p1[36]); - Assert.AreEqual(333, *(float*)&p1[40]); - Assert.AreEqual(22, *(int*)&p1[44]); - Assert.AreEqual(1, *(int*)&p1[48]); - Assert.AreEqual(2, *(int*)&p1[52]); - Assert.AreEqual(3, *(int*)&p1[56]); - Assert.AreEqual(3.14, *(double*)&p1[64]); - Assert.AreEqual(6.28, *(double*)&p1[72]); - Assert.AreEqual(42, *(int*)&p1[80]); - Assert.AreEqual(111, *(int*)&p1[84]); - Assert.AreEqual(222, *(int*)&p1[88]); - Assert.AreEqual(11, *(int*)&p1[96]); - Assert.AreEqual(22, *(int*)&p1[100]); - Assert.AreEqual(33, *(int*)&p1[112]); - Assert.AreEqual(44, *(int*)&p1[116]); - Assert.AreEqual(9999, *(int*)&p1[120]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(55, *(float*)&p1[16]); + Assert.AreEqual(44, *(float*)&p1[20]); + Assert.AreEqual(888, *(float*)&p1[24]); + Assert.AreEqual(111, *(float*)&p1[32]); + Assert.AreEqual(222, *(float*)&p1[36]); + Assert.AreEqual(333, *(float*)&p1[40]); + Assert.AreEqual(22, *(int*)&p1[44]); + Assert.AreEqual(1, *(int*)&p1[48]); + Assert.AreEqual(2, *(int*)&p1[52]); + Assert.AreEqual(3, *(int*)&p1[56]); + Assert.AreEqual(3.14, *(double*)&p1[64]); + Assert.AreEqual(6.28, *(double*)&p1[72]); + Assert.AreEqual(42, *(int*)&p1[80]); + Assert.AreEqual(111, *(int*)&p1[84]); + Assert.AreEqual(222, *(int*)&p1[88]); + Assert.AreEqual(11, *(int*)&p1[96]); + Assert.AreEqual(22, *(int*)&p1[100]); + Assert.AreEqual(33, *(int*)&p1[112]); + Assert.AreEqual(44, *(int*)&p1[116]); + Assert.AreEqual(9999, *(int*)&p1[120]); + } } [AutoConstructor] @@ -204,11 +225,9 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadFlatCustomTypeShader() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); FlatCustomTypeShader shader = new( buffer, new SimpleTypes( @@ -221,32 +240,42 @@ namespace ComputeSharp.Tests.Internals i2x2: new(11, 22, 33, 44), d: 9999)); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(124, size); + Assert.AreEqual(31, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(55, *(float*)&p1[16]); - Assert.AreEqual(44, *(float*)&p1[20]); - Assert.AreEqual(888, *(float*)&p1[24]); - Assert.AreEqual(111, *(float*)&p1[32]); - Assert.AreEqual(222, *(float*)&p1[36]); - Assert.AreEqual(333, *(float*)&p1[40]); - Assert.AreEqual(22, *(int*)&p1[44]); - Assert.AreEqual(1, *(int*)&p1[48]); - Assert.AreEqual(2, *(int*)&p1[52]); - Assert.AreEqual(3, *(int*)&p1[56]); - Assert.AreEqual(3.14, *(double*)&p1[64]); - Assert.AreEqual(6.28, *(double*)&p1[72]); - Assert.AreEqual(42, *(int*)&p1[80]); - Assert.AreEqual(111, *(int*)&p1[84]); - Assert.AreEqual(222, *(int*)&p1[88]); - Assert.AreEqual(11, *(int*)&p1[96]); - Assert.AreEqual(22, *(int*)&p1[100]); - Assert.AreEqual(33, *(int*)&p1[112]); - Assert.AreEqual(44, *(int*)&p1[116]); - Assert.AreEqual(9999, *(int*)&p1[120]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(55, *(float*)&p1[16]); + Assert.AreEqual(44, *(float*)&p1[20]); + Assert.AreEqual(888, *(float*)&p1[24]); + Assert.AreEqual(111, *(float*)&p1[32]); + Assert.AreEqual(222, *(float*)&p1[36]); + Assert.AreEqual(333, *(float*)&p1[40]); + Assert.AreEqual(22, *(int*)&p1[44]); + Assert.AreEqual(1, *(int*)&p1[48]); + Assert.AreEqual(2, *(int*)&p1[52]); + Assert.AreEqual(3, *(int*)&p1[56]); + Assert.AreEqual(3.14, *(double*)&p1[64]); + Assert.AreEqual(6.28, *(double*)&p1[72]); + Assert.AreEqual(42, *(int*)&p1[80]); + Assert.AreEqual(111, *(int*)&p1[84]); + Assert.AreEqual(222, *(int*)&p1[88]); + Assert.AreEqual(11, *(int*)&p1[96]); + Assert.AreEqual(22, *(int*)&p1[100]); + Assert.AreEqual(33, *(int*)&p1[112]); + Assert.AreEqual(44, *(int*)&p1[116]); + Assert.AreEqual(9999, *(int*)&p1[120]); + } } [AutoConstructor] @@ -288,11 +317,9 @@ namespace ComputeSharp.Tests.Internals [TestMethod] public unsafe void LoadNestedCustomTypes() { - ulong* p0 = stackalloc ulong[128]; - byte* p1 = stackalloc byte[256]; - using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(16); + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); NestedCustomTypesShader shader = new( buffer, new CustomType1( @@ -317,45 +344,55 @@ namespace ComputeSharp.Tests.Internals a: 888888, b: new(333.3f, 444.4f)))); - int size = DispatchDataLoader.LoadDispatchData(Gpu.Default, in shader, ref *p0, ref *p1); + shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); - Assert.AreEqual(188, size); + Assert.AreEqual(47, dataLoader.Values.Length); + Assert.AreEqual(1, dataLoader.Resources.Length); - Assert.AreEqual(p0[0], buffer.D3D12GpuDescriptorHandle.ptr); + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); - Assert.AreEqual(3.14f, *(float*)&p1[16]); - Assert.AreEqual(6.28f, *(float*)&p1[20]); - Assert.AreEqual(123.4f, *(float*)&p1[24]); - Assert.AreEqual(55, *(float*)&p1[32]); - Assert.AreEqual(44, *(float*)&p1[36]); - Assert.AreEqual(888, *(float*)&p1[40]); - Assert.AreEqual(111, *(float*)&p1[48]); - Assert.AreEqual(222, *(float*)&p1[52]); - Assert.AreEqual(333, *(float*)&p1[56]); - Assert.AreEqual(22, *(int*)&p1[60]); - Assert.AreEqual(1, *(int*)&p1[64]); - Assert.AreEqual(2, *(int*)&p1[68]); - Assert.AreEqual(3, *(int*)&p1[72]); - Assert.AreEqual(3.14, *(double*)&p1[80]); - Assert.AreEqual(6.28, *(double*)&p1[88]); - Assert.AreEqual(42, *(int*)&p1[96]); - Assert.AreEqual(111, *(int*)&p1[100]); - Assert.AreEqual(222, *(int*)&p1[104]); - Assert.AreEqual(11, *(int*)&p1[112]); - Assert.AreEqual(22, *(int*)&p1[116]); - Assert.AreEqual(33, *(int*)&p1[128]); - Assert.AreEqual(44, *(int*)&p1[132]); - Assert.AreEqual(9999, *(int*)&p1[136]); - Assert.AreEqual(42, *(int*)&p1[140]); - Assert.AreEqual(1234567, *(int*)&p1[144]); - Assert.AreEqual(44.4f, *(float*)&p1[148]); - Assert.AreEqual(55.5f, *(float*)&p1[152]); - Assert.AreEqual(7654321, *(int*)&p1[160]); - Assert.AreEqual(111.1f, *(float*)&p1[164]); - Assert.AreEqual(222.2f, *(float*)&p1[168]); - Assert.AreEqual(888888, *(int*)&p1[176]); - Assert.AreEqual(333.3f, *(float*)&p1[180]); - Assert.AreEqual(444.4f, *(float*)&p1[184]); + Assert.AreEqual(buffer.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + + fixed (void* p0 = &dataLoader.Values[0]) + { + byte* p1 = (byte*)p0; + + Assert.AreEqual(3.14f, *(float*)&p1[16]); + Assert.AreEqual(6.28f, *(float*)&p1[20]); + Assert.AreEqual(123.4f, *(float*)&p1[24]); + Assert.AreEqual(55, *(float*)&p1[32]); + Assert.AreEqual(44, *(float*)&p1[36]); + Assert.AreEqual(888, *(float*)&p1[40]); + Assert.AreEqual(111, *(float*)&p1[48]); + Assert.AreEqual(222, *(float*)&p1[52]); + Assert.AreEqual(333, *(float*)&p1[56]); + Assert.AreEqual(22, *(int*)&p1[60]); + Assert.AreEqual(1, *(int*)&p1[64]); + Assert.AreEqual(2, *(int*)&p1[68]); + Assert.AreEqual(3, *(int*)&p1[72]); + Assert.AreEqual(3.14, *(double*)&p1[80]); + Assert.AreEqual(6.28, *(double*)&p1[88]); + Assert.AreEqual(42, *(int*)&p1[96]); + Assert.AreEqual(111, *(int*)&p1[100]); + Assert.AreEqual(222, *(int*)&p1[104]); + Assert.AreEqual(11, *(int*)&p1[112]); + Assert.AreEqual(22, *(int*)&p1[116]); + Assert.AreEqual(33, *(int*)&p1[128]); + Assert.AreEqual(44, *(int*)&p1[132]); + Assert.AreEqual(9999, *(int*)&p1[136]); + Assert.AreEqual(42, *(int*)&p1[140]); + Assert.AreEqual(1234567, *(int*)&p1[144]); + Assert.AreEqual(44.4f, *(float*)&p1[148]); + Assert.AreEqual(55.5f, *(float*)&p1[152]); + Assert.AreEqual(7654321, *(int*)&p1[160]); + Assert.AreEqual(111.1f, *(float*)&p1[164]); + Assert.AreEqual(222.2f, *(float*)&p1[168]); + Assert.AreEqual(888888, *(int*)&p1[176]); + Assert.AreEqual(333.3f, *(float*)&p1[180]); + Assert.AreEqual(444.4f, *(float*)&p1[184]); + } } } } diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs index 241ce61b..5d8b7d59 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -1,14 +1,15 @@ using System; -using ComputeSharp.Shaders.Translation; using Microsoft.VisualStudio.TestTools.UnitTesting; +#pragma warning disable CS0618 + namespace ComputeSharp.Tests.Internals { [TestClass] [TestCategory("ShaderHashCode")] - public class ShaderHashCodeTests + public partial class ShaderHashCodeTests { - public struct Shader1 : IComputeShader + public partial struct Shader1 : IComputeShader { public float A; public ReadWriteBuffer B; @@ -28,19 +29,19 @@ namespace ComputeSharp.Tests.Internals Shader1 shader1 = new() { A = value, B = buffer }; int - hash1 = ShaderHashCodeProvider.GetHashCode(shader1), - hash2 = ShaderHashCodeProvider.GetHashCode(shader1); + hash1 = shader1.GetDispatchId(), + hash2 = shader1.GetDispatchId(); Assert.IsTrue(hash1 == hash2); Shader1 shader2 = new() { A = value, B = buffer }; - int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); + int hash3 = shader2.GetDispatchId(); Assert.IsTrue(hash1 == hash3); } - public struct Shader2 : IComputeShader + public partial struct Shader2 : IComputeShader { public float A; public ReadWriteBuffer B; @@ -62,8 +63,8 @@ namespace ComputeSharp.Tests.Internals Shader2 shader1 = new() { A = 1, B = buffer, F = f }; int - hash1 = ShaderHashCodeProvider.GetHashCode(shader1), - hash2 = ShaderHashCodeProvider.GetHashCode(shader1); + hash1 = shader1.GetDispatchId(), + hash2 = shader1.GetDispatchId(); Assert.IsTrue(hash1 == hash2); @@ -71,7 +72,7 @@ namespace ComputeSharp.Tests.Internals Shader2 shader2 = new() { A = 1, B = buffer, F = f }; - int hash3 = ShaderHashCodeProvider.GetHashCode(shader2); + int hash3 = shader2.GetDispatchId(); Assert.IsFalse(hash1 == hash3); } diff --git a/tests/ComputeSharp.Tests/ShadersTests.cs b/tests/ComputeSharp.Tests/ShadersTests.cs index f8bad618..8f9862ee 100644 --- a/tests/ComputeSharp.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.Tests/ShadersTests.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; +using ComputeSharp.__Internals; using ComputeSharp.SwapChain.Shaders; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; @@ -10,6 +11,8 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; +#pragma warning disable CS0618 + namespace ComputeSharp.Tests { [TestClass] @@ -137,7 +140,7 @@ namespace ComputeSharp.Tests if (shaderType.IsAssignableTo(typeof(IComputeShader))) { static void RunComputeShader(ReadWriteTexture2D texture) - where T : struct, IComputeShader + where T : struct, IComputeShader, IShader { texture.GraphicsDevice.For(texture.Width, texture.Height, (T)Activator.CreateInstance(typeof(T), texture, 0f)!); } @@ -149,7 +152,7 @@ namespace ComputeSharp.Tests else { static void RunPixelShader(ReadWriteTexture2D texture) - where T : struct, IPixelShader + where T : struct, IPixelShader, IShader { texture.GraphicsDevice.ForEach(texture, (T)Activator.CreateInstance(typeof(T), 0f)!); } @@ -188,8 +191,8 @@ namespace ComputeSharp.Tests Func, TCompute> computeFactory, Func, TPixel> pixelFactory, float delta) - where TCompute : struct, IComputeShader - where TPixel : struct, IPixelShader + where TCompute : struct, IComputeShader, IShader + where TPixel : struct, IPixelShader, IShader { _ = device.Get(); From 43f32ced28fa78e1bb67a2b46f5c431dc2d5572e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Jul 2021 17:14:36 +0200 Subject: [PATCH 08/37] Fixed build error with ambiguous field names --- .../IComputeShaderDataLoaderGenerator.cs | 16 ++++-- .../ShaderDataLoaderTests.cs | 49 +++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 1445d993..998d1dba 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -362,7 +362,15 @@ namespace ComputeSharp.SourceGenerators !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer select fieldSymbol) { - string typeName = fieldSymbol.Type.GetFullMetadataName(); + string + fieldName = fieldSymbol.Name, + typeName = fieldSymbol.Type.GetFullMetadataName(); + + // Disambiguates the name of target fields against the current input parameters + if (fieldName is "dataLoader" or "device" or "x" or "y" or "z") + { + fieldName = $"this.{fieldName}"; + } // The first item in each nested struct needs to be aligned to 16 bytes if (isFirstField && fieldPath.Count > 0) @@ -378,16 +386,16 @@ namespace ComputeSharp.SourceGenerators AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"), - ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldSymbol.Name}, device)")))); + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)")))); } else if (HlslKnownTypes.IsKnownHlslType(typeName)) { - AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldSymbol.Name }), typeName, ref rawDataOffset, statements); + AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements); } else if (fieldSymbol.Type.IsUnmanagedType) { // Custom struct type defined by the user - AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldSymbol.Name }).ToArray(), ref resourceOffset, ref rawDataOffset, statements); + AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, statements); } } } diff --git a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs index 830e5ba9..fa391b6c 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs @@ -394,5 +394,54 @@ namespace ComputeSharp.Tests.Internals Assert.AreEqual(444.4f, *(float*)&p1[184]); } } + + [AutoConstructor] + public partial struct AmbiguousNamesShader : IComputeShader + { + public ReadWriteBuffer a; + public ReadWriteBuffer b; + public ReadWriteBuffer c; + public ReadWriteBuffer x; + public ReadWriteBuffer y; + public ReadWriteBuffer z; + public int dataLoader; + public int device; + public int dummy; + + public void Execute() + { + } + } + + [TestMethod] + public unsafe void AmbiguousNames() + { + using ReadWriteBuffer a = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer b = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer c = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer x = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(16); + using ReadWriteBuffer z = Gpu.Default.AllocateReadWriteBuffer(16); + + DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); + + new AmbiguousNamesShader(a, b, c, x, y, z, 7777, 8888, 9999).LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + + Assert.AreEqual(6, dataLoader.Values.Length); + Assert.AreEqual(6, dataLoader.Resources.Length); + + Assert.AreEqual(111, (int)dataLoader.Values[0]); + Assert.AreEqual(222, (int)dataLoader.Values[1]); + Assert.AreEqual(333, (int)dataLoader.Values[2]); + Assert.AreEqual(7777, (int)dataLoader.Values[3]); + Assert.AreEqual(8888, (int)dataLoader.Values[4]); + Assert.AreEqual(9999, (int)dataLoader.Values[5]); + Assert.AreEqual(a.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[0]); + Assert.AreEqual(b.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[1]); + Assert.AreEqual(c.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[2]); + Assert.AreEqual(x.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[3]); + Assert.AreEqual(y.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[4]); + Assert.AreEqual(z.D3D12GpuDescriptorHandle.ptr, dataLoader.Resources[5]); + } } } From 6302cf005cd974774ab2126dd60b82e086911b04 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 8 Jul 2021 19:04:55 +0200 Subject: [PATCH 09/37] Fixed pixel shaders dispatch data loading --- src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 2 +- tests/ComputeSharp.Tests/ShadersTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 99bbd3aa..d2b29955 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -214,7 +214,7 @@ namespace ComputeSharp.Shaders commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState); - ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); + PixelShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); shader.LoadDispatchData(in dataLoader, device, x, y, 1); diff --git a/tests/ComputeSharp.Tests/ShadersTests.cs b/tests/ComputeSharp.Tests/ShadersTests.cs index 8f9862ee..1021eb9e 100644 --- a/tests/ComputeSharp.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.Tests/ShadersTests.cs @@ -115,7 +115,7 @@ namespace ComputeSharp.Tests shaderType, texture => new SwapChain.Shaders.Compute.ContouredLayers(texture, 0, background), texture => new ContouredLayers(0, background), - 0.0007f); + 0.000703f); } /// From e432a197a0080e4ad2232011f46751cc565d2494 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 9 Jul 2021 16:36:30 +0200 Subject: [PATCH 10/37] Added initial BuildHlslString source generator implementation Not actually working yet, pending other changes to pipeline creation --- .../IComputeShaderSourceGenerator.cs | 353 +++++++++++++++++- .../Mappings/HlslKnownTypes.cs | 31 ++ .../ShaderMethodSourceGenerator.cs | 5 +- .../Interfaces/__Internals/IShader{TSelf}.cs | 13 +- .../Shaders/Renderer/HlslShaderRenderer.cs | 168 +-------- .../__Internals/ArrayPoolStringBuilder.cs | 169 +++++++++ src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 18 +- .../Translation/Interop/IDxcBlobObject.cs | 4 +- .../Shaders/Translation/ShaderLoader{T}.cs | 9 - 9 files changed, 561 insertions(+), 209 deletions(-) create mode 100644 src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index e1d257a2..abc54d44 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; @@ -16,6 +17,7 @@ using Microsoft.CodeAnalysis.Text; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; #pragma warning disable CS0618 @@ -83,7 +85,7 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; - var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture"); + var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); @@ -92,6 +94,22 @@ namespace ComputeSharp.SourceGenerators var processedConstants = GetProcessedConstants(constantDefinitions); var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + GenerateRenderMethod( + context, + structDeclaration, + structDeclarationSymbol, + processedConstants, + staticFields, + processedTypes, + isComputeShader, + processedMembers, + implicitTextureType, + isSamplerUsed, + sharedBuffers, + forwardDeclarations, + processedMethods, + entryPoint); + // Create the compilation unit with the source attribute var source = CompilationUnit().AddUsings( @@ -99,16 +117,16 @@ namespace ComputeSharp.SourceGenerators AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))), - AttributeArgument(ArrayExpression(processedTypes)), - AttributeArgument(ArrayExpression(implicitTextureField)), - AttributeArgument(ArrayExpression(implicitSamplerField)), - AttributeArgument(NestedArrayExpression(processedMembers)), - AttributeArgument(ArrayExpression(forwardDeclarations)), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), - AttributeArgument(ArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants)), - AttributeArgument(NestedArrayExpression(staticFields)), - AttributeArgument(NestedArrayExpression(sharedBuffers))))) + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(""))), // TODO + AttributeArgument(ArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO + AttributeArgument(NestedArrayExpression(Array.Empty()))))) // TODO .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -127,7 +145,7 @@ namespace ComputeSharp.SourceGenerators /// Indicates whether or not represents a compute shader. /// A sequence of captured fields in . [Pure] - private static IEnumerable> GetProcessedFields( + private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, ICollection types, @@ -176,7 +194,8 @@ namespace ComputeSharp.SourceGenerators continue; } - else if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + else if (typeSymbol.IsUnmanagedType && + !HlslKnownTypes.IsKnownHlslType(metadataName)) { // Track the type if it's a custom struct types.Add(typeSymbol); @@ -187,7 +206,7 @@ namespace ComputeSharp.SourceGenerators _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); // Yield back the current mapping for the name (if the name used a reserved keyword) - yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; + yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName); } // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource @@ -208,7 +227,7 @@ namespace ComputeSharp.SourceGenerators /// The collection of discovered constant definitions. /// A sequence of static constant fields in . [Pure] - private static IEnumerable> GetStaticFields( + private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( GeneratorExecutionContext context, SemanticModelProvider semanticModel, StructDeclarationSyntax structDeclaration, @@ -256,7 +275,7 @@ namespace ComputeSharp.SourceGenerators string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString(); - yield return new[] { mapping ?? fieldSymbol.Name, typeDeclaration, assignment }; + yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); } } } @@ -295,7 +314,7 @@ namespace ComputeSharp.SourceGenerators continue; } - + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); @@ -414,14 +433,14 @@ namespace ComputeSharp.SourceGenerators /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. [Pure] - internal static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) + internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) { foreach (var constant in constantDefinitions) { var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - yield return new string[] { constantName, constant.Value }; + yield return (constantName, constant.Value); } } @@ -475,6 +494,300 @@ namespace ComputeSharp.SourceGenerators context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); } } + + private static void GenerateRenderMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + IEnumerable<(string Name, string Value)> definedConstants, + IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + IEnumerable declaredTypes, + bool isComputeShader, + IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, + string? implicitTextureType, + bool isSamplerUsed, + IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, + IEnumerable? forwardDeclarations, + IEnumerable processedMethods, + string executeMethod) + { + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; + IEnumerable bodyStatements = GenerateRenderMethodBody( + definedConstants, + staticFields, + declaredTypes, + isComputeShader, + instanceFields, + implicitTextureType, + isSamplerUsed, + sharedBuffers, + forwardDeclarations, + processedMethods, + executeMethod); + + // Create the partial shader type declaration with the hashcode interface method implementation. + // This code produces a struct declaration as follows: + // + // public struct ShaderType : IShader + // { + // [GeneratedCode("...", "...")] + // [DebuggerNonUserCode] + // [ExcludeFromCodeCoverage] + // [EditorBrowsable(EditorBrowsableState.Never)] + // [Obsolete("This method is not intended to be called directly by user code")] + // public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + // } + var structDeclarationSyntax = + StructDeclaration(structName).WithModifiers(structModifiers) + .AddBaseListTypes(SimpleBaseType( + GenericName(Identifier("IShader")) + .AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("BuildHlslString")) + .AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code"))))))) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(bodyStatements))); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (var parentType in structDeclaration.Ancestors().OfType()) + { + typeDeclarationSyntax = parentType + .WithMembers(SingletonList(typeDeclarationSyntax)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithAttributeLists(List()) + .WithoutTrivia(); + } + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.CodeDom.Compiler; + // using System.ComponentModel; + // using System.Diagnostics; + // using System.Diagnostics.CodeAnalysis; + // using ComputeSharp.__Internals; + // + // #pragma warning disable + // + // namespace + // { + // + // } + var source = + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.CodeDom.Compiler")), + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Diagnostics")), + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), + UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) + .NormalizeWhitespace() + .ToFullString(); + + // Add the method source attribute + context.AddSource("PREVIEW" + structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + + private static IEnumerable GenerateRenderMethodBody( + IEnumerable<(string Name, string Value)> definedConstants, + IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + IEnumerable declaredTypes, + bool isComputeShader, + IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, + string? implicitTextureType, + bool isSamplerUsed, + IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, + IEnumerable? forwardDeclarations, + IEnumerable processedMethods, + string executeMethod) + { + // Header + yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); + yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");"); + yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); + yield return ParseStatement("builder.AppendLine(\"// This shader was created by ComputeSharp.\");"); + yield return ParseStatement("builder.AppendLine(\"// See: https://github.com/Sergio0694/ComputeSharp.\");"); + + // Group size constants + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_X \");"); + yield return ParseStatement("builder.AppendLine(threadsX.ToString());"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Y \");"); + yield return ParseStatement("builder.AppendLine(threadsY.ToString());"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Z \");"); + yield return ParseStatement("builder.AppendLine(threadsZ.ToString());"); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + yield return ParseStatement($"builder.AppendLine(\"#define {name} {value}\");"); + } + + // Static fields + if (staticFields.Any()) + { + yield return ParseStatement("builder.AppendLine();"); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name} = {assignment};\");"); + } + else + { + yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name};\");"); + } + } + } + + // Declared types + foreach (var type in declaredTypes) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{type}\");"); + } + + // Captured variables + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"cbuffer _ : register(b0)\");"); + yield return ParseStatement("builder.AppendLine('{');"); + yield return ParseStatement("builder.AppendLine(\" uint __x;\");"); + yield return ParseStatement("builder.AppendLine(\" uint __y;\");"); + + if (isComputeShader) + { + yield return ParseStatement("builder.AppendLine(\" uint __z;\");"); + } + + // User-defined values + foreach (var instanceField in instanceFields) + { + if (instanceField.Symbol.Type.IsUnmanagedType) + { + yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName};\");"); + } + } + + yield return ParseStatement("builder.AppendLine('}');"); + + int + constantBuffersCount = 0, + readOnlyBuffersCount = 0, + readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});\");"); + } + + // Optional sampler field + if (isSamplerUsed) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"SamplerState __sampler : register(s);\");"); + } + + // Resources + foreach (var instanceField in instanceFields) + { + string metadataName = instanceField.Symbol.GetFullMetadataName(); + + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"cbuffer _{instanceField.HlslName} : register(b{constantBuffersCount++})\");"); + yield return ParseStatement("builder.AppendLine('{');"); + yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName}[2];\");"); + yield return ParseStatement("builder.AppendLine('}');"); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(t{readOnlyBuffersCount++});\");"); + } + else if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(u{readWriteBuffersCount++});\");"); + } + } + + // Shared buffers + foreach (var sharedBuffer in sharedBuffers) + { + object count = (object?)sharedBuffer.Count ?? "threadsX * threadsY * threadsZ"; + + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"groupshared {sharedBuffer.Type} {sharedBuffer.Name} [{count}];\");"); + } + + // Forward declarations + if (forwardDeclarations is not null) + { + foreach (var forwardDeclaration in forwardDeclarations) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{forwardDeclaration}\");"); + } + } + + // Captured methods + if (processedMethods is not null) + { + foreach (var method in processedMethods) + { + yield return ParseStatement("builder.AppendLine();"); + yield return + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(method))))); + } + } + + // Entry point + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]\");"); + yield return + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(executeMethod))))); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 1c7a0751..468a1e56 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -101,6 +101,16 @@ namespace ComputeSharp.SourceGenerators.Mappings return knownTypes; } + /// + /// Checks whether or not a given type name matches a constant buffer type. + /// + /// The input type name to check. + /// Whether or not represents a constant buffer type. + public static bool IsConstantBufferType(string typeName) + { + return typeName == "ComputeSharp.ConstantBuffer`1"; + } + /// /// Checks whether or not a given type name matches a structured buffer type. /// @@ -118,6 +128,27 @@ namespace ComputeSharp.SourceGenerators.Mappings }; } + /// + /// Checks whether or not a given type name matches a readonly typed resource type. + /// + /// The input type name to check. + /// Whether or not represents a readonly typed resource type. + public static bool IsReadOnlyTypedResourceType(string typeName) + { + switch (typeName) + { + case "ComputeSharp.ReadOnlyBuffer`1": + case "ComputeSharp.ReadOnlyTexture2D`1": + case "ComputeSharp.ReadOnlyTexture2D`2": + case "ComputeSharp.ReadOnlyTexture3D`1": + case "ComputeSharp.ReadOnlyTexture3D`2": + case "ComputeSharp.IReadOnlyTexture2D`1": + case "ComputeSharp.IReadOnlyTexture3D`1": + return true; + default: return false; + }; + } + /// /// Checks whether or not a given type name matches a typed resource type. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7ea87bdf..a9f4f412 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; @@ -83,7 +84,7 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), AttributeArgument(ArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants))))) + AttributeArgument(NestedArrayExpression(Array.Empty()))))) // TODO .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs index d3389bf0..b81e424c 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs @@ -17,7 +17,7 @@ namespace ComputeSharp.__Internals /// /// The unique dispatch identifier for the shader. [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This interface is not intended to be used directly by user code")] + [Obsolete("This method is not intended to be used directly by user code")] int GetDispatchId(); /// @@ -33,5 +33,16 @@ namespace ComputeSharp.__Internals [Obsolete("This method is not intended to be called directly by user code")] void LoadDispatchData(in TDataLoader dataLoader, GraphicsDevice device, int x, int y, int z) where TDataLoader : struct, IDispatchDataLoader; + + /// + /// Builds the HLSL source code for the current shader instance. + /// + /// The target instance to write the HLSL source to. + /// 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. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ); } } diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs index 754709ee..b0d797c3 100644 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs @@ -1,8 +1,5 @@ -using System; -using System.Buffers; -using System.Diagnostics; -using System.Diagnostics.Contracts; -using System.Runtime.CompilerServices; +using System.Diagnostics.Contracts; +using ComputeSharp.__Internals; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; @@ -191,166 +188,5 @@ namespace ComputeSharp.Shaders.Renderer return builder; } - - /// - /// A helper type that implements a pooled buffer writer for values. - /// - [DebuggerTypeProxy(typeof(DebugView))] - public ref struct ArrayPoolStringBuilder - { - /// - /// The underlying array. - /// - private char[] array; - - /// - /// The starting offset within . - /// - private int index; - - /// - /// Creates a new instance ready to use. - /// - /// A new instance with default values. - [Pure] - public static ArrayPoolStringBuilder Create() - { - ArrayPoolStringBuilder builder; - - builder.array = ArrayPool.Shared.Rent(1024); - builder.index = 0; - - return builder; - } - - /// - public ReadOnlySpan WrittenSpan - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => new(this.array, 0, this.index); - } - - /// - /// Appends the input sequence of characters to the current buffer. - /// - /// The input characters to write. - public void Append(string value) - { - EnsureCapacity(value.Length); - - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); - - this.index += value.Length; - } - - /// - /// Appends a character to the current buffer. - /// - public void Append(char character) - { - EnsureCapacity(1); - - this.array[this.index++] = character; - } - - /// - /// Appends the input sequence of characters to the current buffer, with a trailing new line. - /// - /// The input characters to write. - public void AppendLine(string value) - { - EnsureCapacity(value.Length + 1); - - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); - - this.index += value.Length; - - this.array[this.index++] = '\n'; - } - - /// - /// Appends a character and a new line to the current buffer. - /// - public void AppendLine(char character) - { - EnsureCapacity(2); - - this.array[this.index++] = character; - this.array[this.index++] = '\n'; - } - - /// - /// Appends a new line to the current buffer. - /// - public void AppendLine() - { - EnsureCapacity(1); - - this.array[this.index++] = '\n'; - } - - /// - /// Ensures that has enough free space to contain a given number of new items. - /// - /// The minimum number of items to ensure space for in . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EnsureCapacity(int requestedSize) - { - if (requestedSize > this.array.Length - this.index) - { - ResizeBuffer(requestedSize); - } - } - - /// - /// Resizes to ensure it can fit the specified number of new items. - /// - /// The minimum number of items to ensure space for in . - [MethodImpl(MethodImplOptions.NoInlining)] - private void ResizeBuffer(int sizeHint) - { - int minimumSize = this.index + sizeHint; - - // Rent a new array with the specified size, and copy as many items from the current array - // as possible to the new array. This mirrors the behavior of the Array.Resize API from - // the BCL: if the new size is greater than the length of the current array, copy all the - // items from the original array into the new one. Otherwise, copy as many items as possible, - // until the new array is completely filled, and ignore the remaining items in the first array. - char[] newArray = ArrayPool.Shared.Rent(minimumSize); - int itemsToCopy = Math.Min(this.array.Length, minimumSize); - - Array.Copy(this.array, 0, newArray, 0, itemsToCopy); - - ArrayPool.Shared.Return(array); - - this.array = newArray; - } - - /// - public void Dispose() - { - ArrayPool.Shared.Return(this.array); - } - - /// - /// A debug proxy used for displaying debug info. - /// - internal sealed class DebugView - { - /// - /// Initializes a new instance of the class with the specified parameters. - /// - /// The input instance to display. - public DebugView(ArrayPoolStringBuilder builder) - { - Text = builder.WrittenSpan.ToString(); - } - - /// - /// Gets the text to display for the current instance. - /// - public string Text { get; } - } - } } } diff --git a/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs new file mode 100644 index 00000000..a7922b49 --- /dev/null +++ b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs @@ -0,0 +1,169 @@ +using System; +using System.Buffers; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.__Internals +{ + /// + /// A helper type that implements a pooled buffer writer for values. + /// + [DebuggerTypeProxy(typeof(DebugView))] + public ref struct ArrayPoolStringBuilder + { + /// + /// The underlying array. + /// + private char[] array; + + /// + /// The starting offset within . + /// + private int index; + + /// + /// Creates a new instance ready to use. + /// + /// A new instance with default values. + [Pure] + public static ArrayPoolStringBuilder Create() + { + ArrayPoolStringBuilder builder; + + builder.array = ArrayPool.Shared.Rent(1024); + builder.index = 0; + + return builder; + } + + /// + public ReadOnlySpan WrittenSpan + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new(this.array, 0, this.index); + } + + /// + /// Appends the input sequence of characters to the current buffer. + /// + /// The input characters to write. + public void Append(string value) + { + EnsureCapacity(value.Length); + + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); + + this.index += value.Length; + } + + /// + /// Appends a character to the current buffer. + /// + public void Append(char character) + { + EnsureCapacity(1); + + this.array[this.index++] = character; + } + + /// + /// Appends the input sequence of characters to the current buffer, with a trailing new line. + /// + /// The input characters to write. + public void AppendLine(string value) + { + EnsureCapacity(value.Length + 1); + + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); + + this.index += value.Length; + + this.array[this.index++] = '\n'; + } + + /// + /// Appends a character and a new line to the current buffer. + /// + public void AppendLine(char character) + { + EnsureCapacity(2); + + this.array[this.index++] = character; + this.array[this.index++] = '\n'; + } + + /// + /// Appends a new line to the current buffer. + /// + public void AppendLine() + { + EnsureCapacity(1); + + this.array[this.index++] = '\n'; + } + + /// + /// Ensures that has enough free space to contain a given number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnsureCapacity(int requestedSize) + { + if (requestedSize > this.array.Length - this.index) + { + ResizeBuffer(requestedSize); + } + } + + /// + /// Resizes to ensure it can fit the specified number of new items. + /// + /// The minimum number of items to ensure space for in . + [MethodImpl(MethodImplOptions.NoInlining)] + private void ResizeBuffer(int sizeHint) + { + int minimumSize = this.index + sizeHint; + + // Rent a new array with the specified size, and copy as many items from the current array + // as possible to the new array. This mirrors the behavior of the Array.Resize API from + // the BCL: if the new size is greater than the length of the current array, copy all the + // items from the original array into the new one. Otherwise, copy as many items as possible, + // until the new array is completely filled, and ignore the remaining items in the first array. + char[] newArray = ArrayPool.Shared.Rent(minimumSize); + int itemsToCopy = Math.Min(this.array.Length, minimumSize); + + Array.Copy(this.array, 0, newArray, 0, itemsToCopy); + + ArrayPool.Shared.Return(array); + + this.array = newArray; + } + + /// + public void Dispose() + { + ArrayPool.Shared.Return(this.array); + } + + /// + /// A debug proxy used for displaying debug info. + /// + internal sealed class DebugView + { + /// + /// Initializes a new instance of the class with the specified parameters. + /// + /// The input instance to display. + public DebugView(ArrayPoolStringBuilder builder) + { + Text = builder.WrittenSpan.ToString(); + } + + /// + /// Gets the text to display for the current instance. + /// + public string Text { get; } + } + } +} diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index d2b29955..511d5ea0 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -237,19 +237,19 @@ namespace ComputeSharp.Shaders /// The input instance representing the compute shader to run. /// The instance to return with the cached shader data. [MethodImpl(MethodImplOptions.NoInlining)] - private static void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) + private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) { - // Load the input shader - ShaderLoader shaderLoader = ShaderLoader.Load(in shader); + ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(); - // Render the loaded shader - using var shaderSource = HlslShaderRenderer.Render(threadsX, threadsY, threadsZ, shaderLoader); + shader.BuildHlslString(ref builder, threadsX, threadsY, threadsZ); - // Compile the loaded shader to HLSL bytecode - IDxcBlobObject shaderBytecode = new(ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan)); + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan); - // Get the cached shader data - shaderData = new CachedShader(shaderLoader, shaderBytecode); + builder.Dispose(); + + IDxcBlobObject shaderBytecode = new(dxcBlobBytecode.Get()); + + shaderData = new CachedShader(null!, shaderBytecode); // TODO } /// diff --git a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs b/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs index eb3cd02e..9f7e9135 100644 --- a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs +++ b/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs @@ -17,9 +17,9 @@ namespace ComputeSharp.Shaders.Translation.Interop /// Creates a new instance with the specified parameters. /// /// The instance to wrap. - public IDxcBlobObject(ComPtr dxcBlob) + public IDxcBlobObject(IDxcBlob* dxcBlob) { - this.dxcBlob = dxcBlob; + this.dxcBlob = new ComPtr(dxcBlob); } /// diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index 39434980..51af97ba 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -26,11 +26,6 @@ namespace ComputeSharp.Shaders.Translation /// private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); - /// - /// The of instances mapping the captured variables in the current shader. - /// - private readonly List capturedFields = new(); - /// /// The number of constant buffers to define in the shader. /// @@ -254,21 +249,18 @@ namespace ComputeSharp.Shaders.Translation { d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount)); - this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount)); - this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); } else if (fieldInfo.GetValue(shader) is Delegate func) @@ -289,7 +281,6 @@ namespace ComputeSharp.Shaders.Translation } else { - this.capturedFields.Add(fieldInfo); this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName)); } } From fdb0f691a2fe6296ea1e6d3de3258bc79f466ef4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 12:37:31 +0200 Subject: [PATCH 11/37] Added interface APIs to load shader metadata --- .../IComputeShaderDataLoaderGenerator.cs | 16 +++--- .../__Internals/IDispatchMetadataLoader.cs | 23 ++++++++ .../Interfaces/__Internals/IShader{TSelf}.cs | 15 +++++- .../Interop/__Internals/ResourceDescriptor.cs | 54 +++++++++++++++++++ src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 4 +- 5 files changed, 100 insertions(+), 12 deletions(-) create mode 100644 src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs create mode 100644 src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 998d1dba..12bd1543 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -98,7 +98,7 @@ namespace ComputeSharp.SourceGenerators // [EditorBrowsable(EditorBrowsableState.Never)] // [Obsolete("This method is not intended to be called directly by user code")] // [return: ComputeRoot32BitConstants(42)] - // public readonly void LoadDispatchData(in TDataLoader dataLoader, GraphicsDevice device, int x, int y, int z) + // public readonly void LoadDispatchData(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z) // where TDataLoader : struct, IDispatchDataLoader // { // @@ -122,8 +122,8 @@ namespace ComputeSharp.SourceGenerators .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) .AddParameterListParameters( - Parameter(Identifier("dataLoader")) - .AddModifiers(Token(SyntaxKind.InKeyword)) + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) .WithType(IdentifierName("TDataLoader")), Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")), Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), @@ -288,13 +288,13 @@ namespace ComputeSharp.SourceGenerators SyntaxKind.NumericLiteralExpression, Literal(0)))))))))); - // dataLoader.LoadCapturedValues(span0); + // loader.LoadCapturedValues(span0); statements.Add( ExpressionStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("dataLoader"), + IdentifierName("loader"), IdentifierName("LoadCapturedValues"))) .AddArgumentListArguments(Argument(IdentifierName("span0"))))); @@ -329,13 +329,13 @@ namespace ComputeSharp.SourceGenerators SyntaxKind.NumericLiteralExpression, Literal(0)))))))))); - // dataLoader.LoadCapturedResources(span1); + // loader.LoadCapturedResources(span1); statements.Add( ExpressionStatement( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("dataLoader"), + IdentifierName("loader"), IdentifierName("LoadCapturedResources"))) .AddArgumentListArguments(Argument(IdentifierName("span1"))))); } @@ -367,7 +367,7 @@ namespace ComputeSharp.SourceGenerators typeName = fieldSymbol.Type.GetFullMetadataName(); // Disambiguates the name of target fields against the current input parameters - if (fieldName is "dataLoader" or "device" or "x" or "y" or "z") + if (fieldName is "loader" or "device" or "x" or "y" or "z") { fieldName = $"this.{fieldName}"; } diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs new file mode 100644 index 00000000..9095e60e --- /dev/null +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs @@ -0,0 +1,23 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// A base representing a metadatadata loader for a shader being dispatched. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public interface IDispatchMetadataLoader + { + /// + /// Loads an opaque metadata handle from the given shader metadata. + /// + /// The serialized metadata for the current shader. + /// The sequence of resource descriptors for the current shader. + /// The resulting opaque metadata handle. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result); + } +} diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs index b81e424c..e2bfda10 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs @@ -24,16 +24,27 @@ namespace ComputeSharp.__Internals /// Loads the dispatch data for the shader. /// /// The type of data loader being used. - /// The instance to use to load the data. + /// The instance to use to load the data. /// The device the shader is being dispatched on. /// The number of iterations to run on the X axis. /// The number of iterations to run on the Y axis. /// The number of iterations to run on the Z axis. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] - void LoadDispatchData(in TDataLoader dataLoader, GraphicsDevice device, int x, int y, int z) + void LoadDispatchData(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z) where TDataLoader : struct, IDispatchDataLoader; + /// + /// Loads an opaque metadata handle from the metadata of the current shader. + /// + /// The type of data loader being used. + /// The instance to use to load the data. + /// The resulting opaque metadata handle. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + void LoadDispatchMetadata(ref TMetadataLoader loader, out IntPtr result) + where TMetadataLoader : struct, IDispatchMetadataLoader; + /// /// Builds the HLSL source code for the current shader instance. /// diff --git a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs new file mode 100644 index 00000000..e97fe2ab --- /dev/null +++ b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs @@ -0,0 +1,54 @@ +using System; +using System.ComponentModel; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; +using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_FLAGS; + +#pragma warning disable IDE0052 + +namespace ComputeSharp.__Internals +{ + /// + /// An opaque type describing a captured resource to be used in a shader. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This interface is not intended to be used directly by user code")] + public struct ResourceDescriptor + { + /// + private D3D12_DESCRIPTOR_RANGE_TYPE RangeType; + + /// + private uint NumDescriptors; + + /// + private uint BaseShaderRegister; + + /// + private uint RegisterSpace; + + /// + private D3D12_DESCRIPTOR_RANGE_FLAGS Flags; + + /// + private uint OffsetInDescriptorsFromTableStart; + + /// + /// Initializes a new instance. + /// + /// The type of resource to create the descriptor for. + /// The offset in the resource from the start of the shader mapping. + /// The resulting instance. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + public static void Create(int type, uint offset, out ResourceDescriptor descriptor) + { + descriptor.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)type; + descriptor.NumDescriptors = 1; + descriptor.BaseShaderRegister = offset; + descriptor.RegisterSpace = 0; + descriptor.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE; + descriptor.OffsetInDescriptorsFromTableStart = FX.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + } + } +} diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 511d5ea0..5651350e 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -157,7 +157,7 @@ namespace ComputeSharp.Shaders ComputeShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); - shader.LoadDispatchData(in dataLoader, device, x, y, z); + shader.LoadDispatchData(ref dataLoader, device, x, y, z); commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, (uint)groupsZ); commandList.ExecuteAndWaitForCompletion(); @@ -216,7 +216,7 @@ namespace ComputeSharp.Shaders PixelShaderDispatchDataLoader dataLoader = new(commandList.D3D12GraphicsCommandList); - shader.LoadDispatchData(in dataLoader, device, x, y, 1); + shader.LoadDispatchData(ref dataLoader, device, x, y, 1); // Load the implicit output texture commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable( From a364c676b08ceb52e49f7b4745e6f25f62860600 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 13:13:03 +0200 Subject: [PATCH 12/37] Added ShaderDispatchMetadataLoader type --- .../ShaderDispatchMetadataLoader.cs | 46 +++++++++++++++++++ src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 10 ++-- 2 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs new file mode 100644 index 00000000..77bedbe8 --- /dev/null +++ b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.Shaders.Extensions; +using ComputeSharp.__Internals; +using Microsoft.Toolkit.Diagnostics; +using TerraFX.Interop; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Shaders.Dispatching +{ + /// + /// A data loader for compute shaders. + /// + internal readonly unsafe struct ShaderDispatchMetadataLoader : IDispatchMetadataLoader + { + /// + /// The object in use. + /// + private readonly ID3D12Device* d3D12Device; + + /// + /// Creates a new instance. + /// + /// The object to use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal ShaderDispatchMetadataLoader(ID3D12Device* d3D12Device) + { + this.d3D12Device = d3D12Device; + } + + /// + public void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result) + { + Guard.HasSizeEqualTo(serializedMetadata, 5, nameof(serializedMetadata)); + + using ComPtr d3D12RootSignature = this.d3D12Device->CreateRootSignature( + MemoryMarshal.Read(serializedMetadata), + MemoryMarshal.Cast(resourceDescriptors), + MemoryMarshal.Read(serializedMetadata[4..])); + + result = *(IntPtr*)&d3D12RootSignature; + } + } +} diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 5651350e..5293e0f4 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Commands; +using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Extensions; -using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; using ComputeSharp.Shaders.Translation.Interop; using ComputeSharp.Shaders.Translation.Models; @@ -12,7 +12,6 @@ using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; -using ComputeSharp.Shaders.Dispatching; #pragma warning disable CS0618 @@ -261,7 +260,12 @@ namespace ComputeSharp.Shaders [MethodImpl(MethodImplOptions.NoInlining)] private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) { - using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1, shaderData.Loader.IsStaticSamplerUsed); + using ComPtr d3D12RootSignature = default; + + ShaderDispatchMetadataLoader metadataLoader = new(device.D3D12Device); + + default(T).LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature); + using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode); pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); From b096c70d23d9e43d0562ff39b905e465c7d80ecf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 13:21:20 +0200 Subject: [PATCH 13/37] Removed IDxcBlobObject type, code refactoring --- .../Interop/__Internals/ResourceDescriptor.cs | 2 +- src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 21 ++++----- .../Translation/Interop/IDxcBlobObject.cs | 38 ---------------- .../Translation/Models/CachedShader.cs | 45 +++++++++++++++++++ .../Translation/Models/CachedShader{T}.cs | 44 ------------------ 5 files changed, 55 insertions(+), 95 deletions(-) delete mode 100644 src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs create mode 100644 src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs diff --git a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs index e97fe2ab..6b2d9422 100644 --- a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs +++ b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs @@ -4,7 +4,7 @@ using TerraFX.Interop; using FX = TerraFX.Interop.Windows; using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_FLAGS; -#pragma warning disable IDE0052 +#pragma warning disable IDE0052, CS0414 namespace ComputeSharp.__Internals { diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 5293e0f4..15a0c699 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -5,7 +5,6 @@ using ComputeSharp.Graphics.Commands; using ComputeSharp.Shaders.Dispatching; using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Translation; -using ComputeSharp.Shaders.Translation.Interop; using ComputeSharp.Shaders.Translation.Models; using ComputeSharp.__Internals; using Microsoft.Toolkit.Diagnostics; @@ -27,7 +26,7 @@ namespace ComputeSharp.Shaders /// /// The mapping used to cache and reuse compiled shaders. /// - private static readonly Dictionary> ShadersCache = new(); + private static readonly Dictionary ShadersCache = new(); /// /// Compiles and runs the input shader on a target instance, with the specified parameters. @@ -134,7 +133,7 @@ namespace ComputeSharp.Shaders lock (ShadersCache) { // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out CachedShader shaderData)) + if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData)) { LoadShader(threadsX, threadsY, threadsZ, in shader, out shaderData); @@ -192,7 +191,7 @@ namespace ComputeSharp.Shaders lock (ShadersCache) { // Get or preload the shader - if (!ShadersCache.TryGetValue(key, out CachedShader shaderData)) + if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData)) { LoadShader(threadsX, threadsY, 1, in shader, out shaderData); @@ -234,9 +233,9 @@ namespace ComputeSharp.Shaders /// 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. - /// The instance to return with the cached shader data. + /// The instance to return with the cached shader data. [MethodImpl(MethodImplOptions.NoInlining)] - private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) + private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) { ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(); @@ -246,19 +245,17 @@ namespace ComputeSharp.Shaders builder.Dispose(); - IDxcBlobObject shaderBytecode = new(dxcBlobBytecode.Get()); - - shaderData = new CachedShader(null!, shaderBytecode); // TODO + shaderData = new CachedShader(dxcBlobBytecode.Get()); } /// /// Creates and caches a instance for a given shader. /// /// The to use to run the shader. - /// The instance with the data on the loaded shader. + /// The instance with the data on the loaded shader. /// The resulting instance to use to run the shader. [MethodImpl(MethodImplOptions.NoInlining)] - private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) + private static unsafe void CreatePipelineData(GraphicsDevice device, CachedShader shaderData, out PipelineData pipelineData) { using ComPtr d3D12RootSignature = default; @@ -266,7 +263,7 @@ namespace ComputeSharp.Shaders default(T).LoadDispatchMetadata(ref metadataLoader, out *(IntPtr*)&d3D12RootSignature); - using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode); + using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.D3D12ShaderBytecode); pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); diff --git a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs b/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs deleted file mode 100644 index 9f7e9135..00000000 --- a/src/ComputeSharp/Shaders/Translation/Interop/IDxcBlobObject.cs +++ /dev/null @@ -1,38 +0,0 @@ -using ComputeSharp.Interop; -using TerraFX.Interop; - -namespace ComputeSharp.Shaders.Translation.Interop -{ - /// - /// An object wrapping an instance. - /// - internal sealed unsafe class IDxcBlobObject : NativeObject - { - /// - /// The instance currently in use. - /// - private ComPtr dxcBlob; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance to wrap. - public IDxcBlobObject(IDxcBlob* dxcBlob) - { - this.dxcBlob = new ComPtr(dxcBlob); - } - - /// - /// Gets a raw pointer to the instance in use. - /// - public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlob.Get()); - - /// - protected override bool OnDispose() - { - this.dxcBlob.Dispose(); - - return true; - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs new file mode 100644 index 00000000..8bf11804 --- /dev/null +++ b/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs @@ -0,0 +1,45 @@ +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Interop; +using TerraFX.Interop; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A class that contains info on a cached shader. + /// + internal sealed unsafe class CachedShader : NativeObject + { + /// + /// The instance currently in use. + /// + private ComPtr dxcBlobBytecode; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The bytecode instance to wrap. + public CachedShader(IDxcBlob* dxcBlobBytecode) + { + this.dxcBlobBytecode = new ComPtr(dxcBlobBytecode); + } + + /// + /// Gets the map of cached instances for each GPU in use. + /// + public ConditionalWeakTable CachedPipelines { get; } = new(); + + /// + /// Gets a raw pointer to the instance in use. + /// + public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlobBytecode.Get()); + + /// + protected override bool OnDispose() + { + this.dxcBlobBytecode.Dispose(); + + return true; + } + } +} diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs deleted file mode 100644 index 8a616cb5..00000000 --- a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Runtime.CompilerServices; -using ComputeSharp.__Internals; -using ComputeSharp.Graphics.Commands; -using ComputeSharp.Shaders.Translation.Interop; - -#pragma warning disable CS0618 - -namespace ComputeSharp.Shaders.Translation.Models -{ - /// - /// A that contains info on a cached shader. - /// - /// The type of compute shader in use. - internal readonly struct CachedShader - where T : struct, IShader - { - /// - /// The instance with the shader metadata. - /// - public readonly ShaderLoader Loader; - - /// - /// The compiled shader bytecode. - /// - public readonly IDxcBlobObject Bytecode; - - /// - /// The map of cached instances for each GPU in use. - /// - public readonly ConditionalWeakTable CachedPipelines; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance with the shader metadata. - /// The compiled shader bytecode. - public CachedShader(ShaderLoader loader, IDxcBlobObject bytecode) - { - Loader = loader; - Bytecode = bytecode; - CachedPipelines = new(); - } - } -} From d4eeac8c045cedecd08ccf063a303b6e2e1f6873 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 14:39:39 +0200 Subject: [PATCH 14/37] Added draft of new aggregate shader source generator type --- ...erGenerator.CreateBuildHlslStringMethod.cs | 622 ++++++++++++++++++ ...aderGenerator.CreateGetDispatchIdMethod.cs | 96 +++ ...rGenerator.CreateLoadDispatchDataMethod.cs | 342 ++++++++++ ...erator.CreateLoadDispatchMetadataMethod.cs | 28 + .../IShaderGenerator.SyntaxReceiver.cs | 49 ++ .../IShaderGenerator.cs | 214 ++++++ 6 files changed, 1351 insertions(+) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.cs diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs new file mode 100644 index 00000000..785c9def --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -0,0 +1,622 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; +using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.SyntaxRewriters; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out bool isSamplerUsed) + { + // Properties are not supported + DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); + + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // A given type can only represent a single shader type + if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) + { + context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); + } + + // Explore the syntax tree and extract the processed info + var semanticModel = new SemanticModelProvider(context.Compilation); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); + var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); + var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); + var (entryPoint, processedMethods, forwardDeclarations, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?); + var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); + var processedConstants = GetProcessedConstants(constantDefinitions); + var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; + IEnumerable bodyStatements = GenerateRenderMethodBody( + processedConstants, + staticFields, + processedTypes, + isComputeShader, + processedMembers, + implicitTextureType, + accessesStaticSampler, + sharedBuffers, + forwardDeclarations, + processedMethods, + entryPoint); + + isSamplerUsed = accessesStaticSampler; + + // This code produces a method declaration as follows: + // + // public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("BuildHlslString")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .WithBody(Block(bodyStatements)); + } + + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The current generator context in use. + /// The input instance to process. + /// The collection of currently discovered types. + /// Indicates whether or not represents a compute shader. + /// A sequence of captured fields in . + [Pure] + private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + ICollection types, + bool isComputeShader) + { + bool hlslResourceFound = false; + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (fieldSymbol.IsStatic) continue; + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + // Group shared fields must be static + if (attribute is not null) + { + context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); + } + + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + + // Allowed fields must be either resources, unmanaged values or delegates + if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + hlslResourceFound = true; + + // Track the type of items in the current buffer + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + { + types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + } + } + else if (!typeSymbol.IsUnmanagedType && + typeSymbol.TypeKind != TypeKind.Delegate) + { + // Shaders can only capture valid HLSL resource types or unmanaged types + context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); + + continue; + } + else if (typeSymbol.IsUnmanagedType && + !HlslKnownTypes.IsKnownHlslType(metadataName)) + { + // Track the type if it's a custom struct + types.Add(typeSymbol); + } + + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // Yield back the current mapping for the name (if the name used a reserved keyword) + yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName); + } + + // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource + if (!hlslResourceFound && isComputeShader) + { + context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); + } + } + + /// + /// Gets a sequence of shader static fields and their mapped names. + /// + /// The current generator context in use. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant fields in . + [Pure] + private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( + GeneratorExecutionContext context, + SemanticModelProvider semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + foreach (var fieldDeclaration in structDeclaration.Members.OfType()) + { + foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; + + if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is not null) continue; + + // Constant properties must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + { + context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + string typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + StaticFieldRewriter staticFieldRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + context); + + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString(); + + yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); + } + } + } + + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The current generator context in use. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured members in . + [Pure] + private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (!fieldSymbol.IsStatic) continue; + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + + if (attribute is null) continue; + + if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) + { + context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + if (!typeSymbol.ElementType.IsUnmanagedType) + { + context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; + + string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); + + types.Add((INamedTypeSymbol)typeSymbol.ElementType); + } + } + + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The current generator context in use. + /// The type symbol for the shader type. + /// The instance for the current type. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// Indicates whether or not represents a compute shader. + /// A sequence of processed methods in , and the entry point. + [Pure] + private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations, bool IsSamplerUser) GetProcessedMethods( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + bool isComputeShader) + { + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); + + string? entryPoint = null; + List methods = new(); + List declarations = new(); + bool isSamplerUsed = false; + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + (isComputeShader && + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0) || + (!isComputeShader && + methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0); + + // Create the source rewriter for the current method + ShaderSourceRewriter shaderSourceRewriter = new( + structDeclarationSymbol, + semanticModel, + discoveredTypes, + staticMethods, + constantDefinitions, + context, + isShaderEntryPoint); + + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; + + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) + { + methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); + declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace().ToFullString()); + } + + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) + { + processedMethod = isComputeShader switch + { + true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! + }; + + entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); + } + else + { + methods.Add(processedMethod.NormalizeWhitespace().ToFullString()); + declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace().ToFullString()); + } + } + + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) + { + methods.Add(staticMethod.NormalizeWhitespace().ToFullString()); + declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString()); + } + + return (entryPoint!, methods, declarations, isSamplerUsed); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) + { + foreach (var constant in constantDefinitions) + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + yield return (constantName, constant.Value); + } + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + internal static IEnumerable GetProcessedTypes(IEnumerable types) + { + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) + { + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + yield return + structDeclaration + .NormalizeWhitespace() + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString(); + } + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The current generator context in use. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); + } + } + + private static IEnumerable GenerateRenderMethodBody( + IEnumerable<(string Name, string Value)> definedConstants, + IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + IEnumerable declaredTypes, + bool isComputeShader, + IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, + string? implicitTextureType, + bool isSamplerUsed, + IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, + IEnumerable? forwardDeclarations, + IEnumerable processedMethods, + string executeMethod) + { + // Header + yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); + yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");"); + yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); + yield return ParseStatement("builder.AppendLine(\"// This shader was created by ComputeSharp.\");"); + yield return ParseStatement("builder.AppendLine(\"// See: https://github.com/Sergio0694/ComputeSharp.\");"); + + // Group size constants + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_X \");"); + yield return ParseStatement("builder.AppendLine(threadsX.ToString());"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Y \");"); + yield return ParseStatement("builder.AppendLine(threadsY.ToString());"); + yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Z \");"); + yield return ParseStatement("builder.AppendLine(threadsZ.ToString());"); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + yield return ParseStatement($"builder.AppendLine(\"#define {name} {value}\");"); + } + + // Static fields + if (staticFields.Any()) + { + yield return ParseStatement("builder.AppendLine();"); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name} = {assignment};\");"); + } + else + { + yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name};\");"); + } + } + } + + // Declared types + foreach (var type in declaredTypes) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{type}\");"); + } + + // Captured variables + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"cbuffer _ : register(b0)\");"); + yield return ParseStatement("builder.AppendLine('{');"); + yield return ParseStatement("builder.AppendLine(\" uint __x;\");"); + yield return ParseStatement("builder.AppendLine(\" uint __y;\");"); + + if (isComputeShader) + { + yield return ParseStatement("builder.AppendLine(\" uint __z;\");"); + } + + // User-defined values + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + if (fieldSymbol.Type.IsUnmanagedType) + { + yield return ParseStatement($"builder.AppendLine(\" {fieldType} {fieldName};\");"); + } + } + + yield return ParseStatement("builder.AppendLine('}');"); + + int + constantBuffersCount = 0, + readOnlyBuffersCount = 0, + readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});\");"); + } + + // Optional sampler field + if (isSamplerUsed) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"SamplerState __sampler : register(s);\");"); + } + + // Resources + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + string metadataName = fieldSymbol.GetFullMetadataName(); + + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"cbuffer _{fieldName} : register(b{constantBuffersCount++})\");"); + yield return ParseStatement("builder.AppendLine('{');"); + yield return ParseStatement($"builder.AppendLine(\" {fieldType} {fieldName}[2];\");"); + yield return ParseStatement("builder.AppendLine('}');"); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{fieldType} : register(t{readOnlyBuffersCount++});\");"); + } + else if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{fieldType} : register(u{readWriteBuffersCount++});\");"); + } + } + + // Shared buffers + foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + { + object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"groupshared {bufferType} {bufferName} [{count}];\");"); + } + + // Forward declarations + if (forwardDeclarations is not null) + { + foreach (var forwardDeclaration in forwardDeclarations) + { + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement($"builder.AppendLine(\"{forwardDeclaration}\");"); + } + } + + // Captured methods + if (processedMethods is not null) + { + foreach (var method in processedMethods) + { + yield return ParseStatement("builder.AppendLine();"); + yield return + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(method))))); + } + } + + // Entry point + yield return ParseStatement("builder.AppendLine();"); + yield return ParseStatement("builder.AppendLine(\"[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]\");"); + yield return + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(executeMethod))))); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs new file mode 100644 index 00000000..9f3e0235 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol) + { + // This code produces a method declaration as follows: + // + // public readonly int GetDispatchId() + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(structDeclarationSymbol)); + } + + /// + /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// + /// The input instance to process. + /// The instance to hash the input shader. + [Pure] + private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol) + { + var delegateFields = structDeclarationSymbol + .GetMembers() + .OfType() + .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) + .ToImmutableArray(); + + if (delegateFields.Length == 0) + { + // return 0; + return + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); + } + + List blockStatements = new(4); + + // HashCode hashCode = default; + blockStatements.Add(LocalDeclarationStatement( + VariableDeclaration(IdentifierName("HashCode")) + .AddVariables( + VariableDeclarator(Identifier("hashCode")) + .WithInitializer(EqualsValueClause( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword))))))); + + foreach (IFieldSymbol fieldSymbol in delegateFields) + { + // hashCode.Add(delegateField.Method); + blockStatements.Add(ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(fieldSymbol.Name), + IdentifierName("Method")))))); + } + + // return hashCode.ToHashCode(); + blockStatements.Add(ReturnStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("hashCode"), + IdentifierName("ToHashCode"))))); + + return Block(blockStatements); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs new file mode 100644 index 00000000..13ccee56 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + out IEnumerable discoveredResources, + out int root32BitConstantsCount) + { + // This code produces a method declaration as follows: + // + // public readonly void LoadDispatchData(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z) + // where TDataLoader : struct, IDispatchDataLoader + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchData")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TDataLoader")), + Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")), + Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) + .AddConstraintClauses( + TypeParameterConstraintClause(IdentifierName("TDataLoader")) + .AddConstraints( + ClassOrStructConstraint(SyntaxKind.StructConstraint), + TypeConstraint(IdentifierName("IDispatchDataLoader")))) + .WithBody(Block(GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount))); + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader + /// + /// The current generator context in use. + /// The input instance to process. + /// The sequence of discovered resources in the current shader type. + /// The total number of 32 bit root constants being loaded for the current shader type. + /// The sequence of instances to load shader dispatch data. + private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IEnumerable discoveredResources, out int root32BitConstantsCount) + { + List statements = new(); + List resources = new(); + + discoveredResources = resources; + + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + int + resourceOffset = 0, + rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); + + // Append the statements for the dispatch ranges: + // + // span0[0] = (uint)x; + // span0[1] = (uint)y; + // span0[2] = (uint)z; + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); + + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); + + if (isComputeShader) + { + statements.Add( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), + CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); + } + + // Append the statements to load all fields (both resources and other captured values) + AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, resources, statements); + + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to a multiple of a 32 bit value. This is necessary to + // enable loading all the dispatch data after reinterpreting it to a sequence of values + // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int)); + root32BitConstantsCount = rawDataOffset / sizeof(int); + + // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. + // Loaded values in the root signature have the following costs: + // - Root constants cost 1 DWORD each, since they are 32-bit values. + // - Descriptor tables cost 1 DWORD each. + // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. + // So here we check whether the current signature respects that constraint, + // and emit a build error otherwise. For more info on this, see the docs here: + // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. + int rootSignatureDwordSize = root32BitConstantsCount + resourceOffset; + + if (rootSignatureDwordSize > 64) + { + context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); + } + + // Span span0 = stackalloc uint[]; + statements.Insert(0, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); + + // ref uint r0 = ref span0[0]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // loader.LoadCapturedValues(span0); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedValues"))) + .AddArgumentListArguments(Argument(IdentifierName("span0"))))); + + if (resourceOffset > 0) + { + // Span span1 = stackalloc ulong[]; + statements.Insert(1, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset))))))))))); + + // ref ulong r1 = ref span1[0]; + statements.Insert(3, + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // loader.LoadCapturedResources(span1); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadCapturedResources"))) + .AddArgumentListArguments(Argument(IdentifierName("span1"))))); + } + + return statements; + } + + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The current type being explored. + /// The current path of the field with respect to the shader instance. + /// The current offset in the root table of loaded resources. + /// The current offset within the loaded data buffer. + /// The target list of resources in the current shader type. + /// The target list of statements being generated. + private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection resources, ICollection statements) + { + bool isFirstField = true; + + foreach ( + IFieldSymbol fieldSymbol in + from fieldSymbol in currentTypeSymbol.GetMembers().OfType() + where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && + !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer + select fieldSymbol) + { + string + fieldName = fieldSymbol.Name, + typeName = fieldSymbol.Type.GetFullMetadataName(); + + // Disambiguates the name of target fields against the current input parameters + if (fieldName is "loader" or "device" or "x" or "y" or "z") + { + fieldName = $"this.{fieldName}"; + } + + // The first item in each nested struct needs to be aligned to 16 bytes + if (isFirstField && fieldPath.Count > 0) + { + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + isFirstField = false; + } + + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + resources.Add(typeName); + + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"), + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)")))); + } + else if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements); + } + else if (fieldSymbol.Type.IsUnmanagedType) + { + // Custom struct type defined by the user + AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements); + } + } + } + + /// + /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix). + /// + /// The current path of the field with respect to the shader instance. + /// The type name currently being read. + /// The current offset within the loaded data buffer. + /// The target list of statements being generated. + private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection statements) + { + // For scalar, vector and linear matrix types, serialize the value normally. + // Only the initial alignment needs to be considered, while data is packed. + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); + + // Check if the current type is a matrix type with more than one row. In this + // case, each row is aligned as if it was a separate array, so the start of + // each row needs to be at a multiple of 16 bytes (a float4 register). + if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) + { + string + rowTypeName = $"ComputeSharp.{elementName}{columns}", + rowLocalName = $"__{string.Join("_", fieldPath)}__row0"; + + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));")); + + // Generate the loading code for each individual row, with proper alignment. + // This will result in the following (assuming Float2x3 m): + // + // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in m)); + // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0); + // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1); + for (int j = 0; j < rows; j++) + { + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), + ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})")))); + + rawDataOffset += fieldPack * columns; + } + } + else + { + // Calculate the right offset with 16-bytes padding (HLSL constant buffer). + // Since we're in a constant buffer, we need to both pad the starting offset + // to be aligned to the packing size of the type, and also to align the initial + // offset to ensure that values do not cross 16 bytes boundaries either. + rawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); + + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), + ParseExpression($"{string.Join(".", fieldPath)}")))); + + rawDataOffset += fieldSize; + } + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs new file mode 100644 index 00000000..7810b3f6 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + IEnumerable discoveredResources, + int root32BitConstantsCount, + bool isSamplerUsed) + { + return MethodDeclaration(IdentifierName("void"), "LoadDispatchMetadataMethod"); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs new file mode 100644 index 00000000..0f61834c --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ComputeSharp.SourceGenerators +{ + /// + public sealed partial class IShaderGenerator + { + /// + /// An that selects candidate nodes to process. + /// + private sealed class SyntaxReceiver : ISyntaxContextReceiver + { + /// + /// The list of info gathered during exploration. + /// + private readonly List gatheredInfo = new(); + + /// + /// Gets the collection of gathered info to process. + /// + public IReadOnlyCollection GatheredInfo => this.gatheredInfo; + + /// + public void OnVisitSyntaxNode(GeneratorSyntaxContext context) + { + if (context.Node is StructDeclarationSyntax structDeclaration && + context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && + structSymbol.Interfaces.Any(static interfaceSymbol => + interfaceSymbol.Name == nameof(IComputeShader) || + interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) + { + this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); + } + } + + /// + /// A model for a group of item representing a discovered type to process. + /// + /// The instance for the target struct declaration. + /// The instance for . + public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); + } + } +} + diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs new file mode 100644 index 00000000..e50f9882 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -0,0 +1,214 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; + +namespace ComputeSharp.SourceGenerators +{ + /// + /// A source generator creating data loaders for and types. + /// + [Generator] + public sealed partial class IShaderGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); + } + + /// + public void Execute(GeneratorExecutionContext context) + { + // Get the syntax receiver with the candidate nodes + if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) + { + return; + } + + foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) + { + try + { + OnExecute(context, item.StructDeclaration, item.StructSymbol); + } + catch + { + context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, item.StructDeclaration, item.StructSymbol); + } + } + } + + /// + /// Processes a given target type. + /// + /// The input instance to use. + /// The node to process. + /// The for . + private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol) + { + // Create the required interface methods for the current shader type + MethodDeclarationSyntax + getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol), + loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants), + buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out bool isSamplerUsed), + loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(context, structDeclaration, structDeclarationSymbol, discoveredResources, root32BitConstants, isSamplerUsed); + + // Reorder the method declarations to respect the order in the interface definition + MethodDeclarationSyntax[] methods = + { + getDispatchIdMethod, + loadDispatchDataMethod, + loadDispatchMetadataMethod, + buildHlslStringMethod + }; + + // Method attributes + AttributeListSyntax[] attributes = new[] + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is not intended to be used directly by user code")))))) + }; + + string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); + string structName = structDeclaration.Identifier.Text; + SyntaxTokenList structModifiers = structDeclaration.Modifiers; + + // Create the partial shader type declaration with the hashcode interface method implementation. + // This code produces a struct declaration as follows: + // + // public struct ShaderType : IShader + // { + // + // } + var structDeclarationSyntax = + StructDeclaration(structName) + .WithModifiers(structModifiers) + .AddBaseListTypes(SimpleBaseType( + GenericName(Identifier("IShader")) + .AddTypeArgumentListArguments(IdentifierName(structName)))) + .AddMembers(methods.Select(m => m.AddAttributeLists(attributes)).ToArray()); + + TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; + + // Add all parent types in ascending order, if any + foreach (var parentType in structDeclaration.Ancestors().OfType()) + { + typeDeclarationSyntax = parentType + .WithMembers(SingletonList(typeDeclarationSyntax)) + .WithConstraintClauses(List()) + .WithBaseList(null) + .WithAttributeLists(List()) + .WithoutTrivia(); + } + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.CodeDom.Compiler; + // using System.ComponentModel; + // using System.Diagnostics; + // using System.Diagnostics.CodeAnalysis; + // using System.Runtime.CompilerServices; + // using ComputeSharp.__Internals; + // + // #pragma warning disable + // + // namespace + // { + // + // } + var source = + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.CodeDom.Compiler")), + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Diagnostics")), + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), + UsingDirective(IdentifierName("System.Runtime.CompilerServices")), + UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( + NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) + .NormalizeWhitespace() + .ToFullString(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + + /// + /// Creates a instance for the GetDispatchId method. + /// + /// The for . + /// The resulting instance for the GetDispatchId method. + private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol); + + /// + /// Creates a instance for the LoadDispatchDataMethod method. + /// + /// The input instance to use. + /// The for . + /// The sequence of discovered resources in the current shader type. + /// The total number of 32 bit root constants being loaded for the current shader type. + /// The resulting instance for the LoadDispatchDataMethod method. + private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( + GeneratorExecutionContext context, + INamedTypeSymbol structDeclarationSymbol, + out IEnumerable discoveredResources, + out int root32BitConstantsCount); + + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input instance to use. + /// The node to process. + /// The for . + /// Whether or not the current shader type requires a static sampler to be available. + /// The resulting instance for the BuildHlslString method. + private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out bool isSamplerUsed); + + /// + /// Creates a instance for the LoadDispatchMetadata method. + /// + /// The input instance to use. + /// The node to process. + /// The for . + /// The sequence of resources used by the shader. + /// The total number of 32 bit root constants being loaded for the shader. + /// Whether or not the shader requires a static sampler to be available. + /// The resulting instance for the LoadDispatchMetadata method. + private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + IEnumerable discoveredResources, + int root32BitConstantsCount, + bool isSamplerUsed); + } +} + From a5a4a77e65e618b663e9181239756fa900f978b9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 16:05:22 +0200 Subject: [PATCH 15/37] Implemented source generator logic for LoadDispatchMetadataMethod --- ...erGenerator.CreateBuildHlslStringMethod.cs | 6 +- ...rGenerator.CreateLoadDispatchDataMethod.cs | 8 +- ...erator.CreateLoadDispatchMetadataMethod.cs | 150 ++++++++++++++++-- .../IShaderGenerator.cs | 22 ++- 4 files changed, 158 insertions(+), 28 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 785c9def..1e843687 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -24,6 +24,7 @@ namespace ComputeSharp.SourceGenerators GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, + out string? implicitTextureType, out bool isSamplerUsed) { // Properties are not supported @@ -44,7 +45,7 @@ namespace ComputeSharp.SourceGenerators var semanticModel = new SemanticModelProvider(context.Compilation); var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; - var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); + var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, processedMethods, forwardDeclarations, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); @@ -61,13 +62,14 @@ namespace ComputeSharp.SourceGenerators processedTypes, isComputeShader, processedMembers, - implicitTextureType, + pixelShaderTextureType, accessesStaticSampler, sharedBuffers, forwardDeclarations, processedMethods, entryPoint); + implicitTextureType = pixelShaderTextureType; isSamplerUsed = accessesStaticSampler; // This code produces a method declaration as follows: diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 13ccee56..50e40a94 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -20,7 +20,7 @@ namespace ComputeSharp.SourceGenerators private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, - out IEnumerable discoveredResources, + out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount) { // This code produces a method declaration as follows: @@ -53,14 +53,14 @@ namespace ComputeSharp.SourceGenerators } /// - /// Gets a sequence of statements to load the dispatch data for a given shader + /// Gets a sequence of statements to load the dispatch data for a given shader. /// /// The current generator context in use. /// The input instance to process. - /// The sequence of discovered resources in the current shader type. + /// The collection of discovered resources in the current shader type. /// The total number of 32 bit root constants being loaded for the current shader type. /// The sequence of instances to load shader dispatch data. - private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IEnumerable discoveredResources, out int root32BitConstantsCount) + private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount) { List statements = new(); List resources = new(); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 7810b3f6..1e270776 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -1,8 +1,6 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.Contracts; -using System.Linq; -using Microsoft.CodeAnalysis; +using System; +using System.Collections.Generic; +using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -14,14 +12,146 @@ namespace ComputeSharp.SourceGenerators { /// private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - IEnumerable discoveredResources, + string? implicitTextureType, + IReadOnlyCollection discoveredResources, int root32BitConstantsCount, bool isSamplerUsed) { - return MethodDeclaration(IdentifierName("void"), "LoadDispatchMetadataMethod"); + // This code produces a method declaration as follows: + // + // public readonly void LoadDispatchMetadata(ref TMetadataLoader loader, out IntPtr result) + // where TMetadataLoader : struct, IDispatchMetadataLoader + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchMetadata")) + .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TMetadataLoader")), + Parameter(Identifier("result")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName(typeof(IntPtr).Name))) + .AddConstraintClauses( + TypeParameterConstraintClause(IdentifierName("TMetadataLoader")) + .AddConstraints( + ClassOrStructConstraint(SyntaxKind.StructConstraint), + TypeConstraint(IdentifierName("IDispatchMetadataLoader")))) + .WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed))); + } + + /// + /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// + /// The implicit texture type, if available (if the shader is a pixel shader). + /// The collection of resources used by the shader. + /// The total number of 32 bit root constants being loaded for the shader. + /// Whether or not the shader requires a static sampler to be available. + /// The sequence of instances to load shader dispatch data. + private static IEnumerable GetDispatchMetadataLoadingStatements( + string? implicitTextureType, + IReadOnlyCollection discoveredResources, + int root32BitConstantsCount, + bool isSamplerUsed) + { + // Span span0 = stackalloc byte[5]; + yield return + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))); + + // Span span1 = stackalloc ResourceDescriptor[]; + yield return + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("Span")) + .AddTypeArgumentListArguments(IdentifierName("ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(IdentifierName("ResourceDescriptor")) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(discoveredResources.Count)))))))))); + + // ref byte r0 = ref span0[0]; + yield return + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0))))))))); + + // ref ResourceDescriptor r1 = ref span1[0]; + yield return + LocalDeclarationStatement( + VariableDeclaration(RefType(IdentifierName("ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0))))))))); + + // Serialized shader metadata + yield return ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r0, 0), {root32BitConstantsCount});"); + yield return ParseStatement($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});"); + + int + constantBufferOffset = 1, + readOnlyResourceOffset = 0, + readWriteResourceOffset = 0, + resourceOffset = 0; + + // Add the implicit texture descriptor, if needed + if (implicitTextureType is not null) + { + yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + + // Populate the sequence of resource descriptors + foreach (var resource in discoveredResources) + { + if (HlslKnownTypes.IsConstantBufferType(resource)) + { + yield return ParseStatement($"ResourceDescriptor.Create(2, {constantBufferOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource)) + { + yield return ParseStatement($"ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + else + { + yield return ParseStatement($"ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out Unsafe.Add(ref r1, {resourceOffset++}));"); + } + } + + // Invoke the value delegate to create the opaque root signature handle + yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"); } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index e50f9882..8e30c161 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -59,8 +59,8 @@ namespace ComputeSharp.SourceGenerators MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol), loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants), - buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out bool isSamplerUsed), - loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(context, structDeclaration, structDeclarationSymbol, discoveredResources, root32BitConstants, isSamplerUsed); + buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed), + loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed); // Reorder the method declarations to respect the order in the interface definition MethodDeclarationSyntax[] methods = @@ -169,13 +169,13 @@ namespace ComputeSharp.SourceGenerators /// /// The input instance to use. /// The for . - /// The sequence of discovered resources in the current shader type. + /// The collection of discovered resources in the current shader type. /// The total number of 32 bit root constants being loaded for the current shader type. /// The resulting instance for the LoadDispatchDataMethod method. private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, - out IEnumerable discoveredResources, + out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount); /// @@ -184,29 +184,27 @@ namespace ComputeSharp.SourceGenerators /// The input instance to use. /// The node to process. /// The for . + /// The implicit texture type, if available (if the shader is a pixel shader). /// Whether or not the current shader type requires a static sampler to be available. /// The resulting instance for the BuildHlslString method. private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, + out string? implicitTextureType, out bool isSamplerUsed); /// /// Creates a instance for the LoadDispatchMetadata method. /// - /// The input instance to use. - /// The node to process. - /// The for . - /// The sequence of resources used by the shader. + /// The implicit texture type, if available (if the shader is a pixel shader). + /// The collection of resources used by the shader. /// The total number of 32 bit root constants being loaded for the shader. /// Whether or not the shader requires a static sampler to be available. /// The resulting instance for the LoadDispatchMetadata method. private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - IEnumerable discoveredResources, + string? implicitTextureType, + IReadOnlyCollection discoveredResources, int root32BitConstantsCount, bool isSamplerUsed); } From f8207f11ffdcc5dc5c229e285b365c249fc69da7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 16:18:52 +0200 Subject: [PATCH 16/37] Removed previous individual source generators for shaders --- .../AnalyzerReleases.Shipped.md | 88 +- .../Diagnostics/DiagnosticDescriptors.cs | 48 +- ...haderDataLoaderGenerator.SyntaxReceiver.cs | 49 -- .../IComputeShaderDataLoaderGenerator.cs | 468 ----------- ...eShaderHashCodeGenerator.SyntaxReceiver.cs | 49 -- .../IComputeShaderHashCodeGenerator.cs | 221 ----- ...uteShaderSourceGenerator.SyntaxReceiver.cs | 49 -- .../IComputeShaderSourceGenerator.cs | 793 ------------------ .../IShaderGenerator.cs | 6 +- .../ShaderMethodSourceGenerator.cs | 4 +- .../DiagnosticsTests.cs | 98 +-- 11 files changed, 105 insertions(+), 1768 deletions(-) delete mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs delete mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 8ab9597d..02fa72d6 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -7,50 +7,48 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- -CMPS0001 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0002 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0003 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0004 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0005 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0006 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0007 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0008 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0009 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0010 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0011 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0012 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0013 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0014 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0015 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0016 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0017 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0018 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0019 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0020 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0021 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0022 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0023 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0024 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0025 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0026 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0027 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0028 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0029 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0030 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0031 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0032 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0033 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0034 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0035 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0036 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0001 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0002 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0003 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0004 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0005 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0006 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0007 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0008 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0009 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0010 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0011 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0012 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0013 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0014 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0015 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0016 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0017 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0018 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0019 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0020 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0021 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0022 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0023 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0024 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0025 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0026 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0027 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0028 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0029 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0030 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0031 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0032 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | AutoConstructorGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0038 | ComputeSharp.SourceGenerators.IComputeShaderDataLoaderGenerator | Warning | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0039 | ComputeSharp.SourceGenerators.IComputeShaderHashCodeGenerator | Warning | IComputeShaderHashCodeGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0040 | ComputeSharp.SourceGenerators.IComputeShaderSourceGenerator | Warning | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0040 | ComputeSharp.SourceGenerators.IShaderGenerator | Warning | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0042 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) -CMPS0047 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index caf8bc94..e936e826 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -513,51 +513,19 @@ namespace ComputeSharp.SourceGenerators.Diagnostics helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for an internal error in . + /// Gets a for an internal error in . /// - /// Format: "The generator IComputeShaderDataLoaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". + /// Format: "The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". /// /// - public static readonly DiagnosticDescriptor IComputeShaderDataLoaderGeneratorError = new( - id: "CMPS0038", - title: $"Internal error for {nameof(IComputeShaderDataLoaderGenerator)}", - messageFormat: $"The generator {nameof(IComputeShaderDataLoaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", - category: typeof(IComputeShaderDataLoaderGenerator).FullName, - defaultSeverity: DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: $"The {nameof(IComputeShaderDataLoaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator IComputeShaderHashCodeGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". - /// - /// - public static readonly DiagnosticDescriptor IComputeShaderHashCodeGeneratorError = new( - id: "CMPS0039", - title: $"Internal error for {nameof(IComputeShaderHashCodeGenerator)}", - messageFormat: $"The generator {nameof(IComputeShaderHashCodeGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", - category: typeof(IComputeShaderHashCodeGenerator).FullName, - defaultSeverity: DiagnosticSeverity.Warning, - isEnabledByDefault: true, - description: $"The {nameof(IComputeShaderHashCodeGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", - helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator IComputeShaderSourceGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". - /// - /// - public static readonly DiagnosticDescriptor IComputeShaderSourceGeneratorError = new( + public static readonly DiagnosticDescriptor IShaderGeneratorError = new( id: "CMPS0040", - title: $"Internal error for {nameof(IComputeShaderSourceGenerator)}", - messageFormat: $"The generator {nameof(IComputeShaderSourceGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", - category: typeof(IComputeShaderSourceGenerator).FullName, + title: $"Internal error for {nameof(IShaderGenerator)}", + messageFormat: $"The generator {nameof(IShaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash", + category: typeof(IShaderGenerator).FullName, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, - description: $"The {nameof(IComputeShaderSourceGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", + description: $"The {nameof(IShaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// @@ -657,7 +625,7 @@ namespace ComputeSharp.SourceGenerators.Diagnostics id: "CMPS0047", title: "Multiple shader implementations for type declaration", messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface", - category: typeof(IComputeShaderSourceGenerator).FullName, + category: typeof(IShaderGenerator).FullName, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "A shader type cannot implement more than one shader interface.", diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs deleted file mode 100644 index b426151e..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators -{ - /// - public sealed partial class IComputeShaderDataLoaderGenerator - { - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is StructDeclarationSyntax structDeclaration && - context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => - interfaceSymbol.Name == nameof(IComputeShader) || - interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs deleted file mode 100644 index 12bd1543..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ /dev/null @@ -1,468 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.Core.Helpers; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Mappings; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators -{ - /// - /// A source generator creating data loaders for types. - /// - [Generator] - public sealed partial class IComputeShaderDataLoaderGenerator : ISourceGenerator - { - /// - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - // Method attributes - AttributeListSyntax[] attributes = new[] - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code")))))) - }; - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - try - { - OnExecute(context, item.StructDeclaration, item.StructSymbol, attributes); - } - catch - { - context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, item.StructDeclaration, item.StructSymbol); - } - } - } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The for . - /// The list of instances to append to the generated method. - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, AttributeListSyntax[] attributes) - { - string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - string structName = structDeclaration.Identifier.Text; - SyntaxTokenList structModifiers = structDeclaration.Modifiers; - IEnumerable blockStatements = GetDispatchDataLoadingStatements(context, structDeclarationSymbol, out int root32BitConstantsCount); - - // Create the partial shader type declaration with the hashcode interface method implementation. - // This code produces a struct declaration as follows: - // - // public struct ShaderType : IShader - // { - // [GeneratedCode("...", "...")] - // [DebuggerNonUserCode] - // [ExcludeFromCodeCoverage] - // [EditorBrowsable(EditorBrowsableState.Never)] - // [Obsolete("This method is not intended to be called directly by user code")] - // [return: ComputeRoot32BitConstants(42)] - // public readonly void LoadDispatchData(ref TDataLoader loader, GraphicsDevice device, int x, int y, int z) - // where TDataLoader : struct, IDispatchDataLoader - // { - // - // } - // } - var structDeclarationSyntax = - StructDeclaration(structName).WithModifiers(structModifiers) - .AddBaseListTypes(SimpleBaseType( - GenericName(Identifier("IShader")) - .AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers( - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchData")) - .AddAttributeLists(attributes) - .AddAttributeLists(AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", ""))) - .AddArgumentListArguments(AttributeArgument(LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(root32BitConstantsCount)))))) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword)))) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TDataLoader")), - Parameter(Identifier("device")).WithType(IdentifierName("GraphicsDevice")), - Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .AddConstraintClauses( - TypeParameterConstraintClause(IdentifierName("TDataLoader")) - .AddConstraints( - ClassOrStructConstraint(SyntaxKind.StructConstraint), - TypeConstraint(IdentifierName("IDispatchDataLoader")))) - .WithBody(Block(blockStatements))); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (var parentType in structDeclaration.Ancestors().OfType()) - { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .WithoutTrivia(); - } - - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: - // - // using System; - // using System.CodeDom.Compiler; - // using System.ComponentModel; - // using System.Diagnostics; - // using System.Diagnostics.CodeAnalysis; - // using System.Runtime.CompilerServices; - // using ComputeSharp.__Internals; - // - // #pragma warning disable - // - // namespace - // { - // - // } - var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.CodeDom.Compiler")), - UsingDirective(IdentifierName("System.ComponentModel")), - UsingDirective(IdentifierName("System.Diagnostics")), - UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), - UsingDirective(IdentifierName("System.Runtime.CompilerServices")), - UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( - NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) - .NormalizeWhitespace() - .ToFullString(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a sequence of statements to load the dispatch data for a given shader - /// - /// The current generator context in use. - /// The input instance to process. - /// The total number of 32 bit root constants to load. - /// The sequence of instances to load shader dispatch data. - [Pure] - private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out int count) - { - List statements = new(); - - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - int - resourceOffset = 0, - rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); - - // Append the statements for the dispatch ranges: - // - // span0[0] = (uint)x; - // span0[1] = (uint)y; - // span0[2] = (uint)z; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); - - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); - - if (isComputeShader) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); - } - - // Append the statements to load all fields (both resources and other captured values) - AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, statements); - - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to a multiple of a 32 bit value. This is necessary to - // enable loading all the dispatch data after reinterpreting it to a sequence of values - // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int)); - count = rawDataOffset / sizeof(int); - - // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. - // Loaded values in the root signature have the following costs: - // - Root constants cost 1 DWORD each, since they are 32-bit values. - // - Descriptor tables cost 1 DWORD each. - // - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each. - // So here we check whether the current signature respects that constraint, - // and emit a build error otherwise. For more info on this, see the docs here: - // https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits. - int rootSignatureDwordSize = count + resourceOffset; - - if (rootSignatureDwordSize > 64) - { - context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); - } - - // Span span0 = stackalloc uint[]; - statements.Insert(0, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(count))))))))))); - - // ref uint r0 = ref span0[0]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // loader.LoadCapturedValues(span0); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedValues"))) - .AddArgumentListArguments(Argument(IdentifierName("span0"))))); - - if (resourceOffset > 0) - { - // Span span1 = stackalloc ulong[]; - statements.Insert(1, - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset))))))))))); - - // ref ulong r1 = ref span1[0]; - statements.Insert(3, - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // loader.LoadCapturedResources(span1); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedResources"))) - .AddArgumentListArguments(Argument(IdentifierName("span1"))))); - } - - return statements; - } - - /// - /// Explores a given type hierarchy and generates statements to load fields. - /// - /// The current type being explored. - /// The current path of the field with respect to the shader instance. - /// The current offset in the root table of loaded resources. - /// The current offset within the loaded data buffer. - /// The target list of statements being generated. - private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection statements) - { - bool isFirstField = true; - - foreach ( - IFieldSymbol fieldSymbol in - from fieldSymbol in currentTypeSymbol.GetMembers().OfType() - where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } && - !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer - select fieldSymbol) - { - string - fieldName = fieldSymbol.Name, - typeName = fieldSymbol.Type.GetFullMetadataName(); - - // Disambiguates the name of target fields against the current input parameters - if (fieldName is "loader" or "device" or "x" or "y" or "z") - { - fieldName = $"this.{fieldName}"; - } - - // The first item in each nested struct needs to be aligned to 16 bytes - if (isFirstField && fieldPath.Count > 0) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - isFirstField = false; - } - - if (HlslKnownTypes.IsTypedResourceType(typeName)) - { - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.Add(ref r1, {resourceOffset++})"), - ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)")))); - } - else if (HlslKnownTypes.IsKnownHlslType(typeName)) - { - AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements); - } - else if (fieldSymbol.Type.IsUnmanagedType) - { - // Custom struct type defined by the user - AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, statements); - } - } - } - - /// - /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix). - /// - /// The current path of the field with respect to the shader instance. - /// The type name currently being read. - /// The current offset within the loaded data buffer. - /// The target list of statements being generated. - private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection statements) - { - // For scalar, vector and linear matrix types, serialize the value normally. - // Only the initial alignment needs to be considered, while data is packed. - var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); - - // Check if the current type is a matrix type with more than one row. In this - // case, each row is aligned as if it was a separate array, so the start of - // each row needs to be at a multiple of 16 bytes (a float4 register). - if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns)) - { - string - rowTypeName = $"ComputeSharp.{elementName}{columns}", - rowLocalName = $"__{string.Join("_", fieldPath)}__row0"; - - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref Unsafe.As<{typeName}, {rowTypeName}>(ref Unsafe.AsRef(in {string.Join(".", fieldPath)}));")); - - // Generate the loading code for each individual row, with proper alignment. - // This will result in the following (assuming Float2x3 m): - // - // ref Float3 __m__row0 = ref Unsafe.As(ref Unsafe.AsRef(in m)); - // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, Unsafe.Add(ref __m__row0, 0); - // Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = Unsafe.Add(ref __m__row0, 1); - for (int j = 0; j < rows; j++) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), - ParseExpression($"Unsafe.Add(ref {rowLocalName}, {j})")))); - - rawDataOffset += fieldPack * columns; - } - } - else - { - // Calculate the right offset with 16-bytes padding (HLSL constant buffer). - // Since we're in a constant buffer, we need to both pad the starting offset - // to be aligned to the packing size of the type, and also to align the initial - // offset to ensure that values do not cross 16 bytes boundaries either. - rawDataOffset = AlignmentHelper.AlignToBoundary( - AlignmentHelper.Pad(rawDataOffset, fieldPack), - fieldSize, - 16); - - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.As(ref Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), - ParseExpression($"{string.Join(".", fieldPath)}")))); - - rawDataOffset += fieldSize; - } - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs deleted file mode 100644 index 2e58a0cb..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators -{ - /// - public sealed partial class IComputeShaderHashCodeGenerator - { - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is StructDeclarationSyntax structDeclaration && - context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => - interfaceSymbol.Name == nameof(IComputeShader) || - interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs deleted file mode 100644 index ff0663f9..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ /dev/null @@ -1,221 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; - -namespace ComputeSharp.SourceGenerators -{ - /// - /// A source generator creating hash code factories for types. - /// - [Generator] - public sealed partial class IComputeShaderHashCodeGenerator : ISourceGenerator - { - /// - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - // Method attributes - AttributeListSyntax[] attributes = new[] - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code")))))) - }; - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - try - { - OnExecute(context, item.StructDeclaration, item.StructSymbol, attributes); - } - catch - { - context.ReportDiagnostic(IComputeShaderHashCodeGeneratorError, item.StructDeclaration, item.StructSymbol); - } - } - } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The for . - /// The list of instances to append to the generated method. - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, AttributeListSyntax[] attributes) - { - string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - string structName = structDeclaration.Identifier.Text; - SyntaxTokenList structModifiers = structDeclaration.Modifiers; - - // Create the partial shader type declaration with the hashcode interface method implementation. - // This code produces a struct declaration as follows: - // - // public struct ShaderType : IShader - // { - // [GeneratedCode("...", "...")] - // [DebuggerNonUserCode] - // [ExcludeFromCodeCoverage] - // [EditorBrowsable(EditorBrowsableState.Never)] - // [Obsolete("This method is not intended to be called directly by user code")] - // public readonly int GetDispatchId() - // { - // - // } - // } - var structDeclarationSyntax = - StructDeclaration(structName).WithModifiers(structModifiers) - .AddBaseListTypes(SimpleBaseType( - GenericName(Identifier("IShader")) - .AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers( - MethodDeclaration( - PredefinedType(Token(SyntaxKind.IntKeyword)), - Identifier("GetDispatchId")) - .AddAttributeLists(attributes) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) - .WithBody(GetShaderHashCodeBody(structDeclarationSymbol))); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (var parentType in structDeclaration.Ancestors().OfType()) - { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .WithoutTrivia(); - } - - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: - // - // using System; - // using System.CodeDom.Compiler; - // using System.ComponentModel; - // using System.Diagnostics; - // using System.Diagnostics.CodeAnalysis; - // using ComputeSharp.__Internals; - // - // #pragma warning disable - // - // namespace - // { - // - // } - var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.CodeDom.Compiler")), - UsingDirective(IdentifierName("System.ComponentModel")), - UsingDirective(IdentifierName("System.Diagnostics")), - UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), - UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( - NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) - .NormalizeWhitespace() - .ToFullString(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a instance with the logic to compute the hashcode of a given shader type. - /// - /// The input instance to process. - /// The instance to hash the input shader. - [Pure] - private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol) - { - var delegateFields = structDeclarationSymbol - .GetMembers() - .OfType() - .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) - .ToImmutableArray(); - - if (delegateFields.Length == 0) - { - // return 0; - return - Block(ReturnStatement( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))); - } - - List blockStatements = new(4); - - // HashCode hashCode = default; - blockStatements.Add(LocalDeclarationStatement( - VariableDeclaration(IdentifierName("HashCode")) - .AddVariables( - VariableDeclarator(Identifier("hashCode")) - .WithInitializer(EqualsValueClause( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword))))))); - - foreach (IFieldSymbol fieldSymbol in delegateFields) - { - // hashCode.Add(delegateField.Method); - blockStatements.Add(ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(fieldSymbol.Name), - IdentifierName("Method")))))); - } - - // return hashCode.ToHashCode(); - blockStatements.Add(ReturnStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("hashCode"), - IdentifierName("ToHashCode"))))); - - return Block(blockStatements); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs deleted file mode 100644 index a4d2182b..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; - -namespace ComputeSharp.SourceGenerators -{ - /// - public sealed partial class IComputeShaderSourceGenerator - { - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - public void OnVisitSyntaxNode(GeneratorSyntaxContext context) - { - if (context.Node is StructDeclarationSyntax structDeclaration && - context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => - interfaceSymbol.Name == nameof(IComputeShader) || - interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs deleted file mode 100644 index abc54d44..00000000 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ /dev/null @@ -1,793 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.SourceGenerators.Diagnostics; -using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Helpers; -using ComputeSharp.SourceGenerators.Mappings; -using ComputeSharp.SourceGenerators.SyntaxRewriters; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; -using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; - -#pragma warning disable CS0618 - -namespace ComputeSharp.SourceGenerators -{ - /// - /// A source generator for processing types. - /// - [Generator] - public sealed partial class IComputeShaderSourceGenerator : ISourceGenerator - { - /// - public void Initialize(GeneratorInitializationContext context) - { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } - - /// - public void Execute(GeneratorExecutionContext context) - { - // Get the syntax receiver with the candidate nodes - if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver) - { - return; - } - - foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo) - { - SemanticModelProvider semanticModel = new(context.Compilation); - - try - { - OnExecute(context, item.StructDeclaration, semanticModel, item.StructSymbol); - } - catch - { - context.ReportDiagnostic(IComputeShaderSourceGeneratorError, item.StructDeclaration, item.StructSymbol); - } - } - } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The with metadata on the types being processed. - /// The for . - private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, SemanticModelProvider semanticModel, INamedTypeSymbol structDeclarationSymbol) - { - // Properties are not supported - DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // A given type can only represent a single shader type - if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) - { - context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); - } - - // Explore the syntax tree and extract the processed info - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); - var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); - var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); - var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedConstants = GetProcessedConstants(constantDefinitions); - var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - - GenerateRenderMethod( - context, - structDeclaration, - structDeclarationSymbol, - processedConstants, - staticFields, - processedTypes, - isComputeShader, - processedMembers, - implicitTextureType, - isSamplerUsed, - sharedBuffers, - forwardDeclarations, - processedMethods, - entryPoint); - - // Create the compilation unit with the source attribute - var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( - AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))), - AttributeArgument(ArrayExpression(Array.Empty())), // TODO - AttributeArgument(ArrayExpression(Array.Empty())), // TODO - AttributeArgument(ArrayExpression(Array.Empty())), // TODO - AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO - AttributeArgument(ArrayExpression(Array.Empty())), // TODO - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(""))), // TODO - AttributeArgument(ArrayExpression(Array.Empty())), // TODO - AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO - AttributeArgument(NestedArrayExpression(Array.Empty())), // TODO - AttributeArgument(NestedArrayExpression(Array.Empty()))))) // TODO - .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) - .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace() - .ToFullString(); - - // Add the method source attribute - context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - /// - /// Gets a sequence of captured fields and their mapped names. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// Indicates whether or not represents a compute shader. - /// A sequence of captured fields in . - [Pure] - private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types, - bool isComputeShader) - { - bool hlslResourceFound = false; - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (fieldSymbol.IsStatic) continue; - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - // Group shared fields must be static - if (attribute is not null) - { - context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); - } - - // Captured fields must be named type symbols - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - string metadataName = typeSymbol.GetFullMetadataName(); - - // Allowed fields must be either resources, unmanaged values or delegates - if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - hlslResourceFound = true; - - // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(metadataName)) - { - types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); - } - } - else if (!typeSymbol.IsUnmanagedType && - typeSymbol.TypeKind != TypeKind.Delegate) - { - // Shaders can only capture valid HLSL resource types or unmanaged types - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); - - continue; - } - else if (typeSymbol.IsUnmanagedType && - !HlslKnownTypes.IsKnownHlslType(metadataName)) - { - // Track the type if it's a custom struct - types.Add(typeSymbol); - } - - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Yield back the current mapping for the name (if the name used a reserved keyword) - yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName); - } - - // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource - if (!hlslResourceFound && isComputeShader) - { - context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); - } - } - - /// - /// Gets a sequence of shader static fields and their mapped names. - /// - /// The current generator context in use. - /// The instance for the type to process. - /// The instance for the current type. - /// The type symbol for the shader type. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of static constant fields in . - [Pure] - private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - GeneratorExecutionContext context, - SemanticModelProvider semanticModel, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - foreach (var fieldDeclaration in structDeclaration.Members.OfType()) - { - foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) - { - IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; - - if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) - { - continue; - } - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is not null) continue; - - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) - { - context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - string typeDeclaration = fieldSymbol.IsReadOnly switch - { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; - - StaticFieldRewriter staticFieldRewriter = new( - semanticModel, - discoveredTypes, - constantDefinitions, - context); - - string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString(); - - yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); - } - } - } - - /// - /// Gets a sequence of captured members and their mapped names. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// A sequence of captured members in . - [Pure] - private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types) - { - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (!fieldSymbol.IsStatic) continue; - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is null) continue; - - if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - if (!typeSymbol.ElementType.IsUnmanagedType) - { - context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; - - string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); - - types.Add((INamedTypeSymbol)typeSymbol.ElementType); - } - } - - /// - /// Gets a sequence of processed methods declared within a given type. - /// - /// The current generator context in use. - /// The type symbol for the shader type. - /// The instance for the current type. - /// The instance for the type to process. - /// The collection of currently discovered types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// Indicates whether or not represents a compute shader. - /// A sequence of processed methods in , and the entry point. - [Pure] - private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations, bool IsSamplerUser) GetProcessedMethods( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - bool isComputeShader) - { - // Find all declared methods in the type - ImmutableArray methodDeclarations = ( - from syntaxNode in structDeclaration.DescendantNodes() - where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) - select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - - string? entryPoint = null; - List methods = new(); - List declarations = new(); - bool isSamplerUsed = false; - - foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) - { - IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; - bool isShaderEntryPoint = - (isComputeShader && - methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0) || - (!isComputeShader && - methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && - methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0); - - // Create the source rewriter for the current method - ShaderSourceRewriter shaderSourceRewriter = new( - structDeclarationSymbol, - semanticModel, - discoveredTypes, - staticMethods, - constantDefinitions, - context, - isShaderEntryPoint); - - // Rewrite the method syntax tree - MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); - - // Track the implicit sampler, if used - isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; - - // Emit the extracted local functions first - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); - declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace().ToFullString()); - } - - // If the method is the shader entry point, do additional processing - if (isShaderEntryPoint) - { - processedMethod = isComputeShader switch - { - true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, - false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! - }; - - entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); - } - else - { - methods.Add(processedMethod.NormalizeWhitespace().ToFullString()); - declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace().ToFullString()); - } - } - - // Process static methods as well - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - methods.Add(staticMethod.NormalizeWhitespace().ToFullString()); - declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString()); - } - - return (entryPoint!, methods, declarations, isSamplerUsed); - } - - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - [Pure] - internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) - { - foreach (var constant in constantDefinitions) - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - yield return (constantName, constant.Value); - } - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// The sequence of discovered custom types. - /// A sequence of custom type definitions to add to the shader source. - internal static IEnumerable GetProcessedTypes(IEnumerable types) - { - foreach (var type in HlslKnownTypes.GetCustomTypes(types)) - { - var structType = type.GetFullMetadataName().ToHlslIdentifierName(); - var structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (var field in type.GetMembers().OfType()) - { - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) - { - mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); - } - - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mapped!)).AddVariables( - VariableDeclarator(Identifier(field.Name))))); - } - - // Insert the trailing ; right after the closing bracket (after normalization) - yield return - structDeclaration - .NormalizeWhitespace() - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString(); - } - } - - /// - /// Finds and reports all declared properties in a shader. - /// - /// The current generator context in use. - /// The input instance to process. - private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol) - { - foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) - { - context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); - } - } - - private static void GenerateRenderMethod( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - IEnumerable<(string Name, string Value)> definedConstants, - IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - IEnumerable declaredTypes, - bool isComputeShader, - IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, - string? implicitTextureType, - bool isSamplerUsed, - IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, - IEnumerable? forwardDeclarations, - IEnumerable processedMethods, - string executeMethod) - { - string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - string structName = structDeclaration.Identifier.Text; - SyntaxTokenList structModifiers = structDeclaration.Modifiers; - IEnumerable bodyStatements = GenerateRenderMethodBody( - definedConstants, - staticFields, - declaredTypes, - isComputeShader, - instanceFields, - implicitTextureType, - isSamplerUsed, - sharedBuffers, - forwardDeclarations, - processedMethods, - executeMethod); - - // Create the partial shader type declaration with the hashcode interface method implementation. - // This code produces a struct declaration as follows: - // - // public struct ShaderType : IShader - // { - // [GeneratedCode("...", "...")] - // [DebuggerNonUserCode] - // [ExcludeFromCodeCoverage] - // [EditorBrowsable(EditorBrowsableState.Never)] - // [Obsolete("This method is not intended to be called directly by user code")] - // public readonly void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) - // { - // - // } - // } - var structDeclarationSyntax = - StructDeclaration(structName).WithModifiers(structModifiers) - .AddBaseListTypes(SimpleBaseType( - GenericName(Identifier("IShader")) - .AddTypeArgumentListArguments(IdentifierName(structName)))).AddMembers( - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("BuildHlslString")) - .AddAttributeLists( - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderHashCodeGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code"))))))) - .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(bodyStatements))); - - TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax; - - // Add all parent types in ascending order, if any - foreach (var parentType in structDeclaration.Ancestors().OfType()) - { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .WithoutTrivia(); - } - - // Create a static method to create the combined hashcode for a given shader type. - // This code takes a block syntax and produces a compilation unit as follows: - // - // using System; - // using System.CodeDom.Compiler; - // using System.ComponentModel; - // using System.Diagnostics; - // using System.Diagnostics.CodeAnalysis; - // using ComputeSharp.__Internals; - // - // #pragma warning disable - // - // namespace - // { - // - // } - var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.CodeDom.Compiler")), - UsingDirective(IdentifierName("System.ComponentModel")), - UsingDirective(IdentifierName("System.Diagnostics")), - UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), - UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( - NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) - .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) - .NormalizeWhitespace() - .ToFullString(); - - // Add the method source attribute - context.AddSource("PREVIEW" + structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); - } - - private static IEnumerable GenerateRenderMethodBody( - IEnumerable<(string Name, string Value)> definedConstants, - IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - IEnumerable declaredTypes, - bool isComputeShader, - IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, - string? implicitTextureType, - bool isSamplerUsed, - IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, - IEnumerable? forwardDeclarations, - IEnumerable processedMethods, - string executeMethod) - { - // Header - yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); - yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");"); - yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); - yield return ParseStatement("builder.AppendLine(\"// This shader was created by ComputeSharp.\");"); - yield return ParseStatement("builder.AppendLine(\"// See: https://github.com/Sergio0694/ComputeSharp.\");"); - - // Group size constants - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.Append(\"#define __GroupSize__get_X \");"); - yield return ParseStatement("builder.AppendLine(threadsX.ToString());"); - yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Y \");"); - yield return ParseStatement("builder.AppendLine(threadsY.ToString());"); - yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Z \");"); - yield return ParseStatement("builder.AppendLine(threadsZ.ToString());"); - - // Define declarations - foreach (var (name, value) in definedConstants) - { - yield return ParseStatement($"builder.AppendLine(\"#define {name} {value}\");"); - } - - // Static fields - if (staticFields.Any()) - { - yield return ParseStatement("builder.AppendLine();"); - - foreach (var field in staticFields) - { - if (field.Assignment is string assignment) - { - yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name} = {assignment};\");"); - } - else - { - yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name};\");"); - } - } - } - - // Declared types - foreach (var type in declaredTypes) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{type}\");"); - } - - // Captured variables - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.AppendLine(\"cbuffer _ : register(b0)\");"); - yield return ParseStatement("builder.AppendLine('{');"); - yield return ParseStatement("builder.AppendLine(\" uint __x;\");"); - yield return ParseStatement("builder.AppendLine(\" uint __y;\");"); - - if (isComputeShader) - { - yield return ParseStatement("builder.AppendLine(\" uint __z;\");"); - } - - // User-defined values - foreach (var instanceField in instanceFields) - { - if (instanceField.Symbol.Type.IsUnmanagedType) - { - yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName};\");"); - } - } - - yield return ParseStatement("builder.AppendLine('}');"); - - int - constantBuffersCount = 0, - readOnlyBuffersCount = 0, - readWriteBuffersCount = 0; - - // Optional implicit texture field - if (!isComputeShader) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});\");"); - } - - // Optional sampler field - if (isSamplerUsed) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.AppendLine(\"SamplerState __sampler : register(s);\");"); - } - - // Resources - foreach (var instanceField in instanceFields) - { - string metadataName = instanceField.Symbol.GetFullMetadataName(); - - if (HlslKnownTypes.IsConstantBufferType(metadataName)) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"cbuffer _{instanceField.HlslName} : register(b{constantBuffersCount++})\");"); - yield return ParseStatement("builder.AppendLine('{');"); - yield return ParseStatement($"builder.AppendLine(\" {instanceField.HlslType} {instanceField.HlslName}[2];\");"); - yield return ParseStatement("builder.AppendLine('}');"); - } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(t{readOnlyBuffersCount++});\");"); - } - else if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{instanceField.HlslType} : register(u{readWriteBuffersCount++});\");"); - } - } - - // Shared buffers - foreach (var sharedBuffer in sharedBuffers) - { - object count = (object?)sharedBuffer.Count ?? "threadsX * threadsY * threadsZ"; - - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"groupshared {sharedBuffer.Type} {sharedBuffer.Name} [{count}];\");"); - } - - // Forward declarations - if (forwardDeclarations is not null) - { - foreach (var forwardDeclaration in forwardDeclarations) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{forwardDeclaration}\");"); - } - } - - // Captured methods - if (processedMethods is not null) - { - foreach (var method in processedMethods) - { - yield return ParseStatement("builder.AppendLine();"); - yield return - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(method))))); - } - } - - // Entry point - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.AppendLine(\"[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]\");"); - yield return - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(executeMethod))))); - } - } -} - diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 8e30c161..56e71574 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -42,7 +42,7 @@ namespace ComputeSharp.SourceGenerators } catch { - context.ReportDiagnostic(IComputeShaderDataLoaderGeneratorError, item.StructDeclaration, item.StructSymbol); + context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol); } } } @@ -76,8 +76,8 @@ namespace ComputeSharp.SourceGenerators { AttributeList(SingletonSeparatedList( Attribute(IdentifierName("GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IComputeShaderDataLoaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), AttributeList(SingletonSeparatedList(Attribute(IdentifierName("DebuggerNonUserCode")))), AttributeList(SingletonSeparatedList(Attribute(IdentifierName("ExcludeFromCodeCoverage")))), AttributeList(SingletonSeparatedList( diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index a9f4f412..573afef0 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -72,8 +72,8 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); - var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray(); - var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions); + var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray(); + var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 021a575f..42be1d7c 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -35,7 +35,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0001"); + VerifyGeneratedDiagnostics(source, "CMPS0001"); } [TestMethod] @@ -60,7 +60,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0001"); + VerifyGeneratedDiagnostics(source, "CMPS0001"); } [TestMethod] @@ -88,7 +88,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0002"); + VerifyGeneratedDiagnostics(source, "CMPS0002"); } [TestMethod] @@ -116,7 +116,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0003"); + VerifyGeneratedDiagnostics(source, "CMPS0003"); } [TestMethod] @@ -142,7 +142,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0004"); + VerifyGeneratedDiagnostics(source, "CMPS0004"); } [TestMethod] @@ -159,7 +159,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0005"); + VerifyGeneratedDiagnostics(source, "CMPS0005"); } [TestMethod] @@ -194,7 +194,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, diagnosticsId); + VerifyGeneratedDiagnostics(source, diagnosticsId); } [TestMethod] @@ -226,7 +226,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, diagnosticsId); + VerifyGeneratedDiagnostics(source, diagnosticsId); } [TestMethod] @@ -256,7 +256,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0006"); + VerifyGeneratedDiagnostics(source, "CMPS0006"); } [TestMethod] @@ -283,7 +283,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0010"); + VerifyGeneratedDiagnostics(source, "CMPS0010"); } [TestMethod] @@ -310,7 +310,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0010"); + VerifyGeneratedDiagnostics(source, "CMPS0010"); } [TestMethod] @@ -337,7 +337,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0011"); + VerifyGeneratedDiagnostics(source, "CMPS0011"); } [TestMethod] @@ -366,7 +366,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0012"); + VerifyGeneratedDiagnostics(source, "CMPS0012"); } [TestMethod] @@ -392,7 +392,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0012"); + VerifyGeneratedDiagnostics(source, "CMPS0012"); } [TestMethod] @@ -419,7 +419,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0012", "CMPS0013"); + VerifyGeneratedDiagnostics(source, "CMPS0012", "CMPS0013"); } [TestMethod] @@ -448,7 +448,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0014"); + VerifyGeneratedDiagnostics(source, "CMPS0014"); } [TestMethod] @@ -480,7 +480,7 @@ namespace ComputeSharp.Tests.SourceGenerators }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0015"); + VerifyGeneratedDiagnostics(source, "CMPS0015"); } [TestMethod] @@ -512,7 +512,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0016", "CMPS0032"); + VerifyGeneratedDiagnostics(source, "CMPS0016", "CMPS0032"); } [TestMethod] @@ -544,7 +544,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0017"); + VerifyGeneratedDiagnostics(source, "CMPS0017"); } [TestMethod] @@ -573,7 +573,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0018"); + VerifyGeneratedDiagnostics(source, "CMPS0018"); } [TestMethod] @@ -603,7 +603,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0019"); + VerifyGeneratedDiagnostics(source, "CMPS0019"); } [TestMethod] @@ -633,7 +633,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0020"); + VerifyGeneratedDiagnostics(source, "CMPS0020"); } [TestMethod] @@ -665,7 +665,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0021"); + VerifyGeneratedDiagnostics(source, "CMPS0021"); } [TestMethod] @@ -695,7 +695,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0022"); + VerifyGeneratedDiagnostics(source, "CMPS0022"); } [TestMethod] @@ -727,7 +727,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0023"); + VerifyGeneratedDiagnostics(source, "CMPS0023"); } [TestMethod] @@ -754,7 +754,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0024"); + VerifyGeneratedDiagnostics(source, "CMPS0024"); } [TestMethod] @@ -781,7 +781,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0032", "CMPS0025"); + VerifyGeneratedDiagnostics(source, "CMPS0032", "CMPS0025"); } [TestMethod] @@ -808,7 +808,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0026"); + VerifyGeneratedDiagnostics(source, "CMPS0026"); } [TestMethod] @@ -840,7 +840,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0027"); + VerifyGeneratedDiagnostics(source, "CMPS0027"); } [TestMethod] @@ -867,7 +867,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0028"); + VerifyGeneratedDiagnostics(source, "CMPS0028"); } [TestMethod] @@ -894,7 +894,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0029"); + VerifyGeneratedDiagnostics(source, "CMPS0029"); } [TestMethod] @@ -923,7 +923,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0029"); + VerifyGeneratedDiagnostics(source, "CMPS0029"); } [TestMethod] @@ -956,7 +956,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0030"); + VerifyGeneratedDiagnostics(source, "CMPS0030"); } [TestMethod] @@ -983,7 +983,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0031"); + VerifyGeneratedDiagnostics(source, "CMPS0031"); } [TestMethod] @@ -1010,7 +1010,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0032"); + VerifyGeneratedDiagnostics(source, "CMPS0032"); } [TestMethod] @@ -1037,7 +1037,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0033"); + VerifyGeneratedDiagnostics(source, "CMPS0033"); } [TestMethod] @@ -1066,7 +1066,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0034"); + VerifyGeneratedDiagnostics(source, "CMPS0034"); } [TestMethod] @@ -1095,7 +1095,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0035"); + VerifyGeneratedDiagnostics(source, "CMPS0035"); } [TestMethod] @@ -1124,7 +1124,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0035"); + VerifyGeneratedDiagnostics(source, "CMPS0035"); } [TestMethod] @@ -1151,7 +1151,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0036"); + VerifyGeneratedDiagnostics(source, "CMPS0036"); } [TestMethod] @@ -1192,7 +1192,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0042"); + VerifyGeneratedDiagnostics(source, "CMPS0042"); } [TestMethod] @@ -1220,7 +1220,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0043"); + VerifyGeneratedDiagnostics(source, "CMPS0043"); } [TestMethod] @@ -1248,7 +1248,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1279,7 +1279,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1307,7 +1307,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1335,7 +1335,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0045"); } [TestMethod] @@ -1367,7 +1367,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0046"); + VerifyGeneratedDiagnostics(source, "CMPS0046"); } [TestMethod] @@ -1392,7 +1392,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0047"); + VerifyGeneratedDiagnostics(source, "CMPS0047"); } /// @@ -1402,7 +1402,7 @@ namespace ComputeSharp.Tests.SourceGenerators /// The input source to process. /// The target index to check in the resulting output. /// The expected body to compare with the generated code. - private void VerifyGeneratedDiagnostics(string source, params string[] diagnosticsIds) + private static void VerifyGeneratedDiagnostics(string source, params string[] diagnosticsIds) where TGenerator : class, ISourceGenerator, new() { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); From 7552dd518985b5c9d3402a294a1c59638440522e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 16:26:51 +0200 Subject: [PATCH 17/37] Removed legacy shader loading code --- .../ComputeSharp.SourceGenerators.csproj | 3 - .../ComputeRoot32BitConstantsAttribute.cs | 29 -- .../IComputeShaderSourceAttribute.cs | 134 -------- .../MissingShaderMetadataException.cs | 47 --- .../Shaders/Interop/ReflectionServices.cs | 7 +- .../Shaders/Renderer/HlslShaderRenderer.cs | 192 ------------ .../Shaders/Renderer/Models/HlslFieldInfo.cs | 11 - .../Renderer/Models/HlslResourceInfo.cs | 43 --- .../Shaders/Translation/IShaderLoader.cs | 61 ---- .../Translation/Mappings/HlslKnownTypes.cs | 147 --------- .../Shaders/Translation/ShaderLoader{T}.cs | 288 ------------------ 11 files changed, 3 insertions(+), 959 deletions(-) delete mode 100644 src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs delete mode 100644 src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs delete mode 100644 src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs delete mode 100644 src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs delete mode 100644 src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs delete mode 100644 src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/IShaderLoader.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs delete mode 100644 src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 3e2dcc6f..52e8f25f 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -14,8 +14,6 @@ - - @@ -25,7 +23,6 @@ - diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs deleted file mode 100644 index 3277c05b..00000000 --- a/src/ComputeSharp/Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.ComponentModel; - -namespace ComputeSharp.__Internals -{ - /// - /// An attribute that contains info on the number of 32 bit constants for a given shader. - /// - /// This attribute is not meant to be directly used by applications using ComputeSharp. - [AttributeUsage(AttributeTargets.ReturnValue, AllowMultiple = false)] - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is not intended to be used directly by user code")] - public sealed class ComputeRoot32BitConstantsAttribute : Attribute - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The number of 32 bit constants for the annotated method. - public ComputeRoot32BitConstantsAttribute(int count) - { - Count = count; - } - - /// - /// Gets the number of 32 bit constants for the annotated method. - /// - internal int Count { get; } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs deleted file mode 100644 index d33a491b..00000000 --- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Reflection; -using ComputeSharp.Exceptions; - -namespace ComputeSharp.__Internals -{ - /// - /// An attribute that contains info on a processed compute shader that can be executed. - /// - /// This attribute is not meant to be directly used by applications using ComputeSharp. - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is not intended to be used directly by user code")] - public sealed class IComputeShaderSourceAttribute : Attribute - { - /// - /// Creates a new instance with the specified parameters. - /// - /// The type of the current shader. - /// The collection of custom types. - /// The implicit texture field info, if present. - /// The implicit texture sampler field info, if present. - /// The mapped collection of shader fields. - /// The forward declarations for static methods. - /// The source code for the method. - /// The collection of processed methods. - /// The collection of discovered defines. - /// The collection of discovered static fields. - /// The collection of group shared buffers. - public IComputeShaderSourceAttribute( - Type shaderType, - string[] types, - string[]? implicitTextureField, - string[]? implicitSamplerFields, - object[] fields, - string[] forwardDeclarations, - string executeMethod, - string[] methods, - object[] defines, - object[] staticFields, - object[] sharedBuffers) - { - ShaderType = shaderType; - Types = types; - ImplicitTextureField = implicitTextureField is null ? null : (implicitTextureField[0], implicitTextureField[1]); - ImplicitSamplerField = implicitSamplerFields is null ? null : (implicitSamplerFields[0], implicitSamplerFields[1]); - Fields = fields.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); - ForwardDeclarations = forwardDeclarations; - ExecuteMethod = executeMethod; - Methods = methods; - Defines = defines.Cast().ToDictionary(static c => c[0], static c => c[1]); - StaticFields = staticFields.Cast().ToDictionary(static arg => arg[0]!, static arg => (arg[1]!, arg[2])); - SharedBuffers = sharedBuffers.Cast().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2])); - } - - /// - /// Gets the type of the current shader. - /// - internal Type ShaderType { get; } - - /// - /// Gets the collection of processed custom types. - /// - internal IReadOnlyCollection Types { get; } - - /// - /// Gets the mapping for the implicit texture field, if the shader is a pixel shader. - /// - internal (string Name, string Type)? ImplicitTextureField { get; } - - /// - /// Gets the mapping for the implicit sampler field, if necessary. - /// - internal (string Name, string Type)? ImplicitSamplerField { get; } - - /// - /// Gets the mapping of field names. - /// - internal IReadOnlyDictionary Fields { get; } - - /// - /// The forward declarations for static methods. - /// - internal IReadOnlyCollection ForwardDeclarations { get; } - - /// - /// Gets the source code for the method. - /// - internal string ExecuteMethod { get; } - - /// - /// Gets the collection of processed methods. - /// - internal IReadOnlyCollection Methods { get; } - - /// - /// Gets the collection of discovered define declarations. - /// - internal IReadOnlyDictionary Defines { get; } - - /// - /// Gets the collection of discovered static fields. - /// - internal IReadOnlyDictionary StaticFields { get; } - - /// - /// Gets the collection of discovered shared buffers. - /// - internal IReadOnlyDictionary SharedBuffers { get; } - - /// - /// Gets the associated instance for a specified type. - /// - /// The shader type to get the attribute for. - /// The associated instance for type . - [Pure] - internal static IComputeShaderSourceAttribute GetForType() - { - IEnumerable attributes = typeof(T).Assembly.GetCustomAttributes(); - IComputeShaderSourceAttribute? attribute = attributes.SingleOrDefault(static attribute => attribute.ShaderType == typeof(T)); - - if (attribute is null) - { - MissingShaderMetadataException.Throw(); - } - - return attribute!; - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs b/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs deleted file mode 100644 index c4b9f7eb..00000000 --- a/src/ComputeSharp/Core/Exceptions/MissingShaderMetadataException.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Text; - -namespace ComputeSharp.Exceptions -{ - /// - /// A custom type that indicates when metadata is missing for a given shader. - /// - public sealed class MissingShaderMetadataException : Exception - { - /// - /// Creates a new instance. - /// - /// The error message to include in the exception.. - private MissingShaderMetadataException(string error) - : base(error) - { - } - - /// - /// Gets a formatted exception message for a given error. - /// - /// The type of shader that was failed to be loaded. - /// A new instance with a formatted error message. - [Pure] - private static MissingShaderMetadataException Create(Type type) - { - StringBuilder builder = new(512); - - builder.AppendLine($"Failed to retrieve the shader metadata for type {type}."); - builder.AppendLine("This usually indicates that the necessary source generator failed to run. Make sure to be using a IDE with full support " + - "for source generators, and that there are no build warnings in the errors window upon building your project. If a source " + - "generator fails to run correctly, please open an issue at https://github.com/Sergio0694/ComputeSharp and include a working repro along with it."); - - return new(builder.ToString()); - } - - /// - /// Throws a new for a given delegate. - /// - internal static void Throw() - { - throw Create(typeof(T)); - } - } -} diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs index cdc099c0..332654f8 100644 --- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs @@ -2,7 +2,6 @@ using System.Runtime.CompilerServices; using ComputeSharp.__Internals; using ComputeSharp.Core.Extensions; -using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; @@ -103,13 +102,13 @@ namespace ComputeSharp.Interop private static unsafe void GetNonGenericShaderInfo(in T shader, out ShaderInfo shaderInfo) where T : struct, IShader { - ShaderLoader shaderLoader = ShaderLoader.Load(in shader); + ArrayPoolStringBuilder shaderSource = ArrayPoolStringBuilder.Create(); - using var shaderSource = HlslShaderRenderer.Render(1, 1, 1, shaderLoader); + shader.BuildHlslString(ref shaderSource, 1, 1, 1); using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan); - using ComPtr dxcUtils = default; + Guid dxcLibraryClsid = FX.CLSID_DxcLibrary; FX.DxcCreateInstance(&dxcLibraryClsid, FX.__uuidof(), dxcUtils.GetVoidAddressOf()).Assert(); diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs deleted file mode 100644 index b0d797c3..00000000 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System.Diagnostics.Contracts; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Renderer.Models; -using ComputeSharp.Shaders.Translation; - -namespace ComputeSharp.Shaders.Renderer -{ - /// - /// A type that renders an HLSL template from the previously loaded shader data. - /// - internal static class HlslShaderRenderer - { - /// - /// Renders a new HLSL shader source with the given parameters. - /// - /// 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 with the shader information. - /// The source code for the new HLSL shader. - [Pure] - public static ArrayPoolStringBuilder Render(int threadsX, int threadsY, int threadsZ, IShaderLoader info) - { - var builder = ArrayPoolStringBuilder.Create(); - - // Header - builder.AppendLine("// ================================================"); - builder.AppendLine("// AUTO GENERATED"); - builder.AppendLine("// ================================================"); - builder.AppendLine("// This shader was created by ComputeSharp."); - builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); - - // Group size constants - builder.AppendLine(); - builder.Append("#define __GroupSize__get_X "); - builder.AppendLine(threadsX.ToString()); - builder.Append("#define __GroupSize__get_Y "); - builder.AppendLine(threadsY.ToString()); - builder.Append("#define __GroupSize__get_Z "); - builder.AppendLine(threadsZ.ToString()); - - // Define declarations - foreach (var define in info.DefinesInfo) - { - builder.Append("#define "); - builder.Append(define.Key); - builder.Append(' '); - builder.AppendLine(define.Value); - } - - // Static fields - if (info.StaticFields.Count > 0) - { - builder.AppendLine(); - - foreach (var constant in info.StaticFields) - { - builder.Append(constant.Value.TypeDeclaration); - builder.Append(' '); - builder.Append(constant.Key); - - if (constant.Value.Assignment is string assignment) - { - builder.Append(" = "); - builder.Append(assignment); - } - - builder.AppendLine(";"); - } - } - - // Declared types - foreach (var type in info.DeclaredTypes) - { - builder.AppendLine(); - builder.AppendLine(type); - } - - // Captured variables - builder.AppendLine(); - builder.AppendLine("cbuffer _ : register(b0)"); - builder.AppendLine('{'); - builder.AppendLine(" uint __x;"); - builder.AppendLine(" uint __y;"); - - if (info.IsComputeShader) - { - builder.AppendLine(" uint __z;"); - } - - foreach (var local in info.FieldsInfo) - { - builder.Append(" "); - builder.Append(local.FieldType); - builder.Append(' '); - builder.Append(local.FieldName); - builder.AppendLine(';'); - } - - builder.AppendLine('}'); - - // Resources - foreach (var resource in info.HlslResourceInfo) - { - builder.AppendLine(); - - switch (resource) - { - // Constant buffer go to cbuffer fields with a dummy local - case HlslResourceInfo.Constant _: - builder.Append("cbuffer _"); - builder.Append(resource.FieldName); - builder.Append(" : register(b"); - builder.Append(resource.RegisterIndex.ToString()); - builder.AppendLine(')'); - builder.AppendLine('{'); - builder.Append(" "); - builder.Append(resource.FieldType); - builder.Append(' '); - builder.Append(resource.FieldName); - builder.AppendLine("[2];"); - builder.AppendLine('}'); - break; - - // Structured buffer have the same syntax but different id - case HlslResourceInfo.ReadOnly _: - char registerId = 't'; - goto StructuredBuffer; - case HlslResourceInfo.ReadWrite _: - registerId = 'u'; - StructuredBuffer: - builder.Append(resource.FieldType); - builder.Append(' '); - builder.Append(resource.FieldName); - builder.Append(" : register("); - builder.Append(registerId); - builder.Append(resource.RegisterIndex.ToString()); - builder.AppendLine(");"); - break; - - // Texture samplers - case HlslResourceInfo.Sampler _: - builder.Append(resource.FieldType); - builder.Append(' '); - builder.Append(resource.FieldName); - builder.Append(" : register("); - builder.Append('s'); - builder.Append(resource.RegisterIndex.ToString()); - builder.AppendLine(");"); - break; - } - } - - // Shared buffers - foreach (var buffer in info.SharedBuffers) - { - builder.AppendLine(); - builder.Append("groupshared "); - builder.Append(buffer.Value.Type); - builder.Append(' '); - builder.Append(buffer.Key); - builder.Append('['); - - if (buffer.Value.Count is int count) builder.Append(count.ToString()); - else builder.Append((threadsX * threadsY * threadsZ).ToString()); - - builder.AppendLine("];"); - } - - // Forward declarations - foreach (var declaration in info.ForwardDeclarations) - { - builder.AppendLine(); - builder.AppendLine(declaration); - } - - // Captured methods - foreach (var function in info.MethodsInfo) - { - builder.AppendLine(); - builder.AppendLine(function); - } - - // Entry point - builder.AppendLine(); - builder.AppendLine("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); - builder.AppendLine(info.EntryPoint); - - return builder; - } - } -} diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs deleted file mode 100644 index baf1f12c..00000000 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslFieldInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -#pragma warning disable CS1572, CS1573 - -namespace ComputeSharp.Shaders.Renderer.Models -{ - /// - /// A model that contains info on a shader field. - /// - /// The type of the current field in the HLSL shader. - /// The name to use for the current field. - internal record CapturedFieldInfo(string FieldType, string FieldName); -} diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs deleted file mode 100644 index af71a082..00000000 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace ComputeSharp.Shaders.Renderer.Models -{ - /// - /// A model that contains info on a shader resource field. - /// - /// The type of the current field in the HLSL shader. - /// The name to use for the current field. - /// The register index to bind the resource to. - internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex) - : CapturedFieldInfo(FieldType, FieldName) - { - /// - /// A model that represents a captured constant buffer in a shader. - /// - /// - public sealed record Constant(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured readonly typed resource in a shader. - /// Maps to either or . - /// - /// - public sealed record ReadOnly(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured writeable buffer in a shader. - /// Maps to either or . - /// - /// - public sealed record ReadWrite(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - - /// - /// A model that represents a captured sampler in a shader. - /// This resource type doesn't have a mapping to a public API. - /// - /// - public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex) - : HlslResourceInfo(FieldType, FieldName, RegisterIndex); - } -} diff --git a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs deleted file mode 100644 index ccbdc33f..00000000 --- a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Collections.Generic; -using ComputeSharp.Shaders.Renderer.Models; - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A responsible for loading and processing shaders of any type. - /// - internal interface IShaderLoader - { - /// - /// Gets the generated source code for the method in the current shader. - /// - string EntryPoint { get; } - - /// - /// Gets whether or not the current shader is a compute shader (and not a pixel shader). - /// - bool IsComputeShader { get; } - - /// - /// Gets the collection of items for the shader fields. - /// - IReadOnlyList HlslResourceInfo { get; } - - /// - /// Gets the collection of items for the shader fields. - /// - IReadOnlyList FieldsInfo { get; } - - /// - /// Gets the forward declarations for static methods. - /// - IReadOnlyCollection ForwardDeclarations { get; } - - /// - /// Gets the collection of methods to be used in the shader. - /// - IReadOnlyCollection MethodsInfo { get; } - - /// - /// Gets the collection of define declarations to be added to the shader. - /// - IReadOnlyDictionary DefinesInfo { get; } - - /// - /// Gets the collection of discovered static fields. - /// - IReadOnlyDictionary StaticFields { get; } - - /// - /// Gets the collection of declared types for the shader. - /// - IReadOnlyCollection DeclaredTypes { get; } - - /// - /// Gets the collection of discovered group shared buffers. - /// - IReadOnlyDictionary SharedBuffers { get; } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs b/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs deleted file mode 100644 index 90aae996..00000000 --- a/src/ComputeSharp/Shaders/Translation/Mappings/HlslKnownTypes.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Numerics; - -namespace ComputeSharp.Shaders.Mappings -{ - /// - /// A that contains and maps known HLSL type names to common .NET types. - /// - internal static class HlslKnownTypes - { - /// - /// The set of HLSL vector types. - /// - private static HashSet HlslMappedVectorTypes { get; } = new(new[] - { - typeof(Bool2), typeof(Bool3), typeof(Bool4), - typeof(Int2), typeof(Int3), typeof(Int4), - typeof(UInt2), typeof(UInt3), typeof(UInt4), - typeof(Float2), typeof(Float3), typeof(Float4), - typeof(Double2), typeof(Double3), typeof(Double4) - }); - - /// - /// The set of HLSL matrix types. - /// - private static HashSet HlslMappedMatrixTypes { get; } = new(new[] - { - typeof(Bool1x1), typeof(Bool1x2), typeof(Bool1x3), typeof(Bool1x4), - typeof(Bool2x1), typeof(Bool2x2), typeof(Bool2x3), typeof(Bool2x4), - typeof(Bool3x1), typeof(Bool3x2), typeof(Bool3x3), typeof(Bool3x4), - typeof(Bool4x1), typeof(Bool4x2), typeof(Bool4x3), typeof(Bool4x4), - typeof(Int1x1), typeof(Int1x2), typeof(Int1x3), typeof(Int1x4), - typeof(Int2x1), typeof(Int2x2), typeof(Int2x3), typeof(Int2x4), - typeof(Int3x1), typeof(Int3x2), typeof(Int3x3), typeof(Int3x4), - typeof(Int4x1), typeof(Int4x2), typeof(Int4x3), typeof(Int4x4), - typeof(UInt1x1), typeof(UInt1x2), typeof(UInt1x3), typeof(UInt1x4), - typeof(UInt2x1), typeof(UInt2x2), typeof(UInt2x3), typeof(UInt2x4), - typeof(UInt3x1), typeof(UInt3x2), typeof(UInt3x3), typeof(UInt3x4), - typeof(UInt4x1), typeof(UInt4x2), typeof(UInt4x3), typeof(UInt4x4), - typeof(Float1x1), typeof(Float1x2), typeof(Float1x3), typeof(Float1x4), - typeof(Float2x1), typeof(Float2x2), typeof(Float2x3), typeof(Float2x4), - typeof(Float3x1), typeof(Float3x2), typeof(Float3x3), typeof(Float3x4), - typeof(Float4x1), typeof(Float4x2), typeof(Float4x3), typeof(Float4x4), - typeof(Double1x1), typeof(Double1x2), typeof(Double1x3), typeof(Double1x4), - typeof(Double2x1), typeof(Double2x2), typeof(Double2x3), typeof(Double2x4), - typeof(Double3x1), typeof(Double3x2), typeof(Double3x3), typeof(Double3x4), - typeof(Double4x1), typeof(Double4x2), typeof(Double4x3), typeof(Double4x4) - }); - - /// - /// Checks whether or not the input type is a known scalar type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL scalar type. - [Pure] - public static bool IsKnownScalarType(Type type) => type == typeof(bool) || - type == typeof(Bool) || - type == typeof(int) || - type == typeof(uint) || - type == typeof(float) || - type == typeof(double); - - /// - /// Checks whether or not the input type is a known vector type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL vector type. - [Pure] - public static bool IsKnownVectorType(Type type) => HlslMappedVectorTypes.Contains(type) || - type == typeof(Vector2) || - type == typeof(Vector3) || - type == typeof(Vector4); - - /// - /// Checks whether or not the input type is a known matrix type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known HLSL matrix type. - [Pure] - public static bool IsKnownMatrixType(Type type) => HlslMappedMatrixTypes.Contains(type); - - /// - /// Checks whether or not the input type is a known buffer type. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a known buffer type. - [Pure] - public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) || - IsReadOnlyResourceType(type) || - IsReadWriteResourceType(type); - - /// - /// Checks whether or not the input type is a value. - /// - /// The input instance to check. - /// A indicating whether the input is in fact a instance. - [Pure] - public static bool IsConstantBufferType(Type type) => type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(ConstantBuffer<>); - - /// - /// Checks whether or not the input type is a known readonly resource type (buffer or texture). - /// - /// The input instance to check. - /// A indicating whether the input is a readonly resource type. - [Pure] - public static bool IsReadOnlyResourceType(Type type) - { - if (!type.IsGenericType) return false; - - Type genericType = type.GetGenericTypeDefinition(); - - return - genericType == typeof(ReadOnlyBuffer<>) || - genericType == typeof(ReadOnlyTexture2D<>) || - genericType == typeof(ReadOnlyTexture2D<,>) || - genericType == typeof(ReadOnlyTexture3D<>) || - genericType == typeof(ReadOnlyTexture3D<,>) || - genericType == typeof(IReadOnlyTexture2D<>) || - genericType == typeof(IReadOnlyTexture3D<>); - } - - /// - /// Checks whether or not the input type is a known writeable resource type (buffer or texture). - /// - /// The input instance to check. - /// A indicating whether the input is a writeable resource type. - [Pure] - public static bool IsReadWriteResourceType(Type type) - { - if (!type.IsGenericType) return false; - - Type genericType = type.GetGenericTypeDefinition(); - - return - genericType == typeof(ReadWriteBuffer<>) || - genericType == typeof(ReadWriteTexture2D<>) || - genericType == typeof(ReadWriteTexture2D<,>) || - genericType == typeof(ReadWriteTexture3D<>) || - genericType == typeof(ReadWriteTexture3D<,>) || - genericType == typeof(IReadWriteTexture2D<>) || - genericType == typeof(IReadWriteTexture3D<>); ; - } - } -} diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs deleted file mode 100644 index 51af97ba..00000000 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ /dev/null @@ -1,288 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Reflection; -using ComputeSharp.__Internals; -using ComputeSharp.Shaders.Mappings; -using ComputeSharp.Shaders.Renderer.Models; -using Microsoft.Toolkit.Diagnostics; -using TerraFX.Interop; -using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE; - -#pragma warning disable CS0419, CS0618, CS8618 - -namespace ComputeSharp.Shaders.Translation -{ - /// - /// A responsible for loading and processing shaders of a given type. - /// - /// The type of compute shader currently in use. - internal sealed partial class ShaderLoader : IShaderLoader - where T : struct, IShader - { - /// - /// The associated instance for the current shader type. - /// - private static readonly IComputeShaderSourceAttribute Attribute = IComputeShaderSourceAttribute.GetForType(); - - /// - /// The number of constant buffers to define in the shader. - /// - /// - /// This starts at 1 as there's always an initial constant buffer before user-defined ones, containing - /// the captured scalar and vector values as well as the iteration ranges for the shader dispatch. - /// - private uint constantBuffersCount = 1; - - /// - /// The number of readonly buffers to define in the shader. - /// - private uint readOnlyBuffersCount; - - /// - /// The number of read write buffers to define in the shader. - /// - private uint readWriteBuffersCount; - - /// - /// The number of samplers to define in the shader. - /// - private uint samplersCount; - - /// - /// The array of items that are required to load the captured values. - /// - private D3D12_DESCRIPTOR_RANGE1[] d3D12DescriptorRanges1; - - /// - /// The with the items for the shader fields. - /// - private readonly List hlslResourceInfo = new(); - - /// - /// The with the items for the shader fields. - /// - private readonly List fieldsInfo = new(); - - /// - /// The with the collected methods for the shader. - /// - private readonly List methodsInfo = new(); - - /// - /// The with the discovered define declarations for the shader. - /// - private readonly Dictionary definesInfo = new(); - - /// - /// The with the collected declared types for the shader. - /// - private readonly List declaredTypes = new(); - - /// - /// Creates a new instance. - /// - private ShaderLoader() - { - } - - /// - /// Gets the number of 32 bit constants in the root signature for the shader. - /// - public int D3D12Root32BitConstantsCount { get; private set; } - - /// - /// Gets a with the loaded items for the shader. - /// - public ReadOnlySpan D3D12DescriptorRanges1 - { - get => this.d3D12DescriptorRanges1; - } - - /// - public string EntryPoint { get; private set; } - - /// - public bool IsComputeShader { get; private set; } - - /// - /// Gets whether or not the current shader requires access to a static sampler. - /// - public bool IsStaticSamplerUsed { get; private set; } - - /// - public IReadOnlyList HlslResourceInfo => this.hlslResourceInfo; - - /// - public IReadOnlyList FieldsInfo => this.fieldsInfo; - - /// - public IReadOnlyCollection ForwardDeclarations { get; private set; } - - /// - public IReadOnlyCollection MethodsInfo => this.methodsInfo; - - /// - public IReadOnlyDictionary DefinesInfo => this.definesInfo; - - /// - public IReadOnlyCollection DeclaredTypes => this.declaredTypes; - - /// - public IReadOnlyDictionary StaticFields { get; private set; } - - /// - public IReadOnlyDictionary SharedBuffers { get; private set; } - - /// - /// Loads and processes an input shadeer. - /// - /// The instance to use to build the shader. - /// A new instance representing the input shader. - [Pure] - public static ShaderLoader Load(in T shader) - { - ShaderLoader @this = new(); - - @this.LoadMethodMetadata(); - - // Reading members through reflection requires an object parameter, so here we're just boxing - // the input shader once to avoid allocating it multiple times while processing the shader. - @this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader); - - return @this; - } - - /// - /// Loads the metadata info for the current shader. - /// - private void LoadMethodMetadata() - { - ForwardDeclarations = Attribute.ForwardDeclarations; - EntryPoint = Attribute.ExecuteMethod; - StaticFields = Attribute.StaticFields; - SharedBuffers = Attribute.SharedBuffers; - - this.declaredTypes.AddRange(Attribute.Types); - this.methodsInfo.AddRange(Attribute.Methods); - - foreach (var pair in Attribute.Defines) - { - this.definesInfo.Add(pair.Key, pair.Value); - } - - // Extract the computed count of 32 bit root constants to load - D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)typeof(T).GetMethod(nameof(IShader.LoadDispatchData))!.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; - } - - /// - /// Loads the fields info for the current shader being loaded. - /// - /// The boxed instance to use to build the shader. - /// The array of items that are required to load the captured values. - private D3D12_DESCRIPTOR_RANGE1[] LoadFieldsInfo(object shader) - { - IReadOnlyList shaderFields = typeof(T).GetFields( - BindingFlags.Instance | - BindingFlags.Public | - BindingFlags.NonPublic).ToArray(); - - List d3D12DescriptorRanges1 = new(); - - // Add the implicit texture descriptor if the shader is a pixel shader - foreach (Type interfaceType in typeof(T).GetInterfaces()) - { - if (interfaceType.IsGenericType && - interfaceType.GetGenericTypeDefinition() == typeof(IPixelShader<>)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - - (string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value; - - this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - - break; - } - } - - // Set the current shader type - IsComputeShader = d3D12DescriptorRanges1.Count == 0; - - // Ensure the shader has a valid number of captured resources - if (shaderFields.Count == 0 && d3D12DescriptorRanges1.Count == 0) - { - ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field"); - } - - // Add the implicit sampler descriptor if necessary - if (Attribute.ImplicitSamplerField is not null) - { - (string hlslType, string hlslName) = Attribute.ImplicitSamplerField!.Value; - - this.hlslResourceInfo.Add(new HlslResourceInfo.Sampler(hlslType, hlslName, (int)this.samplersCount++)); - - IsStaticSamplerUsed = true; - } - - // Inspect the captured fields - foreach (FieldInfo fieldInfo in shaderFields) - { - LoadFieldInfo(shader, fieldInfo, d3D12DescriptorRanges1); - } - - return d3D12DescriptorRanges1.ToArray(); - } - - /// - /// Loads a specified and adds it to the shader model. - /// - /// The boxed instance to use to build the shader. - /// The target to load. - /// The list of discovered values. - private void LoadFieldInfo(object shader, FieldInfo fieldInfo, List d3D12DescriptorRanges1) - { - Type fieldType = fieldInfo.FieldType; - (string hlslName, string hlslType) = Attribute.Fields[fieldInfo.Name]; - - if (HlslKnownTypes.IsConstantBufferType(fieldType)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount)); - - this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); - } - else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount)); - - this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); - } - else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) - { - d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - - this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); - } - else if (fieldInfo.GetValue(shader) is Delegate func) - { - Guard.IsTrue(func.Method.IsStatic, fieldInfo.Name, "Captured delegates must be pointing to static methods"); - - // Captured static delegates with a return type - var methodSource = ShaderMethodSourceAttribute.GetForDelegate(func); - - this.declaredTypes.AddRange(methodSource.Types); - this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName)); - this.methodsInfo.AddRange(methodSource.Methods); - - foreach (var pair in methodSource.Constants) - { - this.definesInfo[pair.Key] = pair.Value; - } - } - else - { - this.fieldsInfo.Add(new CapturedFieldInfo(hlslType, hlslName)); - } - } - } -} From 5fdee964dac46868a860ff9accdc242d0f2f07ac Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 16:39:39 +0200 Subject: [PATCH 18/37] Fixed shader dispatching with new architecture --- ...rGenerator.CreateLoadDispatchMetadataMethod.cs | 11 +++++++---- .../Dispatching/ShaderDispatchMetadataLoader.cs | 15 ++++++++------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 1e270776..c67767fe 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -35,7 +35,7 @@ namespace ComputeSharp.SourceGenerators .AddModifiers(Token(SyntaxKind.RefKeyword)) .WithType(IdentifierName("TMetadataLoader")), Parameter(Identifier("result")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) + .AddModifiers(Token(SyntaxKind.OutKeyword)) .WithType(IdentifierName(typeof(IntPtr).Name))) .AddConstraintClauses( TypeParameterConstraintClause(IdentifierName("TMetadataLoader")) @@ -74,7 +74,10 @@ namespace ComputeSharp.SourceGenerators ArrayRankSpecifier(SingletonSeparatedList( LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))); - // Span span1 = stackalloc ResourceDescriptor[]; + // Compute the total number of resources (discovered ones and the implicit target texture, if present) + int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0); + + // Span span1 = stackalloc ResourceDescriptor[]; yield return LocalDeclarationStatement( VariableDeclaration( @@ -87,12 +90,12 @@ namespace ComputeSharp.SourceGenerators ArrayType(IdentifierName("ResourceDescriptor")) .AddRankSpecifiers( ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(discoveredResources.Count)))))))))); + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))); // ref byte r0 = ref span0[0]; yield return LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) .AddVariables( VariableDeclarator(Identifier("r0")) .WithInitializer(EqualsValueClause( diff --git a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs index 77bedbe8..29986b2c 100644 --- a/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs +++ b/src/ComputeSharp/Shaders/Dispatching/ShaderDispatchMetadataLoader.cs @@ -31,16 +31,17 @@ namespace ComputeSharp.Shaders.Dispatching } /// - public void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result) + public unsafe void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result) { Guard.HasSizeEqualTo(serializedMetadata, 5, nameof(serializedMetadata)); - using ComPtr d3D12RootSignature = this.d3D12Device->CreateRootSignature( - MemoryMarshal.Read(serializedMetadata), - MemoryMarshal.Cast(resourceDescriptors), - MemoryMarshal.Read(serializedMetadata[4..])); - - result = *(IntPtr*)&d3D12RootSignature; + fixed (IntPtr* p = &result) + { + *(ComPtr*)p = this.d3D12Device->CreateRootSignature( + MemoryMarshal.Read(serializedMetadata), + MemoryMarshal.Cast(resourceDescriptors), + MemoryMarshal.Read(serializedMetadata[4..])); + } } } } From 56b0b758fa8fe369254445446aef8bf4a031edd2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 17:16:13 +0200 Subject: [PATCH 19/37] Changed ref kind for ArrayPoolStringBuilder type in IShader This will allow generated code to request an approximated target size from the shared buffer pool, and reduce or eliminate the number of times the target buffer needs to be resized while building the HLSL source --- ...derGenerator.CreateBuildHlslStringMethod.cs | 18 +++++++++++++++++- .../Interfaces/__Internals/IShader{TSelf}.cs | 4 ++-- .../Shaders/Interop/ReflectionServices.cs | 7 ++++--- .../__Internals/ArrayPoolStringBuilder.cs | 5 +++-- src/ComputeSharp/Shaders/ShaderRunner{T}.cs | 4 +--- 5 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 1e843687..632a49d2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -84,7 +84,7 @@ namespace ComputeSharp.SourceGenerators Identifier("BuildHlslString")) .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.ReadOnlyKeyword)) .AddParameterListParameters( - Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), + Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("ArrayPoolStringBuilder")), Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) @@ -463,6 +463,22 @@ namespace ComputeSharp.SourceGenerators IEnumerable processedMethods, string executeMethod) { + // builder = ArrayPoolStringBuilder.Create(1024); + yield return + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("builder"), + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("ArrayPoolStringBuilder"), + IdentifierName("Create"))) + .AddArgumentListArguments( + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(1024)))))); + // Header yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");"); diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs index e2bfda10..fee6f8aa 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader{TSelf}.cs @@ -48,12 +48,12 @@ namespace ComputeSharp.__Internals /// /// Builds the HLSL source code for the current shader instance. /// - /// The target instance to write the HLSL source to. + /// The resulting instance containing the HLSL source. /// 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. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] - void BuildHlslString(ref ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ); + void BuildHlslString(out ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ); } } diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs index 332654f8..4b8e7194 100644 --- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs @@ -102,11 +102,12 @@ namespace ComputeSharp.Interop private static unsafe void GetNonGenericShaderInfo(in T shader, out ShaderInfo shaderInfo) where T : struct, IShader { - ArrayPoolStringBuilder shaderSource = ArrayPoolStringBuilder.Create(); - - shader.BuildHlslString(ref shaderSource, 1, 1, 1); + shader.BuildHlslString(out ArrayPoolStringBuilder shaderSource, 1, 1, 1); using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan); + + shaderSource.Dispose(); + using ComPtr dxcUtils = default; Guid dxcLibraryClsid = FX.CLSID_DxcLibrary; diff --git a/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs index a7922b49..cda9f57a 100644 --- a/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs +++ b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs @@ -25,13 +25,14 @@ namespace ComputeSharp.__Internals /// /// Creates a new instance ready to use. /// + /// The size hint for the internal buffer to allocate. /// A new instance with default values. [Pure] - public static ArrayPoolStringBuilder Create() + public static ArrayPoolStringBuilder Create(int sizeHint) { ArrayPoolStringBuilder builder; - builder.array = ArrayPool.Shared.Rent(1024); + builder.array = ArrayPool.Shared.Rent(sizeHint); builder.index = 0; return builder; diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index 15a0c699..9fdcf83f 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -237,9 +237,7 @@ namespace ComputeSharp.Shaders [MethodImpl(MethodImplOptions.NoInlining)] private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, in T shader, out CachedShader shaderData) { - ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(); - - shader.BuildHlslString(ref builder, threadsX, threadsY, threadsZ); + shader.BuildHlslString(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ); using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan); From 8a764c36de4f923039aa6657c4cf020929866a3f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 17:36:38 +0200 Subject: [PATCH 20/37] Optimized HLSL source building with target size hint --- ...erGenerator.CreateBuildHlslStringMethod.cs | 345 ++++++++++-------- 1 file changed, 187 insertions(+), 158 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 632a49d2..11c37b53 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -463,8 +463,191 @@ namespace ComputeSharp.SourceGenerators IEnumerable processedMethods, string executeMethod) { - // builder = ArrayPoolStringBuilder.Create(1024); - yield return + List statements = new(); + int sizeHint = 64; + + void AppendLF() + { + statements.Add(ParseStatement("builder.AppendLine();")); + sizeHint += 1; + } + + void AppendLine(string text) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); + sizeHint += text.Length; + } + + void AppendLineAndLF(string text) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); + sizeHint += text.Length + 1; + } + + void AppendCharacterAndLF(char c) + { + statements.Add(ParseStatement($"builder.AppendLine('{c}');")); + sizeHint += 2; + } + + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + + // Group size constants + AppendLF(); + AppendLine("#define __GroupSize__get_X "); + statements.Add(ParseStatement("builder.AppendLine(threadsX.ToString());")); + AppendLine("#define __GroupSize__get_Y "); + statements.Add(ParseStatement("builder.AppendLine(threadsY.ToString());")); + AppendLine("#define __GroupSize__get_Z "); + statements.Add(ParseStatement("builder.AppendLine(threadsZ.ToString());")); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + AppendLineAndLF($"#define {name} {value}"); + } + + // Static fields + if (staticFields.Any()) + { + AppendLF(); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + } + else + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + } + } + } + + // Declared types + foreach (var type in declaredTypes) + { + AppendLF(); + AppendLineAndLF(type); + } + + // Captured variables + AppendLF(); + AppendLineAndLF("cbuffer _ : register(b0)"); + AppendCharacterAndLF('{'); + AppendLineAndLF(" uint __x;"); + AppendLineAndLF(" uint __y;"); + + if (isComputeShader) + { + AppendLineAndLF(" uint __z;"); + } + + // User-defined values + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + if (fieldSymbol.Type.IsUnmanagedType) + { + AppendLineAndLF($" {fieldType} {fieldName};"); + } + } + + AppendCharacterAndLF('}'); + + int + constantBuffersCount = 0, + readOnlyBuffersCount = 0, + readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + AppendLF(); + AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); + } + + // Optional sampler field + if (isSamplerUsed) + { + AppendLF(); + AppendLineAndLF("SamplerState __sampler : register(s);"); + } + + // Resources + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + string metadataName = fieldSymbol.GetFullMetadataName(); + + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); + AppendCharacterAndLF('{'); + AppendLineAndLF($" {fieldType} {fieldName}[2];"); + AppendCharacterAndLF('}'); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} : register(t{readOnlyBuffersCount++});"); + } + else if (HlslKnownTypes.IsTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} : register(u{readWriteBuffersCount++});"); + } + } + + // Shared buffers + foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + { + object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + + AppendLF(); + AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); + } + + // Forward declarations + if (forwardDeclarations is not null) + { + foreach (var forwardDeclaration in forwardDeclarations) + { + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + } + + // Captured methods + if (processedMethods is not null) + { + foreach (var method in processedMethods) + { + AppendLF(); + AppendLineAndLF(method); + } + } + + // Entry point + AppendLF(); + AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); + AppendLineAndLF(executeMethod); + + // builder = ArrayPoolStringBuilder.Create(); + statements.Insert(0, ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, @@ -477,163 +660,9 @@ namespace ComputeSharp.SourceGenerators .AddArgumentListArguments( Argument(LiteralExpression( SyntaxKind.NumericLiteralExpression, - Literal(1024)))))); + Literal(sizeHint))))))); - // Header - yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); - yield return ParseStatement("builder.AppendLine(\"// AUTO GENERATED\");"); - yield return ParseStatement("builder.AppendLine(\"// ================================================\");"); - yield return ParseStatement("builder.AppendLine(\"// This shader was created by ComputeSharp.\");"); - yield return ParseStatement("builder.AppendLine(\"// See: https://github.com/Sergio0694/ComputeSharp.\");"); - - // Group size constants - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.Append(\"#define __GroupSize__get_X \");"); - yield return ParseStatement("builder.AppendLine(threadsX.ToString());"); - yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Y \");"); - yield return ParseStatement("builder.AppendLine(threadsY.ToString());"); - yield return ParseStatement("builder.Append(\"#define __GroupSize__get_Z \");"); - yield return ParseStatement("builder.AppendLine(threadsZ.ToString());"); - - // Define declarations - foreach (var (name, value) in definedConstants) - { - yield return ParseStatement($"builder.AppendLine(\"#define {name} {value}\");"); - } - - // Static fields - if (staticFields.Any()) - { - yield return ParseStatement("builder.AppendLine();"); - - foreach (var field in staticFields) - { - if (field.Assignment is string assignment) - { - yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name} = {assignment};\");"); - } - else - { - yield return ParseStatement($"builder.AppendLine(\"{field.TypeDeclaration} {field.Name};\");"); - } - } - } - - // Declared types - foreach (var type in declaredTypes) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{type}\");"); - } - - // Captured variables - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.AppendLine(\"cbuffer _ : register(b0)\");"); - yield return ParseStatement("builder.AppendLine('{');"); - yield return ParseStatement("builder.AppendLine(\" uint __x;\");"); - yield return ParseStatement("builder.AppendLine(\" uint __y;\");"); - - if (isComputeShader) - { - yield return ParseStatement("builder.AppendLine(\" uint __z;\");"); - } - - // User-defined values - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) - { - if (fieldSymbol.Type.IsUnmanagedType) - { - yield return ParseStatement($"builder.AppendLine(\" {fieldType} {fieldName};\");"); - } - } - - yield return ParseStatement("builder.AppendLine('}');"); - - int - constantBuffersCount = 0, - readOnlyBuffersCount = 0, - readWriteBuffersCount = 0; - - // Optional implicit texture field - if (!isComputeShader) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});\");"); - } - - // Optional sampler field - if (isSamplerUsed) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.AppendLine(\"SamplerState __sampler : register(s);\");"); - } - - // Resources - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) - { - string metadataName = fieldSymbol.GetFullMetadataName(); - - if (HlslKnownTypes.IsConstantBufferType(metadataName)) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"cbuffer _{fieldName} : register(b{constantBuffersCount++})\");"); - yield return ParseStatement("builder.AppendLine('{');"); - yield return ParseStatement($"builder.AppendLine(\" {fieldType} {fieldName}[2];\");"); - yield return ParseStatement("builder.AppendLine('}');"); - } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{fieldType} : register(t{readOnlyBuffersCount++});\");"); - } - else if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{fieldType} : register(u{readWriteBuffersCount++});\");"); - } - } - - // Shared buffers - foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) - { - object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; - - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"groupshared {bufferType} {bufferName} [{count}];\");"); - } - - // Forward declarations - if (forwardDeclarations is not null) - { - foreach (var forwardDeclaration in forwardDeclarations) - { - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement($"builder.AppendLine(\"{forwardDeclaration}\");"); - } - } - - // Captured methods - if (processedMethods is not null) - { - foreach (var method in processedMethods) - { - yield return ParseStatement("builder.AppendLine();"); - yield return - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(method))))); - } - } - - // Entry point - yield return ParseStatement("builder.AppendLine();"); - yield return ParseStatement("builder.AppendLine(\"[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]\");"); - yield return - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(executeMethod))))); + return statements; } } } From 13ef2009e8ef03a14edd51875247fe5d81cba87f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 17:42:19 +0200 Subject: [PATCH 21/37] Added missing XML docs --- ...ShaderGenerator.CreateBuildHlslStringMethod.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 11c37b53..eb28a312 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -450,6 +450,21 @@ namespace ComputeSharp.SourceGenerators } } + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The sequence of defined constants for the shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of declared types used by the shader. + /// Whether or not the current shader is a compute shader (or a pixel shader). + /// The sequence of instance fields for the current shader. + /// The type of the implicit target texture, if present. + /// Whether the static sampler is used by the shader. + /// The sequence of shared buffers declared by the shader. + /// The sequence of forward method declarations. + /// The sequence of processed methods used by the shader. + /// The body of the entry point of the shader. + /// The series of statements to build the HLSL source to compile to execute the current shader. private static IEnumerable GenerateRenderMethodBody( IEnumerable<(string Name, string Value)> definedConstants, IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, From 2e1bb04f8ce6ea282f6b3c5e0d7687890c162a8d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 17:47:25 +0200 Subject: [PATCH 22/37] Fixed HLSL source processing of captured resources --- .../IShaderGenerator.CreateBuildHlslStringMethod.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index eb28a312..ac3fc698 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -605,7 +605,7 @@ namespace ComputeSharp.SourceGenerators // Resources foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) { - string metadataName = fieldSymbol.GetFullMetadataName(); + string metadataName = fieldSymbol.Type.GetFullMetadataName(); if (HlslKnownTypes.IsConstantBufferType(metadataName)) { @@ -618,12 +618,12 @@ namespace ComputeSharp.SourceGenerators else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) { AppendLF(); - AppendLineAndLF($"{fieldType} : register(t{readOnlyBuffersCount++});"); + AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); } else if (HlslKnownTypes.IsTypedResourceType(metadataName)) { AppendLF(); - AppendLineAndLF($"{fieldType} : register(u{readWriteBuffersCount++});"); + AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); } } From 10c07851cbf7217ee004c59daa202c2cb819a1fd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 21:52:43 +0200 Subject: [PATCH 23/37] Fixed a build error in internal tests --- .../ShaderDataLoaderTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs index fa391b6c..6626ef2e 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderDataLoaderTests.cs @@ -26,7 +26,7 @@ namespace ComputeSharp.Tests.Internals DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - new CapturedResourceShader(buffer).LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + new CapturedResourceShader(buffer).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); Assert.AreEqual(3, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -59,7 +59,7 @@ namespace ComputeSharp.Tests.Internals DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77).LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + new MultipleResourcesAndPrimitivesShader(buffer0, buffer1, 1, 22, 77).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); Assert.AreEqual(6, dataLoader.Values.Length); Assert.AreEqual(2, dataLoader.Resources.Length); @@ -98,7 +98,7 @@ namespace ComputeSharp.Tests.Internals DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); ScalarAndVectorTypesShader shader = new(buffer, new(55, 44, 888), 22, 77, new(3.14, 6.28), 42, 9999); - shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); Assert.AreEqual(18, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -160,7 +160,7 @@ namespace ComputeSharp.Tests.Internals i2x2: new(11, 22, 33, 44), d: 9999); - shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); Assert.AreEqual(31, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -240,7 +240,7 @@ namespace ComputeSharp.Tests.Internals i2x2: new(11, 22, 33, 44), d: 9999)); - shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); Assert.AreEqual(31, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -344,7 +344,7 @@ namespace ComputeSharp.Tests.Internals a: 888888, b: new(333.3f, 444.4f)))); - shader.LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + shader.LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); Assert.AreEqual(47, dataLoader.Values.Length); Assert.AreEqual(1, dataLoader.Resources.Length); @@ -425,7 +425,7 @@ namespace ComputeSharp.Tests.Internals DebugDispatchDataLoader dataLoader = DebugDispatchDataLoader.Create(); - new AmbiguousNamesShader(a, b, c, x, y, z, 7777, 8888, 9999).LoadDispatchData(in dataLoader, Gpu.Default, 111, 222, 333); + new AmbiguousNamesShader(a, b, c, x, y, z, 7777, 8888, 9999).LoadDispatchData(ref dataLoader, Gpu.Default, 111, 222, 333); Assert.AreEqual(6, dataLoader.Values.Length); Assert.AreEqual(6, dataLoader.Resources.Length); From 632cd6faf5078bd7798236290fd0b1a235b583bd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 22:27:15 +0200 Subject: [PATCH 24/37] Fixed constant buffers registration in HLSL source --- .../IShaderGenerator.CreateBuildHlslStringMethod.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index ac3fc698..c5cad728 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -584,7 +584,7 @@ namespace ComputeSharp.SourceGenerators AppendCharacterAndLF('}'); int - constantBuffersCount = 0, + constantBuffersCount = 1, readOnlyBuffersCount = 0, readWriteBuffersCount = 0; From 6fbcf21f74fc24b237e383ba36e8bb0c209fa32c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 10 Jul 2021 23:17:26 +0200 Subject: [PATCH 25/37] Switched source generated files to only use LF line endings --- .../AutoConstructorGenerator.cs | 2 +- ...derGenerator.CreateBuildHlslStringMethod.cs | 18 +++++++++--------- .../IShaderGenerator.cs | 2 +- .../ShaderMethodSourceGenerator.cs | 6 +++--- .../SyntaxRewriters/ShaderSourceRewriter.cs | 2 +- .../AutoConstructorGeneratorTests.cs | 6 +++--- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index 395f1b22..8d31d254 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -101,7 +101,7 @@ namespace ComputeSharp.SourceGenerators var source = CompilationUnit().AddMembers( NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)) - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .ToFullString(); // Add the partial type diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index c5cad728..05a12ef3 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -228,7 +228,7 @@ namespace ComputeSharp.SourceGenerators constantDefinitions, context); - string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace().ToFullString(); + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); } @@ -350,8 +350,8 @@ namespace ComputeSharp.SourceGenerators // Emit the extracted local functions first foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); - declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace().ToFullString()); + methods.Add(localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()); + declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); } // If the method is the shader entry point, do additional processing @@ -363,20 +363,20 @@ namespace ComputeSharp.SourceGenerators false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! }; - entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); + entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); } else { - methods.Add(processedMethod.NormalizeWhitespace().ToFullString()); - declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace().ToFullString()); + methods.Add(processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()); + declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); } } // Process static methods as well foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) { - methods.Add(staticMethod.NormalizeWhitespace().ToFullString()); - declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString()); + methods.Add(staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()); + declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); } return (entryPoint!, methods, declarations, isSamplerUsed); @@ -431,7 +431,7 @@ namespace ComputeSharp.SourceGenerators // Insert the trailing ; right after the closing bracket (after normalization) yield return structDeclaration - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) .ToFullString(); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 56e71574..23d30bbd 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -150,7 +150,7 @@ namespace ComputeSharp.SourceGenerators UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .ToFullString(); // Add the method source attribute diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 573afef0..d73d1d92 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -87,7 +87,7 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(NestedArrayExpression(Array.Empty()))))) // TODO .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .ToFullString(); // Add the method source attribute @@ -120,7 +120,7 @@ namespace ComputeSharp.SourceGenerators .Visit(methodDeclaration)! .WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)) .WithoutTrivia() - .NormalizeWhitespace() + .NormalizeWhitespace(eol: "\n") .ToFullString(); List localFunctions = new(shaderSourceRewriter.LocalFunctions.Count); @@ -128,7 +128,7 @@ namespace ComputeSharp.SourceGenerators // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - localFunctions.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); + localFunctions.Add(localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()); } return (targetMethod, localFunctions); diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 43fe3386..cd0c7d32 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -406,7 +406,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context); MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(), - processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia(); + processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia(); this.staticMethods.Add(method, processedMethod.WithIdentifier(Identifier(methodIdentifier))); } diff --git a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs index 1e46d676..92a4e006 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs @@ -75,7 +75,7 @@ namespace ComputeSharp.Tests.SourceGenerators /// The input source to process. /// The target index to check in the resulting output. /// The expected body to compare with the generated code. - private void VerifyGeneratedMethodLines(string source, int index, string expectedBody) + private static void VerifyGeneratedMethodLines(string source, int index, string expectedBody) where TGenerator : class, ISourceGenerator, new() { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); @@ -97,8 +97,8 @@ namespace ComputeSharp.Tests.SourceGenerators string outputBody = outputCompilation.SyntaxTrees.Skip(index + 1).First().ToString(); string[] - outputLines = outputBody.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), - expectedLines = expectedBody.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + outputLines = outputBody.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), + expectedLines = expectedBody.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); Assert.AreEqual(expectedLines.Length, outputLines.Length); From f2c1b79b6af51fc4fc25b26d1b46f1f196f9e990 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 12 Jul 2021 17:42:24 +0200 Subject: [PATCH 26/37] Restored code generation for [ShaderMethod] attribute --- .../Helpers/SyntaxFactoryHelper.cs | 16 +++++++++------- .../ShaderMethodSourceGenerator.cs | 5 ++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs index e90839c0..b6e7c5d0 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -39,14 +39,14 @@ namespace ComputeSharp.SourceGenerators.Helpers /// /// That it, it applies the following transformation: /// - /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } } + /// { ("K1", "V1", I1), ("K2", "V2", null) } => new object[] { new object[] { "K1", "V1", I1 }, new object[] { "K2", "V2", null } } /// /// /// /// The input sequence of groups. /// An instance with the described contents. [Pure] - public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable> groups) + public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups) { return ArrayCreationExpression( @@ -54,11 +54,13 @@ namespace ComputeSharp.SourceGenerators.Helpers .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(groups.Select(static group => - ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( - group.Select(static item => item is null - ? LiteralExpression(SyntaxKind.NullLiteralExpression) - : LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))) - .ToArray()))).ToArray())); + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)), + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray())); } /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index d73d1d92..c3507627 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; @@ -84,7 +83,7 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), AttributeArgument(ArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(Array.Empty()))))) // TODO + AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace(eol: "\n") From ce5e9703cd4df5183acf17a9309f169098fa9b26 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 12 Jul 2021 20:21:56 +0200 Subject: [PATCH 27/37] Enabled initial support for shader metaprogramming --- .../ComputeSharp.SourceGenerators.csproj | 1 - ...erGenerator.CreateBuildHlslStringMethod.cs | 58 +++++++-- .../ShaderMethodSourceGenerator.cs | 6 +- .../ShaderMethodSourceAttribute.cs | 30 +++-- .../MissingMethodSourceException.cs | 53 -------- .../Core/Extensions/MethodInfoExtensions.cs | 4 +- .../MetaprogrammingTests.cs | 115 ++++++++++++++++++ 7 files changed, 189 insertions(+), 78 deletions(-) delete mode 100644 src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs create mode 100644 tests/ComputeSharp.Tests/MetaprogrammingTests.cs diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 52e8f25f..a621a6da 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -22,7 +22,6 @@ - diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 05a12ef3..885fc970 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; +using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Helpers; @@ -14,6 +15,8 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; +#pragma warning disable CS0618 + namespace ComputeSharp.SourceGenerators { /// @@ -404,7 +407,7 @@ namespace ComputeSharp.SourceGenerators /// /// The sequence of discovered custom types. /// A sequence of custom type definitions to add to the shader source. - internal static IEnumerable GetProcessedTypes(IEnumerable types) + internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable types) { foreach (var type in HlslKnownTypes.GetCustomTypes(types)) { @@ -430,10 +433,11 @@ namespace ComputeSharp.SourceGenerators // Insert the trailing ; right after the closing bracket (after normalization) yield return - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString(); + (structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString()); } } @@ -468,7 +472,7 @@ namespace ComputeSharp.SourceGenerators private static IEnumerable GenerateRenderMethodBody( IEnumerable<(string Name, string Value)> definedConstants, IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - IEnumerable declaredTypes, + IEnumerable<(string Name, string Definition)> declaredTypes, bool isComputeShader, IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, string? implicitTextureType, @@ -479,6 +483,32 @@ namespace ComputeSharp.SourceGenerators string executeMethod) { List statements = new(); + int capturedDelegates = 0; + + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) + { + // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + } + } + int sizeHint = 64; void AppendLF() @@ -554,10 +584,10 @@ namespace ComputeSharp.SourceGenerators } // Declared types - foreach (var type in declaredTypes) + foreach (var (typeName, typeDefinition) in declaredTypes) { AppendLF(); - AppendLineAndLF(type); + AppendLineAndLF(typeDefinition); } // Captured variables @@ -656,13 +686,23 @@ namespace ComputeSharp.SourceGenerators } } + // Captured delegate methods + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) + { + AppendLF(); + statements.Add(ParseStatement($"builder.AppendLine(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));")); + } + } + // Entry point AppendLF(); AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); AppendLineAndLF(executeMethod); // builder = ArrayPoolStringBuilder.Create(); - statements.Insert(0, + statements.Insert(capturedDelegates, ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index c3507627..e3f91e72 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -70,7 +70,7 @@ namespace ComputeSharp.SourceGenerators Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); + var (invokeMethod, localFunctions) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions); @@ -80,9 +80,9 @@ namespace ComputeSharp.SourceGenerators AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), - AttributeArgument(ArrayExpression(processedTypes)), + AttributeArgument(NestedArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(ArrayExpression(processedMethods)), + AttributeArgument(ArrayExpression(localFunctions)), AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 8d0bbce3..703e9c9a 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -5,7 +5,6 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using ComputeSharp.Core.Extensions; -using ComputeSharp.Exceptions; namespace ComputeSharp.__Internals { @@ -37,12 +36,12 @@ namespace ComputeSharp.__Internals /// The source code for the target entry point method. /// The collection of processed methods. /// The collection of discovered constants. - public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants) + public ShaderMethodSourceAttribute(string methodName, object[] types, string invokeMethod, string[] methods, object[] constants) { this.invokeMethod = invokeMethod; MethodName = methodName; - Types = types; + Types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); Methods = methods; Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } @@ -55,7 +54,7 @@ namespace ComputeSharp.__Internals /// /// Gets the collection of processed custom types. /// - internal IReadOnlyCollection Types { get; } + internal IReadOnlyDictionary Types { get; } /// /// Gets the collection of processed methods. @@ -73,7 +72,7 @@ namespace ComputeSharp.__Internals /// The name to bind the method to. /// The mapped source code for the current mehtod. [Pure] - internal string GetMappedInvokeMethod(string name) + public string GetMappedInvokeMethod(string name) { return this.invokeMethod.Replace(InvokeMethodIdentifier, name); } @@ -82,13 +81,14 @@ namespace ComputeSharp.__Internals /// Gets the associated instance for a specified delegate. /// /// The input instance to get info for. + /// The name of the shader field containing . /// The associated instance for the given delegate. [Pure] - internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function) + public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name) { if (!function.Method.IsStatic) { - ThrowArgumentExceptionForNonStaticShader(); + return ThrowArgumentExceptionForNonStaticMethod(name); } var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes(); @@ -102,15 +102,25 @@ namespace ComputeSharp.__Internals } } - return MissingMethodSourceException.Throw(function); + return ThrowArgumentExceptionForMissingShaderMethodAttribute(name); } /// /// Throws an when a given is not static. /// - private static void ThrowArgumentExceptionForNonStaticShader() + /// The name of the shader field containing the invalid method. + private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name) { - throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function"); + throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name); + } + + /// + /// Throws an when a given doesn't have applied to it. + /// + /// The name of the shader field containing the invalid method. + private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name) + { + throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name); } } } \ No newline at end of file diff --git a/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs b/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs deleted file mode 100644 index c31a043b..00000000 --- a/src/ComputeSharp/Core/Exceptions/MissingMethodSourceException.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Diagnostics.Contracts; -using System.Text; -using ComputeSharp.__Internals; -using ComputeSharp.Core.Extensions; - -#pragma warning disable CS0618 - -namespace ComputeSharp.Exceptions -{ - /// - /// A custom that indicates when an HLSL-only API is called from C# - /// - public sealed class MissingMethodSourceException : InvalidOperationException - { - /// - /// Creates a new instance. - /// - /// The exception message to display. - private MissingMethodSourceException(string message) - : base(message) - { - } - - /// - /// Creates a new instance from the specified parameters. - /// - /// The target that couldn't be processed. - /// A new instance with a formatted error message. - [Pure] - private static MissingMethodSourceException Create(Delegate method) - { - StringBuilder builder = new(512); - - builder.AppendLine("The processed source for a method captured as a delegate in a shader was not found."); - builder.AppendLine($"The delegate was of type {method.GetType()} and it was wrapping the method {method.Method.GetFullName()}."); - builder.Append($"Make sure that the target method is annotated with [{nameof(ShaderMethodAttribute)}]."); - builder.ToString(); - - return new(builder.ToString()); - } - - /// - /// Throws a new for a given delegate. - /// - /// The target that couldn't be processed. - /// This method always throws and never actually returns anything. - internal static ShaderMethodSourceAttribute Throw(Delegate method) - { - throw Create(method); - } - } -} diff --git a/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs b/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs index b413e1b3..fbff690b 100644 --- a/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs +++ b/src/ComputeSharp/Core/Extensions/MethodInfoExtensions.cs @@ -23,10 +23,10 @@ namespace ComputeSharp.Core.Extensions { var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName)); - return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})"; + return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}<{arguments}>({parameters})"; } - return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})"; + return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}({parameters})"; } } } diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs new file mode 100644 index 00000000..71d5bc4f --- /dev/null +++ b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs @@ -0,0 +1,115 @@ +using System; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#pragma warning disable IDE0062 + +namespace ComputeSharp.Tests +{ + [TestClass] + [TestCategory("Metaprogramming")] + public partial class MetaprogrammingTests + { + [AutoConstructor] + internal readonly partial struct ActivationWithDelegateShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = activation(ThreadIds.X); + } + } + + public static class Activations + { + [ShaderMethod] + public static int Square(int x) => x * x; + + [ShaderMethod] + public static int AddOne(int x) => x + 1; + + // Missing attribute + public static int Identity(int x) => x; + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void ActivationWithDelegate(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Square)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.Square(i)); + } + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.AddOne)); + + result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(i)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(ArgumentException))] + public unsafe void DelegateWithMissingAttributeOnMethod(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Identity)); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(ArgumentException))] + public unsafe void DelegateWrappingNonStaticMethod(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + [ShaderMethod] + int Dummy(int x) => x; + + device.Get().For(100, new ActivationWithDelegateShader(buffer, Dummy)); + } + + [AutoConstructor] + internal readonly partial struct ActivationWithMultipleDelegatesShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func f1; + public readonly Func f2; + + public void Execute() + { + buffer[ThreadIds.X] = f2(f1(ThreadIds.X)); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void ActivationWithMultipleDelegates(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new ActivationWithMultipleDelegatesShader(buffer, Activations.Square, Activations.AddOne)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i))); + } + } + } +} From b0db306f57a5f2e0403b76b0fe820591a36d751d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 12 Jul 2021 22:03:32 +0200 Subject: [PATCH 28/37] Aggregated HLSL source building statements --- ...erGenerator.CreateBuildHlslStringMethod.cs | 57 ++++++++++++------- 1 file changed, 37 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 885fc970..7d74cc11 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; +using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; @@ -483,6 +484,7 @@ namespace ComputeSharp.SourceGenerators string executeMethod) { List statements = new(); + StringBuilder textBuilder = new(); int capturedDelegates = 0; foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) @@ -513,34 +515,47 @@ namespace ComputeSharp.SourceGenerators void AppendLF() { - statements.Add(ParseStatement("builder.AppendLine();")); - sizeHint += 1; + textBuilder.Append('\n'); } void AppendLine(string text) { - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); - sizeHint += text.Length; + textBuilder.Append(text); } void AppendLineAndLF(string text) { - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("AppendLine"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); - sizeHint += text.Length + 1; + textBuilder.Append(text); + textBuilder.Append('\n'); } void AppendCharacterAndLF(char c) { - statements.Add(ParseStatement($"builder.AppendLine('{c}');")); - sizeHint += 2; + textBuilder.Append(c); + textBuilder.Append('\n'); + } + + void AppendStatement(string text) + { + FlushText(); + + statements.Add(ParseStatement(text)); + } + + void FlushText() + { + if (textBuilder.Length > 0) + { + sizeHint += textBuilder.Length; + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(textBuilder.ToString())))))); + + textBuilder.Clear(); + } } // Header @@ -553,11 +568,11 @@ namespace ComputeSharp.SourceGenerators // Group size constants AppendLF(); AppendLine("#define __GroupSize__get_X "); - statements.Add(ParseStatement("builder.AppendLine(threadsX.ToString());")); + AppendStatement("builder.AppendLine(threadsX.ToString());"); AppendLine("#define __GroupSize__get_Y "); - statements.Add(ParseStatement("builder.AppendLine(threadsY.ToString());")); + AppendStatement("builder.AppendLine(threadsY.ToString());"); AppendLine("#define __GroupSize__get_Z "); - statements.Add(ParseStatement("builder.AppendLine(threadsZ.ToString());")); + AppendStatement("builder.AppendLine(threadsZ.ToString());"); // Define declarations foreach (var (name, value) in definedConstants) @@ -692,7 +707,7 @@ namespace ComputeSharp.SourceGenerators if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) { AppendLF(); - statements.Add(ParseStatement($"builder.AppendLine(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));")); + AppendStatement($"builder.AppendLine(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));"); } } @@ -701,6 +716,8 @@ namespace ComputeSharp.SourceGenerators AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); AppendLineAndLF(executeMethod); + FlushText(); + // builder = ArrayPoolStringBuilder.Create(); statements.Insert(capturedDelegates, ExpressionStatement( From c40bdf0a267b20e3cb4ffe25e1ccc6ae80d5696a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 12 Jul 2021 22:12:37 +0200 Subject: [PATCH 29/37] Remove unnecessary ArrayPoolStringBuilder public methods --- ...erGenerator.CreateBuildHlslStringMethod.cs | 58 +++++++++---------- .../__Internals/ArrayPoolStringBuilder.cs | 49 +++------------- 2 files changed, 37 insertions(+), 70 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 7d74cc11..f59ea44d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -486,31 +486,6 @@ namespace ComputeSharp.SourceGenerators List statements = new(); StringBuilder textBuilder = new(); int capturedDelegates = 0; - - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) - { - if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) - { - // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ShaderMethodSourceAttribute)), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - - capturedDelegates++; - } - } - int sizeHint = 64; void AppendLF() @@ -558,6 +533,31 @@ namespace ComputeSharp.SourceGenerators } } + // Go through all existing delegate fields, if any + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + { + if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) + { + // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + } + } + // Header AppendLineAndLF("// ================================================"); AppendLineAndLF("// AUTO GENERATED"); @@ -568,11 +568,11 @@ namespace ComputeSharp.SourceGenerators // Group size constants AppendLF(); AppendLine("#define __GroupSize__get_X "); - AppendStatement("builder.AppendLine(threadsX.ToString());"); + AppendStatement("builder.Append(threadsX);"); AppendLine("#define __GroupSize__get_Y "); - AppendStatement("builder.AppendLine(threadsY.ToString());"); + AppendStatement("builder.Append(threadsY);"); AppendLine("#define __GroupSize__get_Z "); - AppendStatement("builder.AppendLine(threadsZ.ToString());"); + AppendStatement("builder.Append(threadsZ);"); // Define declarations foreach (var (name, value) in definedConstants) @@ -707,7 +707,7 @@ namespace ComputeSharp.SourceGenerators if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) { AppendLF(); - AppendStatement($"builder.AppendLine(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));"); + AppendStatement($"builder.Append(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));"); } } diff --git a/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs index cda9f57a..b5f1069e 100644 --- a/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs +++ b/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs @@ -1,5 +1,6 @@ using System; using System.Buffers; +using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; @@ -9,6 +10,8 @@ namespace ComputeSharp.__Internals /// /// A helper type that implements a pooled buffer writer for values. /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This type is not intended to be used directly by user code")] [DebuggerTypeProxy(typeof(DebugView))] public ref struct ArrayPoolStringBuilder { @@ -59,49 +62,13 @@ namespace ComputeSharp.__Internals } /// - /// Appends a character to the current buffer. + /// Appends the text representation of the input value to the current buffer. /// - public void Append(char character) + /// The input value to write. + public void Append(int value) { - EnsureCapacity(1); - - this.array[this.index++] = character; - } - - /// - /// Appends the input sequence of characters to the current buffer, with a trailing new line. - /// - /// The input characters to write. - public void AppendLine(string value) - { - EnsureCapacity(value.Length + 1); - - value.AsSpan().CopyTo(this.array.AsSpan(this.index)); - - this.index += value.Length; - - this.array[this.index++] = '\n'; - } - - /// - /// Appends a character and a new line to the current buffer. - /// - public void AppendLine(char character) - { - EnsureCapacity(2); - - this.array[this.index++] = character; - this.array[this.index++] = '\n'; - } - - /// - /// Appends a new line to the current buffer. - /// - public void AppendLine() - { - EnsureCapacity(1); - - this.array[this.index++] = '\n'; + // TODO: switch to ISpanFormattable on .NET 6 + Append(value.ToString()); } /// From 9a3a33298fdbfe2410f3425ffca361bac3391ca7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 12 Jul 2021 22:20:07 +0200 Subject: [PATCH 30/37] Minor code refactoring, removed unnecessary attributes --- .../__Internals/IDispatchDataLoader.cs | 4 ---- .../__Internals/IDispatchMetadataLoader.cs | 2 -- .../__Internals/GraphicsResourceHelper.cs | 18 ------------------ .../Interop/__Internals/ResourceDescriptor.cs | 2 -- .../__Internals/ArrayPoolStringBuilder.cs | 0 5 files changed, 26 deletions(-) rename src/ComputeSharp/Shaders/{Renderer => Translation}/__Internals/ArrayPoolStringBuilder.cs (100%) diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs index c74fc4a7..29af4b67 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchDataLoader.cs @@ -14,16 +14,12 @@ namespace ComputeSharp.__Internals /// Loads the captured values used by the shader to be dispatched. /// /// The sequence of serialized captured values. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] void LoadCapturedValues(ReadOnlySpan data); /// /// Loads the captured resources used by the shader to be dispatched. /// /// The sequence of serialized resources. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] void LoadCapturedResources(ReadOnlySpan data); } } diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs index 9095e60e..4ad4b3ce 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IDispatchMetadataLoader.cs @@ -16,8 +16,6 @@ namespace ComputeSharp.__Internals /// The serialized metadata for the current shader. /// The sequence of resource descriptors for the current shader. /// The resulting opaque metadata handle. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] void LoadMetadataHandle(ReadOnlySpan serializedMetadata, ReadOnlySpan resourceDescriptors, out IntPtr result); } } diff --git a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index fdf9a066..17eaea5f 100644 --- a/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -34,8 +34,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the buffer. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(Buffer buffer, GraphicsDevice device) where T : unmanaged @@ -53,8 +51,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadOnlyTexture2D texture, GraphicsDevice device) where T : unmanaged @@ -72,8 +68,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadWriteTexture2D texture, GraphicsDevice device) where T : unmanaged @@ -91,8 +85,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture2D texture, GraphicsDevice device) where TPixel : unmanaged @@ -114,8 +106,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture2D texture, GraphicsDevice device) where TPixel : unmanaged @@ -137,8 +127,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadOnlyTexture3D texture, GraphicsDevice device) where T : unmanaged @@ -156,8 +144,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(ReadWriteTexture3D texture, GraphicsDevice device) where T : unmanaged @@ -175,8 +161,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture3D texture, GraphicsDevice device) where TPixel : unmanaged @@ -198,8 +182,6 @@ namespace ComputeSharp.__Internals /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture3D texture, GraphicsDevice device) where TPixel : unmanaged diff --git a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs index 6b2d9422..fbe2853f 100644 --- a/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs +++ b/src/ComputeSharp/Graphics/Resources/Interop/__Internals/ResourceDescriptor.cs @@ -39,8 +39,6 @@ namespace ComputeSharp.__Internals /// The type of resource to create the descriptor for. /// The offset in the resource from the start of the shader mapping. /// The resulting instance. - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This method is not intended to be called directly by user code")] public static void Create(int type, uint offset, out ResourceDescriptor descriptor) { descriptor.RangeType = (D3D12_DESCRIPTOR_RANGE_TYPE)type; diff --git a/src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs b/src/ComputeSharp/Shaders/Translation/__Internals/ArrayPoolStringBuilder.cs similarity index 100% rename from src/ComputeSharp/Shaders/Renderer/__Internals/ArrayPoolStringBuilder.cs rename to src/ComputeSharp/Shaders/Translation/__Internals/ArrayPoolStringBuilder.cs From fdc06c2b459d0d16c1d47a618191ac0c98759570 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Jul 2021 14:07:51 +0200 Subject: [PATCH 31/37] Added setup to support imported delegate members mapping --- ...erGenerator.CreateBuildHlslStringMethod.cs | 59 ++++++++++++++++--- .../IShaderGenerator.cs | 32 ++++++---- 2 files changed, 74 insertions(+), 17 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index f59ea44d..dac9d470 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -29,7 +29,8 @@ namespace ComputeSharp.SourceGenerators StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, - out bool isSamplerUsed) + out bool isSamplerUsed, + out bool isHashSetDirectiveNeeded) { // Properties are not supported DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); @@ -71,7 +72,8 @@ namespace ComputeSharp.SourceGenerators sharedBuffers, forwardDeclarations, processedMethods, - entryPoint); + entryPoint, + out isHashSetDirectiveNeeded); implicitTextureType = pixelShaderTextureType; isSamplerUsed = accessesStaticSampler; @@ -469,6 +471,7 @@ namespace ComputeSharp.SourceGenerators /// The sequence of forward method declarations. /// The sequence of processed methods used by the shader. /// The body of the entry point of the shader. + /// Indicates whether or not the directive for is needed. /// The series of statements to build the HLSL source to compile to execute the current shader. private static IEnumerable GenerateRenderMethodBody( IEnumerable<(string Name, string Value)> definedConstants, @@ -479,9 +482,10 @@ namespace ComputeSharp.SourceGenerators string? implicitTextureType, bool isSamplerUsed, IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, - IEnumerable? forwardDeclarations, + IEnumerable forwardDeclarations, IEnumerable processedMethods, - string executeMethod) + string executeMethod, + out bool isHashSetDirectiveNeeded) { List statements = new(); StringBuilder textBuilder = new(); @@ -558,6 +562,42 @@ namespace ComputeSharp.SourceGenerators } } + // Declare the hashsets to track imported members and types from delegates, if needed + if (capturedDelegates > 0) + { + void DeclareMapping(int index, string name, IEnumerable items) + { + // HashSet = new(); + statements.Insert(index, + LocalDeclarationStatement(VariableDeclaration( + GenericName(Identifier("HashSet")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword)))) + .AddVariables( + VariableDeclarator(Identifier(name)) + .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + + // .Add(""); + foreach (var item in items) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(name), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + } + } + + DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name)); + DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name)); + DeclareMapping(2, "__methodNames", forwardDeclarations); + } + + isHashSetDirectiveNeeded = capturedDelegates > 0; + // Header AppendLineAndLF("// ================================================"); AppendLineAndLF("// AUTO GENERATED"); @@ -599,7 +639,7 @@ namespace ComputeSharp.SourceGenerators } // Declared types - foreach (var (typeName, typeDefinition) in declaredTypes) + foreach (var (_, typeDefinition) in declaredTypes) { AppendLF(); AppendLineAndLF(typeDefinition); @@ -702,7 +742,7 @@ namespace ComputeSharp.SourceGenerators } // Captured delegate methods - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + foreach (var (fieldSymbol, fieldName, _) in instanceFields) { if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) { @@ -718,8 +758,13 @@ namespace ComputeSharp.SourceGenerators FlushText(); + // The builder declaration needs to go after the captured delegate attribute + // declaration, and also after the 3 name mapping hashsets inserted at the top. + int builderDeclarationIndex = capturedDelegates > 0 ? capturedDelegates + 3 : 0; + // builder = ArrayPoolStringBuilder.Create(); - statements.Insert(capturedDelegates, + statements.Insert( + builderDeclarationIndex, ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 23d30bbd..e341f03d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -59,7 +59,7 @@ namespace ComputeSharp.SourceGenerators MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol), loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants), - buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed), + buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out bool isHashSetDirectiveNeeded), loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed); // Reorder the method declarations to respect the order in the interface definition @@ -122,6 +122,23 @@ namespace ComputeSharp.SourceGenerators .WithoutTrivia(); } + // Prepare the necessary using directives + List usingDirectives = new() + { + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.CodeDom.Compiler")), + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Diagnostics")), + UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), + UsingDirective(IdentifierName("System.Runtime.CompilerServices")), + UsingDirective(IdentifierName("ComputeSharp.__Internals")) + }; + + if (isHashSetDirectiveNeeded) + { + usingDirectives.Insert(2, UsingDirective(IdentifierName("System.Collections.Generic"))); + } + // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: // @@ -140,14 +157,7 @@ namespace ComputeSharp.SourceGenerators // // } var source = - CompilationUnit().AddUsings( - UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.CodeDom.Compiler")), - UsingDirective(IdentifierName("System.ComponentModel")), - UsingDirective(IdentifierName("System.Diagnostics")), - UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), - UsingDirective(IdentifierName("System.Runtime.CompilerServices")), - UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddMembers( + CompilationUnit().AddUsings(usingDirectives.ToArray()).AddMembers( NamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax) .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace(eol: "\n") @@ -186,13 +196,15 @@ namespace ComputeSharp.SourceGenerators /// The for . /// The implicit texture type, if available (if the shader is a pixel shader). /// Whether or not the current shader type requires a static sampler to be available. + /// Indicates whether or not the directive for is needed. /// The resulting instance for the BuildHlslString method. private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, - out bool isSamplerUsed); + out bool isSamplerUsed, + out bool isHashSetDirectiveNeeded); /// /// Creates a instance for the LoadDispatchMetadata method. From 4c50309bdd1aa874d9454904a1c72cefc88a5b88 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Jul 2021 20:19:56 +0200 Subject: [PATCH 32/37] Enabled constants import for captured delegates --- .../Helpers/SyntaxFactoryHelper.cs | 66 +-------------- ...erGenerator.CreateBuildHlslStringMethod.cs | 83 ++++++++++--------- ...derMethodSourceAttribute.HlslGeneration.cs | 35 ++++++++ .../ShaderMethodSourceAttribute.cs | 64 ++++++-------- .../MetaprogrammingTests.cs | 34 ++++++++ 5 files changed, 140 insertions(+), 142 deletions(-) create mode 100644 src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs index b6e7c5d0..5c6d27b8 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -39,7 +39,7 @@ namespace ComputeSharp.SourceGenerators.Helpers /// /// That it, it applies the following transformation: /// - /// { ("K1", "V1", I1), ("K2", "V2", null) } => new object[] { new object[] { "K1", "V1", I1 }, new object[] { "K2", "V2", null } } + /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } } /// /// /// @@ -55,74 +55,12 @@ namespace ComputeSharp.SourceGenerators.Helpers .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(groups.Select(static group => ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions( LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)), LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray())); } - - /// - /// Creates an [] array expression with the nested groups in the input sequence. - /// - /// That it, it applies the following transformation: - /// - /// { ("K1", "V1", I1), ("K2", "V2", null) } => new object[] { new object[] { "K1", "V1", I1 }, new object[] { "K2", "V2", null } } - /// - /// - /// - /// The input sequence of groups. - /// An instance with the described contents. - [Pure] - public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B, int? C)> groups) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(groups.Select(static group => - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)), - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B)), - group.C is int i - ? LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i)) - : LiteralExpression(SyntaxKind.NullLiteralExpression)))).ToArray())); - } - - /// - /// Creates a []? array expression from the given tuple instance. - /// - /// That it, it applies the following transformation: - /// - /// null => null - /// ("S1", "S2") => new string[] { "S1", "S2" } - /// - /// - /// - /// The input tuple instance. - /// An instance with the described contents. - [Pure] - public static ExpressionSyntax ArrayExpression((string First, string Second)? values) - { - if (values is null) - { - return LiteralExpression(SyntaxKind.NullLiteralExpression); - } - - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.First)), - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.Second)))); - } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index dac9d470..f0ff8b7a 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -490,6 +490,7 @@ namespace ComputeSharp.SourceGenerators List statements = new(); StringBuilder textBuilder = new(); int capturedDelegates = 0; + int prologueStatements = 0; int sizeHint = 64; void AppendLF() @@ -514,7 +515,7 @@ namespace ComputeSharp.SourceGenerators textBuilder.Append('\n'); } - void AppendStatement(string text) + void AppendParsedStatement(string text) { FlushText(); @@ -538,28 +539,26 @@ namespace ComputeSharp.SourceGenerators } // Go through all existing delegate fields, if any - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) { - if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) - { - // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ShaderMethodSourceAttribute)), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - capturedDelegates++; - } + capturedDelegates++; + prologueStatements++; } // Declare the hashsets to track imported members and types from delegates, if needed @@ -576,6 +575,8 @@ namespace ComputeSharp.SourceGenerators VariableDeclarator(Identifier(name)) .WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression()))))); + prologueStatements++; + // .Add(""); foreach (var item in items) { @@ -588,6 +589,8 @@ namespace ComputeSharp.SourceGenerators IdentifierName("Add"))) .AddArgumentListArguments(Argument( LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + + prologueStatements++; } } @@ -608,11 +611,14 @@ namespace ComputeSharp.SourceGenerators // Group size constants AppendLF(); AppendLine("#define __GroupSize__get_X "); - AppendStatement("builder.Append(threadsX);"); + AppendParsedStatement("builder.Append(threadsX);"); + AppendLF(); AppendLine("#define __GroupSize__get_Y "); - AppendStatement("builder.Append(threadsY);"); + AppendParsedStatement("builder.Append(threadsY);"); + AppendLF(); AppendLine("#define __GroupSize__get_Z "); - AppendStatement("builder.Append(threadsZ);"); + AppendParsedStatement("builder.Append(threadsZ);"); + AppendLF(); // Define declarations foreach (var (name, value) in definedConstants) @@ -620,6 +626,12 @@ namespace ComputeSharp.SourceGenerators AppendLineAndLF($"#define {name} {value}"); } + // Defines from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); + } + // Static fields if (staticFields.Any()) { @@ -658,12 +670,9 @@ namespace ComputeSharp.SourceGenerators } // User-defined values - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.IsUnmanagedType)) { - if (fieldSymbol.Type.IsUnmanagedType) - { - AppendLineAndLF($" {fieldType} {fieldName};"); - } + AppendLineAndLF($" {fieldType} {fieldName};"); } AppendCharacterAndLF('}'); @@ -742,13 +751,11 @@ namespace ComputeSharp.SourceGenerators } // Captured delegate methods - foreach (var (fieldSymbol, fieldName, _) in instanceFields) + foreach (var (fieldSymbol, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) { - if (fieldSymbol.Type.TypeKind == TypeKind.Delegate) - { - AppendLF(); - AppendStatement($"builder.Append(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));"); - } + AppendLF(); + AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); + AppendLF(); } // Entry point @@ -758,13 +765,9 @@ namespace ComputeSharp.SourceGenerators FlushText(); - // The builder declaration needs to go after the captured delegate attribute - // declaration, and also after the 3 name mapping hashsets inserted at the top. - int builderDeclarationIndex = capturedDelegates > 0 ? capturedDelegates + 3 : 0; - // builder = ArrayPoolStringBuilder.Create(); statements.Insert( - builderDeclarationIndex, + prologueStatements, ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs new file mode 100644 index 00000000..eabb96b8 --- /dev/null +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.__Internals +{ + /// + public sealed partial class ShaderMethodSourceAttribute : Attribute + { + /// + /// Appends the mapped source code for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered constant names. + public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair constant in this.constants) + { + if (mapping.Add(constant.Key)) + { + builder.Append($"#define {constant.Key} {constant.Value}\n"); + } + } + } + + /// + /// Appends the mapped source code for the current method. + /// + /// The target instance to write to. + /// The name to bind the method to. + public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name) + { + builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name)); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 703e9c9a..bde41457 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -16,7 +16,7 @@ namespace ComputeSharp.__Internals [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This attribute is not intended to be used directly by user code")] - public sealed class ShaderMethodSourceAttribute : Attribute + public sealed partial class ShaderMethodSourceAttribute : Attribute { /// /// The identifier for the invoke method, for late binding. @@ -28,6 +28,26 @@ namespace ComputeSharp.__Internals /// private readonly string invokeMethod; + /// + /// The fully qualified name of the current method. + /// + private readonly string methodName; + + /// + /// The collection of custom types. + /// + private readonly Dictionary types; + + /// + /// The collection of processed methods. + /// + private readonly string[] methods; + + /// + /// The collection of discovered constants. + /// + private readonly Dictionary constants; + /// /// Creates a new instance with the specified parameters. /// @@ -39,42 +59,10 @@ namespace ComputeSharp.__Internals public ShaderMethodSourceAttribute(string methodName, object[] types, string invokeMethod, string[] methods, object[] constants) { this.invokeMethod = invokeMethod; - - MethodName = methodName; - Types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); - Methods = methods; - Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); - } - - /// - /// Gets the fully qualified name of the shader type. - /// - internal string MethodName { get; } - - /// - /// Gets the collection of processed custom types. - /// - internal IReadOnlyDictionary Types { get; } - - /// - /// Gets the collection of processed methods. - /// - internal IReadOnlyCollection Methods { get; } - - /// - /// Gets the collection of discovered constants. - /// - internal IReadOnlyDictionary Constants { get; } - - /// - /// Gets the mapped source code for the current method. - /// - /// The name to bind the method to. - /// The mapped source code for the current mehtod. - [Pure] - public string GetMappedInvokeMethod(string name) - { - return this.invokeMethod.Replace(InvokeMethodIdentifier, name); + this.methodName = methodName; + this.types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); + this.methods = methods; + this.constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } /// @@ -96,7 +84,7 @@ namespace ComputeSharp.__Internals foreach (var attribute in attributes) { - if (attribute.MethodName.Equals(methodName)) + if (attribute.methodName.Equals(methodName)) { return attribute; } diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs index 71d5bc4f..1a7f434a 100644 --- a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs +++ b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs @@ -33,6 +33,9 @@ namespace ComputeSharp.Tests // Missing attribute public static int Identity(int x) => x; + + [ShaderMethod] + public static int FunctionWithConstants(int x) => (int)(x + FourAndAHalf); } [CombinatorialTestMethod] @@ -111,5 +114,36 @@ namespace ComputeSharp.Tests Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i))); } } + + public const float FourAndAHalf = 4.5f; + public const int MagicNumber = 42; + + [AutoConstructor] + internal readonly partial struct DelegateWithConstantsShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = MagicNumber + activation(ThreadIds.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DelegateWithConstants(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new DelegateWithConstantsShader(buffer, Activations.FunctionWithConstants)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], MagicNumber + Activations.FunctionWithConstants(i)); + } + } } } From da786aaf0dd22152ca1ac0fb72ad66abcbc53332 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Jul 2021 15:32:09 +0200 Subject: [PATCH 33/37] Enabled support for var declarations in shaders --- .../HlslSourceRewriter.Diagnostics.cs | 15 ------------- .../SyntaxRewriters/HlslSourceRewriter.cs | 19 +++++++++++++++++ .../DiagnosticsTests.cs | 10 ++++----- .../ComputeSharp.Tests/ShaderCompilerTests.cs | 21 +++++++++++++++++++ 4 files changed, 45 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index 38a70d07..9cea28a0 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -171,21 +171,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return base.VisitUsingStatement(node); } - /// - public override SyntaxNode? VisitVariableDeclarator(VariableDeclaratorSyntax node) - { - var updatedNode = (VariableDeclaratorSyntax)base.VisitVariableDeclarator(node)!; - - if (node.Initializer is null && - node.Parent is VariableDeclarationSyntax declaration && - SemanticModel.For(node).GetTypeInfo(declaration.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) - { - Context.ReportDiagnostic(InvalidObjectDeclaration, node, type); - } - - return updatedNode; - } - /// public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node) { diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index b52a6974..d346d8f4 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -73,6 +73,25 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); } + /// + public override SyntaxNode? VisitVariableDeclaration(VariableDeclarationSyntax node) + { + var updatedNode = (VariableDeclarationSyntax)base.VisitVariableDeclaration(node)!; + + if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type) + { + Context.ReportDiagnostic(InvalidObjectDeclaration, node, type); + } + + // If var is used, replace it with the explicit type + if (updatedNode.Type is IdentifierNameSyntax { IsVar: true }) + { + updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node.Type, SemanticModel.For(node), DiscoveredTypes); + } + + return updatedNode; + } + /// public override SyntaxNode VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) { diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 42be1d7c..55d7f58d 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -283,7 +283,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0010"); + VerifyGeneratedDiagnostics(source, "CMPS0010", "CMPS0031"); } [TestMethod] @@ -310,7 +310,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0010"); + VerifyGeneratedDiagnostics(source, "CMPS0010", "CMPS0031"); } [TestMethod] @@ -337,7 +337,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0011"); + VerifyGeneratedDiagnostics(source, "CMPS0011", "CMPS0031"); } [TestMethod] @@ -894,7 +894,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0029"); + VerifyGeneratedDiagnostics(source, "CMPS0029", "CMPS0031"); } [TestMethod] @@ -923,7 +923,7 @@ namespace ComputeSharp.Tests.SourceGenerators } }"; - VerifyGeneratedDiagnostics(source, "CMPS0029"); + VerifyGeneratedDiagnostics(source, "CMPS0029", "CMPS0031"); } [TestMethod] diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 50e72d30..b667e00a 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -171,5 +171,26 @@ namespace ComputeSharp.Tests return new(1, 1, 1, 1); } } + + [AutoConstructor] + public readonly partial struct LoopWithVarCounterShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + /// + public void Execute() + { + for (var i = 0; i < 10; i++) + { + buffer[ThreadIds.X * 10 + i] = i; + } + } + } + + [TestMethod] + public void LoopWithVarCounter() + { + ReflectionServices.GetShaderInfo(out var info); + } } } From 4db77f72b0688f7581afbf484f69ff590d24ec93 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Jul 2021 16:09:24 +0200 Subject: [PATCH 34/37] Enabled types import for captured delegates --- ...erGenerator.CreateBuildHlslStringMethod.cs | 8 +++ ...derMethodSourceAttribute.HlslGeneration.cs | 16 ++++++ .../MetaprogrammingTests.cs | 55 +++++++++++++++++++ 3 files changed, 79 insertions(+) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index f0ff8b7a..cbda6b4d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -657,6 +657,14 @@ namespace ComputeSharp.SourceGenerators AppendLineAndLF(typeDefinition); } + // Declared types from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendLF(); + AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); + AppendLF(); + } + // Captured variables AppendLF(); AppendLineAndLF("cbuffer _ : register(b0)"); diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs index eabb96b8..9e79aa98 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs @@ -22,6 +22,22 @@ namespace ComputeSharp.__Internals } } + /// + /// Appends the discovered types for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair type in this.types) + { + if (mapping.Add(type.Key)) + { + builder.Append(type.Value); + } + } + } + /// /// Appends the mapped source code for the current method. /// diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs index 1a7f434a..9d5bf688 100644 --- a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs +++ b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs @@ -36,6 +36,26 @@ namespace ComputeSharp.Tests [ShaderMethod] public static int FunctionWithConstants(int x) => (int)(x + FourAndAHalf); + + [ShaderMethod] + public static Position FunctionWithTypes(int x) + { + Point point = default; + point.A = x; + point.B = x * x; + + Position position = default; + position.X = point.A; + position.Y = point.B; + + return position; + } + + public struct Point + { + public int A; + public int B; + } } [CombinatorialTestMethod] @@ -145,5 +165,40 @@ namespace ComputeSharp.Tests Assert.AreEqual(result[i], MagicNumber + Activations.FunctionWithConstants(i)); } } + + public struct Position + { + public int X; + public int Y; + } + + [AutoConstructor] + internal readonly partial struct DelegateWithTypesShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = activation(ThreadIds.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DelegateWithTypes(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new DelegateWithTypesShader(buffer, Activations.FunctionWithTypes)); + + Position[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i].X, Activations.FunctionWithTypes(i).X); + Assert.AreEqual(result[i].Y, Activations.FunctionWithTypes(i).Y); + } + } } } From 8e0db58a19677078cafe79189e7a16053c45fd86 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Jul 2021 17:26:05 +0200 Subject: [PATCH 35/37] Fixed processing of discovered methods for [SourceMethod] --- .../Helpers/SyntaxFactoryHelper.cs | 22 ------------- .../ShaderMethodSourceGenerator.cs | 31 ++++++++++++------- .../ShaderMethodSourceAttribute.cs | 20 ++++++------ 3 files changed, 30 insertions(+), 43 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs index 5c6d27b8..80403c01 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -12,28 +12,6 @@ namespace ComputeSharp.SourceGenerators.Helpers /// internal static class SyntaxFactoryHelper { - /// - /// Creates a [] array expression from the given sequence of instances. - /// - /// That it, it applies the following transformation: - /// - /// { "S1", "S2" } => new string[] { "S1", "S2" } - /// - /// - /// - /// The input sequence of instances. - /// An instance with the described contents. - [Pure] - public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); - } - /// /// Creates an [] array expression with the nested groups in the input sequence. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index e3f91e72..898c36a4 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -66,11 +66,10 @@ namespace ComputeSharp.SourceGenerators { // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var (invokeMethod, localFunctions) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); + var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions); var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions); @@ -80,9 +79,9 @@ namespace ComputeSharp.SourceGenerators AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), - AttributeArgument(NestedArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(ArrayExpression(localFunctions)), + AttributeArgument(NestedArrayExpression(processedTypes)), + AttributeArgument(NestedArrayExpression(processedMethods)), AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) @@ -100,18 +99,18 @@ namespace ComputeSharp.SourceGenerators /// The instance for the current method. /// The instance for the method to process. /// The collection of currently discovered types. - /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// A sequence of processed methods in (main method and local functions). + /// A sequence of processed methods in (main method and all captured methods). [Pure] - private static (string TargetMethod, IEnumerable LocalFunctions) GetProcessedMethods( + private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods( GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, ICollection discoveredTypes, - IDictionary staticMethods, IDictionary constantDefinitions) { + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context); // Rewrite the method syntax tree @@ -122,15 +121,25 @@ namespace ComputeSharp.SourceGenerators .NormalizeWhitespace(eol: "\n") .ToFullString(); - List localFunctions = new(shaderSourceRewriter.LocalFunctions.Count); + List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - localFunctions.Add(localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()); + processedMethods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); } - return (targetMethod, localFunctions); + // Emit the discovered static methods + foreach (var staticMethod in staticMethods.Values) + { + processedMethods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + } + + return (targetMethod, processedMethods); } } } diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index bde41457..fd76f48f 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -23,16 +23,16 @@ namespace ComputeSharp.__Internals /// internal const string InvokeMethodIdentifier = "____"; - /// - /// The source code for the target entry point method. - /// - private readonly string invokeMethod; - /// /// The fully qualified name of the current method. /// private readonly string methodName; + /// + /// The source code for the target entry point method. + /// + private readonly string invokeMethod; + /// /// The collection of custom types. /// @@ -41,7 +41,7 @@ namespace ComputeSharp.__Internals /// /// The collection of processed methods. /// - private readonly string[] methods; + private readonly Dictionary methods; /// /// The collection of discovered constants. @@ -52,16 +52,16 @@ namespace ComputeSharp.__Internals /// Creates a new instance with the specified parameters. /// /// The fully qualified name of the current method. - /// The collection of custom types. /// The source code for the target entry point method. + /// The collection of custom types. /// The collection of processed methods. /// The collection of discovered constants. - public ShaderMethodSourceAttribute(string methodName, object[] types, string invokeMethod, string[] methods, object[] constants) + public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants) { - this.invokeMethod = invokeMethod; this.methodName = methodName; + this.invokeMethod = invokeMethod; this.types = types.Cast().ToDictionary(static c => c[0], static c => c[1]); - this.methods = methods; + this.methods = methods.Cast().ToDictionary(static c => c[0], static c => c[1]); this.constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } From 06111edacb0eed90c63521c5029eb2704f9cfdd8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Jul 2021 19:58:13 +0200 Subject: [PATCH 36/37] Enabled methods import for captured delegates --- ...erGenerator.CreateBuildHlslStringMethod.cs | 128 +++++++++++------- ...derMethodSourceAttribute.HlslGeneration.cs | 38 ++++++ .../MetaprogrammingTests.cs | 36 +++++ 3 files changed, 150 insertions(+), 52 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index cbda6b4d..c345ff3c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -53,7 +53,7 @@ namespace ComputeSharp.SourceGenerators var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, forwardDeclarations, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = GetProcessedConstants(constantDefinitions); @@ -70,7 +70,6 @@ namespace ComputeSharp.SourceGenerators pixelShaderTextureType, accessesStaticSampler, sharedBuffers, - forwardDeclarations, processedMethods, entryPoint, out isHashSetDirectiveNeeded); @@ -301,7 +300,7 @@ namespace ComputeSharp.SourceGenerators /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. [Pure] - private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations, bool IsSamplerUser) GetProcessedMethods( + private static (string EntryPoint, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -318,8 +317,7 @@ namespace ComputeSharp.SourceGenerators select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); string? entryPoint = null; - List methods = new(); - List declarations = new(); + List<(string, string)> processedMethods = new(); bool isSamplerUsed = false; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) @@ -356,8 +354,9 @@ namespace ComputeSharp.SourceGenerators // Emit the extracted local functions first foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - methods.Add(localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()); - declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); + processedMethods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); } // If the method is the shader entry point, do additional processing @@ -373,19 +372,21 @@ namespace ComputeSharp.SourceGenerators } else { - methods.Add(processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()); - declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); + processedMethods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } } // Process static methods as well foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) { - methods.Add(staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()); - declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); + processedMethods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } - return (entryPoint!, methods, declarations, isSamplerUsed); + return (entryPoint!, processedMethods, isSamplerUsed); } /// @@ -468,7 +469,6 @@ namespace ComputeSharp.SourceGenerators /// The type of the implicit target texture, if present. /// Whether the static sampler is used by the shader. /// The sequence of shared buffers declared by the shader. - /// The sequence of forward method declarations. /// The sequence of processed methods used by the shader. /// The body of the entry point of the shader. /// Indicates whether or not the directive for is needed. @@ -482,8 +482,7 @@ namespace ComputeSharp.SourceGenerators string? implicitTextureType, bool isSamplerUsed, IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, - IEnumerable forwardDeclarations, - IEnumerable processedMethods, + IEnumerable<(string Signature, string Definition)> processedMethods, string executeMethod, out bool isHashSetDirectiveNeeded) { @@ -538,31 +537,8 @@ namespace ComputeSharp.SourceGenerators } } - // Go through all existing delegate fields, if any - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ShaderMethodSourceAttribute)), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - - capturedDelegates++; - prologueStatements++; - } - // Declare the hashsets to track imported members and types from delegates, if needed - if (capturedDelegates > 0) + if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) { void DeclareMapping(int index, string name, IEnumerable items) { @@ -596,7 +572,30 @@ namespace ComputeSharp.SourceGenerators DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name)); DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name)); - DeclareMapping(2, "__methodNames", forwardDeclarations); + DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature)); + + // Go through all existing delegate fields, if any + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + prologueStatements++; + } } isHashSetDirectiveNeeded = capturedDelegates > 0; @@ -660,9 +659,7 @@ namespace ComputeSharp.SourceGenerators // Declared types from captured delegates foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) { - AppendLF(); AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); - AppendLF(); } // Captured variables @@ -739,23 +736,50 @@ namespace ComputeSharp.SourceGenerators } // Forward declarations - if (forwardDeclarations is not null) + foreach (var (forwardDeclaration, _) in processedMethods) { - foreach (var forwardDeclaration in forwardDeclarations) + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + // Forward declarations from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); + } + + // Remove all forward declarations from methods that are embedded into the shader. + // This is necessary to avoid duplicate definitions from methods from delegates. + if (capturedDelegates > 0) + { + // .Add(""); + foreach (var (forwardDeclaration, _) in processedMethods) { - AppendLF(); - AppendLineAndLF(forwardDeclaration); + FlushText(); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__methodNames"), + IdentifierName("Remove"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); } } // Captured methods - if (processedMethods is not null) + foreach (var (_, method) in processedMethods) { - foreach (var method in processedMethods) - { - AppendLF(); - AppendLineAndLF(method); - } + AppendLF(); + AppendLineAndLF(method); + } + + // Captured methods from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); } // Captured delegate methods diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs index 9e79aa98..be523c2c 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs @@ -33,7 +33,45 @@ namespace ComputeSharp.__Internals { if (mapping.Add(type.Key)) { + builder.Append("\n"); builder.Append(type.Value); + builder.Append("\n"); + } + } + } + + /// + /// Appends the discovered forward declarations for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair method in this.methods) + { + if (mapping.Add(method.Key)) + { + builder.Append("\n"); + builder.Append(method.Key); + builder.Append("\n"); + } + } + } + + /// + /// Appends the discovered methods for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair method in this.methods) + { + if (mapping.Remove(method.Key)) + { + builder.Append("\n"); + builder.Append(method.Value); + builder.Append("\n"); } } } diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs index 9d5bf688..70bb9d22 100644 --- a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs +++ b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs @@ -56,6 +56,14 @@ namespace ComputeSharp.Tests public int A; public int B; } + + [ShaderMethod] + public static int FunctionWithLocalFunctionAndStaticMethod(int x) + { + static int AddTwo(int x) => x + 2; + + return Square(3 + AddOne(x) + AddTwo(x)); + } } [CombinatorialTestMethod] @@ -200,5 +208,33 @@ namespace ComputeSharp.Tests Assert.AreEqual(result[i].Y, Activations.FunctionWithTypes(i).Y); } } + + [AutoConstructor] + internal readonly partial struct DelegateWithLocalFunctionsAndStaticMethodsShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = Activations.AddOne(ThreadIds.X) + activation(ThreadIds.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DelegateWithLocalFunctionsAndStaticMethods(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new DelegateWithLocalFunctionsAndStaticMethodsShader(buffer, Activations.FunctionWithLocalFunctionAndStaticMethod)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(i) + Activations.FunctionWithLocalFunctionAndStaticMethod(i)); + } + } } } From 09c9c48fd71b3bfe628160b22399f1dcb671c1fd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Jul 2021 20:30:51 +0200 Subject: [PATCH 37/37] Fixed shader compilation error from external namespaces --- .../IShaderGenerator.cs | 1 + .../ComputeSharp.Tests/ShaderCompilerTests.cs | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index e341f03d..085f2734 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -131,6 +131,7 @@ namespace ComputeSharp.SourceGenerators UsingDirective(IdentifierName("System.Diagnostics")), UsingDirective(IdentifierName("System.Diagnostics.CodeAnalysis")), UsingDirective(IdentifierName("System.Runtime.CompilerServices")), + UsingDirective(IdentifierName("ComputeSharp")), UsingDirective(IdentifierName("ComputeSharp.__Internals")) }; diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index b667e00a..08f3a20e 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -1,3 +1,4 @@ +using ComputeSharp; using ComputeSharp.Interop; using ComputeSharp.Tests.Misc; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -194,3 +195,32 @@ namespace ComputeSharp.Tests } } } + +namespace ExternalNamespace +{ + [TestClass] + [TestCategory("ShaderCompiler")] + public partial class ShaderCompilerTestsInExternalNamespace + { + [AutoConstructor] + public readonly partial struct UserDefinedTypeShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + /// + public void Execute() + { + for (var i = 0; i < 10; i++) + { + buffer[ThreadIds.X * 10 + i] = i; + } + } + } + + [TestMethod] + public void UserDefinedType() + { + ReflectionServices.GetShaderInfo(out var info); + } + } +}