From 4c50309bdd1aa874d9454904a1c72cefc88a5b88 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 13 Jul 2021 20:19:56 +0200 Subject: [PATCH] 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)); + } + } } }