From f8e951dd15838decf6a5aa06f5b79c00f6454ef9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 7 Mar 2021 20:14:32 +0100 Subject: [PATCH] Enabled rewriting for shader static constants --- .../IComputeShaderSourceGenerator.cs | 73 ++++++++++++++++++- .../IComputeShaderSourceAttribute.cs | 14 +++- .../Shaders/Renderer/HlslShaderRenderer.cs | 25 ++++++- .../Shaders/Translation/IShaderLoader.cs | 11 ++- .../Shaders/Translation/ShaderLoader{T}.cs | 16 ++-- 5 files changed, 119 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 1970146f..fd5a11a2 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -71,12 +71,13 @@ namespace ComputeSharp.SourceGenerators Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var processedMembers = GetProcessedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); + var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); var processedConstants = GetProcessedConstants(constantDefinitions); + var staticConstants = GetConstantProperties(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -90,6 +91,7 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), AttributeArgument(ArrayExpression(processedMethods)), AttributeArgument(NestedArrayExpression(processedConstants)), + AttributeArgument(NestedArrayExpression(staticConstants)), AttributeArgument(NestedArrayExpression(sharedBuffers))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) @@ -101,14 +103,14 @@ namespace ComputeSharp.SourceGenerators } /// - /// Gets a sequence of captured members and their mapped names. + /// 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. - /// A sequence of captured members in . + /// A sequence of captured fields in . [Pure] - private static IEnumerable> GetProcessedMembers( + private static IEnumerable> GetProcessedFields( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, ICollection types) @@ -171,6 +173,69 @@ namespace ComputeSharp.SourceGenerators } } + /// + /// Gets a sequence of shader static constant properties 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 properties in . + [Pure] + private static IEnumerable> GetConstantProperties( + GeneratorExecutionContext context, + SemanticModel semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + foreach (var propertyDeclaration in structDeclaration.Members.OfType()) + { + IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration)!; + + if (!propertySymbol.IsStatic || !propertySymbol.IsReadOnly) + { + continue; + } + + // Constant properties must be named type symbols + if (propertySymbol.Type is not INamedTypeSymbol typeSymbol) + { + context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type); + + continue; + } + + string metadataName = typeSymbol.GetFullMetadataName(); + + // Constant properties must be of a primitive, vector or matrix type + if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + { + context.ReportDiagnostic(InvalidShaderConstantPropertyType, propertyDeclaration, structDeclarationSymbol, propertySymbol.Name, propertySymbol.Type); + + continue; + } + + ConstantPropertyRewriter constantPropertyRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + context); + + if (constantPropertyRewriter.Visit(propertyDeclaration) is ExpressionSyntax expression) + { + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(propertySymbol.Name, out string? mapping); + + yield return new[] { mapping ?? propertySymbol.Name, typeName, expression.NormalizeWhitespace().ToFullString() }; + } + } + } + /// /// Gets a sequence of captured members and their mapped names. /// diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index b9f62c79..64f6bba7 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -24,6 +24,7 @@ namespace ComputeSharp.__Internals /// The mapped collection of shader fields. /// The source code for the method. /// The collection of processed methods. + /// The collection of discovered defines. /// The collection of discovered constants. /// The collection of group shared buffers. public IComputeShaderSourceAttribute( @@ -32,6 +33,7 @@ namespace ComputeSharp.__Internals object[] args, string executeMethod, string[] methods, + object[] defines, object[] constants, object[] sharedBuffers) { @@ -40,7 +42,8 @@ namespace ComputeSharp.__Internals Fields = args.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); ExecuteMethod = executeMethod; Methods = methods; - Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); + Defines = defines.Cast().ToDictionary(static c => c[0], static c => c[1]); + Constants = constants.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])); } @@ -70,13 +73,18 @@ namespace ComputeSharp.__Internals internal IReadOnlyCollection Methods { get; } /// - /// Gets the collection of discovered constants. + /// Gets the collection of discovered define declarations. /// - internal IReadOnlyDictionary Constants { get; } + internal IReadOnlyDictionary Defines { get; } /// /// Gets the collection of discovered constants. /// + internal IReadOnlyDictionary Constants { get; } + + /// + /// Gets the collection of discovered shared buffers. + /// internal IReadOnlyDictionary SharedBuffers { get; } /// diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs index 1232512f..3a48a8aa 100644 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs @@ -42,13 +42,30 @@ namespace ComputeSharp.Shaders.Renderer builder.Append("#define __GroupSize__get_Z "); builder.AppendLine(threadsZ.ToString()); - // User defined onstants - foreach (var constant in info.ConstantsInfo) + // Define declarations + foreach (var define in info.DefinesInfo) { builder.Append("#define "); - builder.Append(constant.Key); + builder.Append(define.Key); builder.Append(' '); - builder.AppendLine(constant.Value); + builder.AppendLine(define.Value); + } + + // Static constants + if (info.ConstantsInfo.Count > 0) + { + builder.AppendLine(); + + foreach (var constant in info.ConstantsInfo) + { + builder.Append("static const "); + builder.Append(constant.Value.Type); + builder.Append(' '); + builder.Append(constant.Key); + builder.Append(" = "); + builder.Append(constant.Value.Assignment); + builder.AppendLine(";"); + } } // Declared types diff --git a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs index 0ff336a8..2d9662ae 100644 --- a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs +++ b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs @@ -29,9 +29,14 @@ namespace ComputeSharp.Shaders.Translation IReadOnlyCollection MethodsInfo { get; } /// - /// Gets the collection of constants to be declared in the shader. + /// Gets the collection of define declarations to be added to the shader. /// - IReadOnlyDictionary ConstantsInfo { get; } + IReadOnlyDictionary DefinesInfo { get; } + + /// + /// Gets the collection of discovered constants. + /// + IReadOnlyDictionary ConstantsInfo { get; } /// /// Gets the collection of declared types for the shader. @@ -39,7 +44,7 @@ namespace ComputeSharp.Shaders.Translation IReadOnlyCollection DeclaredTypes { get; } /// - /// Gets the collection of discovered constants. + /// Gets the collection of discovered group shared buffers. /// IReadOnlyDictionary SharedBuffers { get; } } diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index e0495df5..213f6f32 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -66,9 +66,9 @@ namespace ComputeSharp.Shaders.Translation private readonly List methodsInfo = new(); /// - /// The with the discovered constants for the shader. + /// The with the discovered define declarations for the shader. /// - private readonly Dictionary constantsInfo = new(); + private readonly Dictionary definesInfo = new(); /// /// The with the collected declared types for the shader. @@ -108,11 +108,14 @@ namespace ComputeSharp.Shaders.Translation public IReadOnlyCollection MethodsInfo => this.methodsInfo; /// - public IReadOnlyDictionary ConstantsInfo => this.constantsInfo; + public IReadOnlyDictionary DefinesInfo => this.definesInfo; /// public IReadOnlyCollection DeclaredTypes => this.declaredTypes; + /// + public IReadOnlyDictionary ConstantsInfo { get; private set; } + /// public IReadOnlyDictionary SharedBuffers { get; private set; } @@ -143,14 +146,15 @@ namespace ComputeSharp.Shaders.Translation private void LoadMethodMetadata() { EntryPoint = Attribute.ExecuteMethod; + ConstantsInfo = Attribute.Constants; SharedBuffers = Attribute.SharedBuffers; this.declaredTypes.AddRange(Attribute.Types); this.methodsInfo.AddRange(Attribute.Methods); - foreach (var pair in Attribute.Constants) + foreach (var pair in Attribute.Defines) { - this.constantsInfo.Add(pair.Key, pair.Value); + this.definesInfo.Add(pair.Key, pair.Value); } } @@ -233,7 +237,7 @@ namespace ComputeSharp.Shaders.Translation foreach (var pair in methodSource.Constants) { - this.constantsInfo[pair.Key] = pair.Value; + this.definesInfo[pair.Key] = pair.Value; } } else ThrowHelper.ThrowArgumentException("Invalid captured variable");