From c0e78bb1a2eea01663df5bc382cd9919cdf25b43 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 12:59:18 +0100 Subject: [PATCH 01/11] Add HlslDefinitionsSyntaxProcessor.TryGetStaticField --- .../Diagnostics/DiagnosticDescriptors.cs | 10 +- .../HlslDefinitionsSyntaxProcessor.cs | 94 +++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 6 +- 3 files changed, 102 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index b2d42ef9..c54cbe30 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -397,19 +397,19 @@ partial class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for an invalid shader static readonly field type. + /// Gets a for an invalid static field type. /// - /// Format: "The pixel shader of type {0} contains a static readonly field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". + /// Format: "The pixel shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". /// /// public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new( id: "CMPSD2D0030", - title: "Invalid shader static readonly field type", - messageFormat: """The pixel shader of type {0} contains a static readonly field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", + title: "Invalid shader static field type", + messageFormat: """The pixel shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A type representing a pixel shader contains a static readonly field of a type that is not supported.", + description: "A type representing a pixel shader contains or references a static field of a type that is not supported.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 22919a98..97f6d3d6 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -1,10 +1,13 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Threading; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -38,6 +41,97 @@ internal static class HlslDefinitionsSyntaxProcessor return builder.ToImmutable(); } + /// + /// Tries to get and rewrite a given static field to be used in a shader. + /// + /// The type symbol for the shader type. + /// The symbol for the field to analyze. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// The collection of produced instances. + /// The used to cancel the operation, if needed. + /// The mapped name for the field. + /// The type declaration for the field. + /// The assignment expression for the field, if present. + /// The instance used to rewrite the field expression. + /// Whether the field was processed successfully and is valid. + public static bool TryGetStaticField( + INamedTypeSymbol structDeclarationSymbol, + IFieldSymbol fieldSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + ImmutableArrayBuilder diagnostics, + CancellationToken token, + [NotNullWhen(true)] out string? name, + [NotNullWhen(true)] out string? typeDeclaration, + out string? assignmentExpression, + [NotNullWhen(true)] out StaticFieldRewriter? staticFieldRewriter) + { + if (fieldSymbol.IsImplicitlyDeclared || !fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + goto Failure; + } + + if (!fieldSymbol.TryGetSyntaxNode(token, out VariableDeclaratorSyntax? variableDeclarator)) + { + goto Failure; + } + + // Static fields must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullyQualifiedMetadataName())) + { + diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + goto Failure; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + // The field name is either the mapped name (if a reserved name) or just the field name. + // This method is shared across external fields too, and callers can just override this. + name = mapping ?? fieldSymbol.Name; + + // Readonly fields are rewritten to static const fields, and mutable fields are just static. + // Note that there's no protection for mutable static fields that may have been written to + // in C# elsewhere. Shader authors should be aware that those writes would not appear in HLSL, + // as each shader invocation would only see the initial assignment value (or the default value). + typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + token.ThrowIfCancellationRequested(); + + // Create the rewriter to use, which is also returned to callers so they can extract any additional + // info if needed. For instance, the D2D generator will check if the dispatch position is required. + staticFieldRewriter = new StaticFieldRewriter( + semanticModel, + discoveredTypes, + constantDefinitions, + diagnostics, + token); + + ExpressionSyntax? processedDeclaration = staticFieldRewriter.Visit(variableDeclarator); + + token.ThrowIfCancellationRequested(); + + assignmentExpression = processedDeclaration?.NormalizeWhitespace(eol: "\n").ToFullString(); + + return true; + + Failure: + name = null; + typeDeclaration = null; + assignmentExpression = null; + staticFieldRewriter = null; + + return false; + } + /// /// Gets the sequence of processed discovered custom types. /// diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index c2f305f8..85078b3a 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -515,17 +515,17 @@ partial class DiagnosticDescriptors /// /// Gets a for an invalid shader static field type. /// - /// Format: "The compute shader of type {0} contains a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". + /// Format: "The compute shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)". /// /// public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new( id: "CMPS0038", title: "Invalid shader static field type", - messageFormat: """The compute shader of type {0} contains a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", + messageFormat: """The compute shader of type {0} contains or references a static field "{1}" of an invalid type {2} (only primitive, vector and matrix types are supported)""", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "A type representing a compute shader contains a static field of a type that is not supported.", + description: "A type representing a compute shader contains or references a static field of a type that is not supported.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// From 4f60d704113a543eff000e639baa81ab14696629 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 13:06:22 +0100 Subject: [PATCH 02/11] Use shared static field rewriter in DX12/D2D generators --- ...xelShaderDescriptorGenerator.HlslSource.cs | 50 +++++-------------- ...uteShaderDescriptorGenerator.HlslSource.cs | 48 +++++------------- 2 files changed, 26 insertions(+), 72 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index d070d38e..abef3b7d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -256,52 +256,28 @@ partial class D2DPixelShaderDescriptorGenerator foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) { - // Find all declared static fields in the type - if (memberSymbol is not IFieldSymbol { IsImplicitlyDeclared: false, IsStatic: true, IsConst: false, } fieldSymbol) + if (memberSymbol is not IFieldSymbol fieldSymbol) { continue; } - if (!fieldSymbol.TryGetSyntaxNode(token, out VariableDeclaratorSyntax? variableDeclarator)) - { - continue; - } - - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullyQualifiedMetadataName())) - { - diagnostics.Add(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)}" - }; - - token.ThrowIfCancellationRequested(); - - StaticFieldRewriter staticFieldRewriter = new( + if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( + structDeclarationSymbol, + fieldSymbol, semanticModel, discoveredTypes, constantDefinitions, diagnostics, - token); + token, + out string? name, + out string? typeDeclaration, + out string? assignmentExpression, + out StaticFieldRewriter? staticFieldRewriter)) + { + needsD2D1RequiresScenePosition |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute; - ExpressionSyntax? processedDeclaration = staticFieldRewriter.Visit(variableDeclarator); - - token.ThrowIfCancellationRequested(); - - string? assignment = processedDeclaration?.NormalizeWhitespace(eol: "\n").ToFullString(); - - needsD2D1RequiresScenePosition |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute; - - builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + builder.Add((name, typeDeclaration, assignmentExpression)); + } } return builder.ToImmutable(); diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index c2e3c8d9..27f31746 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -265,55 +265,33 @@ partial class ComputeShaderDescriptorGenerator foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) { - // Find all declared static fields in the type + // Pre-filter fields that cannot be valid, to reduce the calls to check the [GroupShared] attribute if (memberSymbol is not IFieldSymbol { IsImplicitlyDeclared: false, IsStatic: true, IsConst: false, } fieldSymbol) { continue; } - if (!fieldSymbol.TryGetSyntaxNode(token, out VariableDeclaratorSyntax? variableDeclarator)) - { - continue; - } - + // Ignore [GroupShared] fields, they'll be gathered in a separate rewriting step if (fieldSymbol.TryGetAttributeWithFullyQualifiedMetadataName("ComputeSharp.GroupSharedAttribute", out _)) { continue; } - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullyQualifiedMetadataName())) - { - diagnostics.Add(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)}" - }; - - token.ThrowIfCancellationRequested(); - - StaticFieldRewriter staticFieldRewriter = new( + if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( + structDeclarationSymbol, + fieldSymbol, semanticModel, discoveredTypes, constantDefinitions, diagnostics, - token); - - ExpressionSyntax? processedDeclaration = staticFieldRewriter.Visit(variableDeclarator); - - token.ThrowIfCancellationRequested(); - - string? assignment = processedDeclaration?.NormalizeWhitespace(eol: "\n").ToFullString(); - - builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + token, + out string? name, + out string? typeDeclaration, + out string? assignmentExpression, + out _)) + { + builder.Add((name, typeDeclaration, assignmentExpression)); + } } return builder.ToImmutable(); From eefd0de9f062e55e4008087d10200382417aeae3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 15:51:46 +0100 Subject: [PATCH 03/11] Add mapping of static fields to HLSL rewriters --- .../D2DPixelShaderDescriptorGenerator.HlslSource.cs | 9 +++++++++ .../HlslDefinitionsSyntaxProcessor.cs | 3 +++ .../SyntaxRewriters/HlslSourceRewriter.cs | 8 ++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 11 +++++++++-- .../SyntaxRewriters/StaticFieldRewriter.cs | 4 +++- .../ComputeShaderDescriptorGenerator.HlslSource.cs | 9 +++++++++ 6 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index abef3b7d..2e00cabd 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -53,6 +53,7 @@ partial class D2DPixelShaderDescriptorGenerator Dictionary instanceMethods = new(SymbolEqualityComparer.Default); Dictionary constructors = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + Dictionary staticFieldDefinitions = new(SymbolEqualityComparer.Default); token.ThrowIfCancellationRequested(); @@ -78,6 +79,7 @@ partial class D2DPixelShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, token, out bool methodsNeedD2D1RequiresScenePosition); @@ -89,6 +91,7 @@ partial class D2DPixelShaderDescriptorGenerator structDeclarationSymbol, discoveredTypes, constantDefinitions, + staticFieldDefinitions, token, out bool fieldsNeedD2D1RequiresScenePosition); @@ -238,6 +241,7 @@ partial class D2DPixelShaderDescriptorGenerator /// The type symbol for the shader type. /// The collection of currently discovered types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The used to cancel the operation, if needed. /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// A sequence of static constant fields in . @@ -247,6 +251,7 @@ partial class D2DPixelShaderDescriptorGenerator INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, CancellationToken token, out bool needsD2D1RequiresScenePosition) { @@ -267,6 +272,7 @@ partial class D2DPixelShaderDescriptorGenerator semanticModel, discoveredTypes, constantDefinitions, + staticFieldDefinitions, diagnostics, token, out string? name, @@ -294,6 +300,7 @@ partial class D2DPixelShaderDescriptorGenerator /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// Whether or not the shader needs the [D2DRequiresScenePosition] annotation. /// The used to cancel the operation, if needed. /// A sequence of processed methods in , and the entry point. @@ -306,6 +313,7 @@ partial class D2DPixelShaderDescriptorGenerator IDictionary instanceMethods, IDictionary constructors, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, CancellationToken token, out bool needsD2D1RequiresScenePosition) { @@ -350,6 +358,7 @@ partial class D2DPixelShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, diagnostics, token, isShaderEntryPoint); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 97f6d3d6..cbff40dd 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -49,6 +49,7 @@ internal static class HlslDefinitionsSyntaxProcessor /// The instance for the type to process. /// The collection of currently discovered types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The collection of produced instances. /// The used to cancel the operation, if needed. /// The mapped name for the field. @@ -62,6 +63,7 @@ internal static class HlslDefinitionsSyntaxProcessor SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token, [NotNullWhen(true)] out string? name, @@ -112,6 +114,7 @@ internal static class HlslDefinitionsSyntaxProcessor semanticModel, discoveredTypes, constantDefinitions, + staticFieldDefinitions, diagnostics, token); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index 320805ef..8f43912a 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -33,18 +33,21 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The collection of produced instances. /// The value for the current operation. protected HlslSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token) { SemanticModel = semanticModel; DiscoveredTypes = discoveredTypes; ConstantDefinitions = constantDefinitions; + StaticFieldDefinitions = staticFieldDefinitions; Diagnostics = diagnostics; CancellationToken = token; } @@ -64,6 +67,11 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// protected IDictionary ConstantDefinitions { get; } + /// + /// Gets the collection of discovered static field definitions. + /// + protected IDictionary StaticFieldDefinitions { get; } + /// /// Gets the collection of produced instances. /// diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 26e677a6..da4705af 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -77,6 +77,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The collection of produced instances. /// The value for the current operation. /// Whether or not the current instance is processing a shader entry point. @@ -88,10 +89,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter IDictionary instanceMethods, IDictionary constructors, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token, bool isEntryPoint) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token) + : base(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) { this.shaderType = shaderType; this.staticMethods = staticMethods; @@ -111,6 +113,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The collection of produced instances. /// The value for the current operation. private ShaderSourceRewriter( @@ -120,9 +123,10 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter IDictionary instanceMethods, IDictionary constructors, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token) - : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token) + : base(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) { this.staticMethods = staticMethods; this.instanceMethods = instanceMethods; @@ -545,6 +549,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter this.instanceMethods, this.constructors, ConstantDefinitions, + StaticFieldDefinitions, Diagnostics, CancellationToken); @@ -598,6 +603,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter this.instanceMethods, this.constructors, ConstantDefinitions, + StaticFieldDefinitions, Diagnostics, CancellationToken); @@ -685,6 +691,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter this.instanceMethods, this.constructors, ConstantDefinitions, + StaticFieldDefinitions, Diagnostics, CancellationToken); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs index 2d8fddcf..11b3cc55 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/StaticFieldRewriter.cs @@ -23,15 +23,17 @@ namespace ComputeSharp.SourceGeneration.SyntaxRewriters; /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. +/// The collection of discovered static field definitions. /// The collection of produced instances. /// The value for the current operation. internal sealed partial class StaticFieldRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token) - : HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, diagnostics, token) + : HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) { /// public ExpressionSyntax? Visit(VariableDeclaratorSyntax? node) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index 27f31746..c67dcfbe 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -59,6 +59,7 @@ partial class ComputeShaderDescriptorGenerator Dictionary instanceMethods = new(SymbolEqualityComparer.Default); Dictionary constructors = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + Dictionary staticFieldDefinitions = new(SymbolEqualityComparer.Default); // Setup the semantic model and basic properties INamedTypeSymbol? pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: "IComputeShader" }); @@ -93,6 +94,7 @@ partial class ComputeShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, isComputeShader, token); @@ -105,6 +107,7 @@ partial class ComputeShaderDescriptorGenerator structDeclarationSymbol, discoveredTypes, constantDefinitions, + staticFieldDefinitions, token); token.ThrowIfCancellationRequested(); @@ -251,6 +254,7 @@ partial class ComputeShaderDescriptorGenerator /// The type symbol for the shader type. /// The collection of currently discovered types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// The used to cancel the operation, if needed. /// A sequence of static constant fields in . private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( @@ -259,6 +263,7 @@ partial class ComputeShaderDescriptorGenerator INamedTypeSymbol structDeclarationSymbol, ICollection discoveredTypes, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, CancellationToken token) { using ImmutableArrayBuilder<(string, string, string?)> builder = new(); @@ -283,6 +288,7 @@ partial class ComputeShaderDescriptorGenerator semanticModel, discoveredTypes, constantDefinitions, + staticFieldDefinitions, diagnostics, token, out string? name, @@ -349,6 +355,7 @@ partial class ComputeShaderDescriptorGenerator /// The collection of discovered instance methods for custom struct types. /// The collection of discovered constructors for custom struct types. /// The collection of discovered constant definitions. + /// The collection of discovered static field definitions. /// Indicates whether or not represents a compute shader. /// The used to cancel the operation, if needed. /// A sequence of processed methods in , and the entry point. @@ -361,6 +368,7 @@ partial class ComputeShaderDescriptorGenerator IDictionary instanceMethods, IDictionary constructors, IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, bool isComputeShader, CancellationToken token) { @@ -411,6 +419,7 @@ partial class ComputeShaderDescriptorGenerator instanceMethods, constructors, constantDefinitions, + staticFieldDefinitions, diagnostics, token, isShaderEntryPoint); From 74820e1b57985acfbe88e8a2b5a26b5cfaf624db Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 22:24:48 +0100 Subject: [PATCH 04/11] Remove unnecessary ShaderSourceRewriter constructor Also fix the nullability of the shaderType field --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 38 +++---------------- 1 file changed, 5 insertions(+), 33 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index da4705af..5d51696c 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -24,7 +24,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// /// The type symbol for the shader type. /// - private readonly INamedTypeSymbol? shaderType; + private readonly INamedTypeSymbol shaderType; /// /// The collection of discovered static methods. @@ -92,7 +92,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter IDictionary staticFieldDefinitions, ImmutableArrayBuilder diagnostics, CancellationToken token, - bool isEntryPoint) + bool isEntryPoint = false) : base(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) { this.shaderType = shaderType; @@ -104,37 +104,6 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter this.isEntryPoint = isEntryPoint; } - /// - /// Creates a new instance with the specified parameters. - /// - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The set of discovered and processed static methods. - /// The collection of discovered instance methods for custom struct types. - /// The collection of discovered constructors for custom struct types. - /// The collection of discovered constant definitions. - /// The collection of discovered static field definitions. - /// The collection of produced instances. - /// The value for the current operation. - private ShaderSourceRewriter( - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary instanceMethods, - IDictionary constructors, - IDictionary constantDefinitions, - IDictionary staticFieldDefinitions, - ImmutableArrayBuilder diagnostics, - CancellationToken token) - : base(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) - { - this.staticMethods = staticMethods; - this.instanceMethods = instanceMethods; - this.constructors = constructors; - this.implicitVariables = []; - this.localFunctions = []; - } - /// /// Gets the collection of processed local functions in the current tree. /// @@ -543,6 +512,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter } ShaderSourceRewriter shaderSourceRewriter = new( + this.shaderType, SemanticModel, DiscoveredTypes, this.staticMethods, @@ -597,6 +567,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter } ShaderSourceRewriter shaderSourceRewriter = new( + this.shaderType, SemanticModel, DiscoveredTypes, this.instanceMethods, @@ -685,6 +656,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter } ShaderSourceRewriter shaderSourceRewriter = new( + this.shaderType, SemanticModel, DiscoveredTypes, this.instanceMethods, From dedfbd87287d877f51588b8522993bd03cb9dff7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 22:40:29 +0100 Subject: [PATCH 05/11] Use primary constructor in ShaderSourceRewriter --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 76 ++++++++----------- 1 file changed, 31 insertions(+), 45 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index 5d51696c..f771423e 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -19,42 +19,65 @@ namespace ComputeSharp.SourceGeneration.SyntaxRewriters; /// /// A custom type that processes C# methods to convert to HLSL compliant code. /// -internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter +/// The type symbol for the shader type. +/// The instance for the target syntax tree. +/// The set of discovered custom types. +/// The set of discovered and processed static methods. +/// The collection of discovered instance methods for custom struct types. +/// The collection of discovered constructors for custom struct types. +/// The collection of discovered constant definitions. +/// The collection of discovered static field definitions. +/// The collection of produced instances. +/// The value for the current operation. +/// Whether or not the current instance is processing a shader entry point. +internal sealed partial class ShaderSourceRewriter( + INamedTypeSymbol shaderType, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary instanceMethods, + IDictionary constructors, + IDictionary constantDefinitions, + IDictionary staticFieldDefinitions, + ImmutableArrayBuilder diagnostics, + CancellationToken token, + bool isEntryPoint = false) + : HlslSourceRewriter(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) { /// /// The type symbol for the shader type. /// - private readonly INamedTypeSymbol shaderType; + private readonly INamedTypeSymbol shaderType = shaderType; /// /// The collection of discovered static methods. /// - private readonly IDictionary staticMethods; + private readonly IDictionary staticMethods = staticMethods; /// /// The collection of discovered instance methods for custom struct types. /// - private readonly IDictionary instanceMethods; + private readonly IDictionary instanceMethods = instanceMethods; /// /// The collection of discovered constructors for custom struct types. /// - private readonly IDictionary constructors; + private readonly IDictionary constructors = constructors; /// /// The collection of processed local functions in the current tree. /// - private readonly Dictionary localFunctions; + private readonly Dictionary localFunctions = []; /// /// The list of implicit variables to declare at the start of the body. /// - private readonly List implicitVariables; + private readonly List implicitVariables = []; /// /// Whether or not the current instance is processing a shader entry point. /// - private readonly bool isEntryPoint; + private readonly bool isEntryPoint = isEntryPoint; /// /// The identifier of the current , @@ -67,43 +90,6 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// private int localFunctionDepth; - /// - /// Creates a new instance with the specified parameters. - /// - /// The type symbol for the shader type. - /// The instance for the target syntax tree. - /// The set of discovered custom types. - /// The set of discovered and processed static methods. - /// The collection of discovered instance methods for custom struct types. - /// The collection of discovered constructors for custom struct types. - /// The collection of discovered constant definitions. - /// The collection of discovered static field definitions. - /// The collection of produced instances. - /// The value for the current operation. - /// Whether or not the current instance is processing a shader entry point. - public ShaderSourceRewriter( - INamedTypeSymbol shaderType, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary instanceMethods, - IDictionary constructors, - IDictionary constantDefinitions, - IDictionary staticFieldDefinitions, - ImmutableArrayBuilder diagnostics, - CancellationToken token, - bool isEntryPoint = false) - : base(semanticModel, discoveredTypes, constantDefinitions, staticFieldDefinitions, diagnostics, token) - { - this.shaderType = shaderType; - this.staticMethods = staticMethods; - this.instanceMethods = instanceMethods; - this.constructors = constructors; - this.localFunctions = []; - this.implicitVariables = []; - this.isEntryPoint = isEntryPoint; - } - /// /// Gets the collection of processed local functions in the current tree. /// From 1372d14a90ae3cb4eaf7f348b34a6adfe4232963 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 22:41:25 +0100 Subject: [PATCH 06/11] Enable tracking external static fields --- ...xelShaderDescriptorGenerator.HlslSource.cs | 6 +++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 39 +++++++++++++++++++ ...uteShaderDescriptorGenerator.HlslSource.cs | 6 +++ 3 files changed, 51 insertions(+) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index 2e00cabd..150cc289 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -286,6 +286,12 @@ partial class D2DPixelShaderDescriptorGenerator } } + // Also gather the external static fields (same as in the DX12 generator) + foreach ((string, string, string?) externalField in staticFieldDefinitions.Values) + { + builder.Add(externalField); + } + return builder.ToImmutable(); } diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index f771423e..b36a9aba 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -7,6 +7,7 @@ using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -366,6 +367,44 @@ internal sealed partial class ShaderSourceRewriter( { return updatedNode.Name; } + + // Handle static fields, but only if they're not in the shader type itself. If that is the case, they will already + // be discovered separately, when crawling all members of the shader type. Here we only gather external fields. + if (fieldOperation.Field.IsStatic && + !SymbolEqualityComparer.Default.Equals(fieldOperation.Field.ContainingType, this.shaderType)) + { + if (!StaticFieldDefinitions.TryGetValue(fieldOperation.Field, out (string Name, string, string?) info)) + { + // Execute the same logic as for shader static fields, to process them and extract the relevant info. + // In this case, we use the fully qualified name of the field as identifier, not just the field name. + if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( + this.shaderType, + fieldOperation.Field, + SemanticModel, + DiscoveredTypes, + ConstantDefinitions, + StaticFieldDefinitions, + Diagnostics, + CancellationToken, + out _, + out string? typeDeclaration, + out string? assignmentExpression, + out _)) + { + info.Name = fieldOperation.Field.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); + + StaticFieldDefinitions.Add(fieldOperation.Field, (info.Name, typeDeclaration, assignmentExpression)); + } + else + { + // We failed to process the field for whatever reason. Just stop rewriting it and return + // the current updated node. We'll have some diagnostic for this case emitted previously. + return updatedNode; + } + } + + return IdentifierName(info.Name); + } } // If the current member access is a field or property access, check the lookup table diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index c67dcfbe..6c60560f 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -300,6 +300,12 @@ partial class ComputeShaderDescriptorGenerator } } + // Also gather the external static fields + foreach ((string, string, string?) externalField in staticFieldDefinitions.Values) + { + builder.Add(externalField); + } + return builder.ToImmutable(); } From f84445207247431835523cb43f232a8bd53c2dc6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 23:42:29 +0100 Subject: [PATCH 07/11] Add unit test for simple external static accesses --- .../ComputeSharp.Tests/ShaderRewriterTests.cs | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index c0c30d32..7aeba85e 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -485,6 +485,77 @@ public partial class ShaderRewriterTests } } + [CombinatorialTestMethod] + [AllDevices] + public void ShaderWithMixedStaticFieldsInExternalTypes(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(16); + + device.Get().For(1, new MixedStaticFieldsInExternalTypesShader(buffer)); + + float[] results = buffer.ToArray(); + + Assert.AreEqual(3.14f, results[0]); + Assert.AreEqual(111, results[1]); + Assert.AreEqual(0, results[2]); + Assert.AreEqual(222, results[3]); + Assert.AreEqual(6.28f, results[4]); + Assert.AreEqual(42, results[5]); + Assert.AreEqual(0, results[6]); + Assert.AreEqual(333, results[7]); + Assert.AreEqual(2, results[8]); + Assert.AreEqual(444, results[9]); + Assert.AreEqual(123, results[10]); + Assert.AreEqual(666, results[11]); + } + + [AutoConstructor] + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MixedStaticFieldsInExternalTypesShader : IComputeShader + { + public static readonly float PI = 3.14f; + public static readonly int A = 111; + public static int B; + public static int C = 222; + + private readonly ReadWriteBuffer buffer; + + public void Execute() + { + // Read static fields from this shader + buffer[0] = PI; + buffer[1] = A; + buffer[2] = B; + buffer[3] = C; + + // Read static fields from an external type + buffer[4] = ExternalType.PI2; + buffer[5] = ExternalType.A; + buffer[6] = ExternalType.B; + buffer[7] = ExternalType.C; + + // Mutate the fields and check again + B += 2; + C *= 2; + ExternalType.B = 123; + ExternalType.C *= 2; + + buffer[8] = B; + buffer[9] = C; + buffer[10] = ExternalType.B; + buffer[11] = ExternalType.C; + } + } + + internal static class ExternalType + { + public static readonly float PI2 = 6.28f; + public static readonly int A = 42; + public static int B; + public static int C = 333; + } + // See https://github.com/Sergio0694/ComputeSharp/issues/278 [CombinatorialTestMethod] [AllDevices] From c0f1ad6a1ed0debeed3101e01b2987380b707e15 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Dec 2023 23:54:41 +0100 Subject: [PATCH 08/11] Handle member accesses for static shader fields --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 26 +++++++++++++------ .../ComputeSharp.Tests/ShaderRewriterTests.cs | 11 ++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index b36a9aba..d4d9584f 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -368,12 +368,22 @@ internal sealed partial class ShaderSourceRewriter( return updatedNode.Name; } - // Handle static fields, but only if they're not in the shader type itself. If that is the case, they will already - // be discovered separately, when crawling all members of the shader type. Here we only gather external fields. - if (fieldOperation.Field.IsStatic && - !SymbolEqualityComparer.Default.Equals(fieldOperation.Field.ContainingType, this.shaderType)) + // Handle static fields, which can be either in the shader type itself, or in external types + if (fieldOperation.Field.IsStatic) { - if (!StaticFieldDefinitions.TryGetValue(fieldOperation.Field, out (string Name, string, string?) info)) + (string Name, string, string?) fieldInfo; + + // Special case static fields in the shader type itself. Those are already discovered separately, when crawling + // all members of the shader type. But, if this path was hit, it means that they are accessed via a member access + // expression, which means they need to be rewritten to match the simple name they will have in the shader. This + // is often the case if they're accessed from external types. So we just map the name and use that expression. + if (SymbolEqualityComparer.Default.Equals(fieldOperation.Field.ContainingType, this.shaderType)) + { + _ = HlslKnownKeywords.TryGetMappedName(fieldOperation.Field.Name, out string? mappedFieldName); + + return IdentifierName(mappedFieldName ?? fieldOperation.Field.Name); + } + else if (!StaticFieldDefinitions.TryGetValue(fieldOperation.Field, out fieldInfo)) { // Execute the same logic as for shader static fields, to process them and extract the relevant info. // In this case, we use the fully qualified name of the field as identifier, not just the field name. @@ -391,9 +401,9 @@ internal sealed partial class ShaderSourceRewriter( out string? assignmentExpression, out _)) { - info.Name = fieldOperation.Field.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); + fieldInfo.Name = fieldOperation.Field.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); - StaticFieldDefinitions.Add(fieldOperation.Field, (info.Name, typeDeclaration, assignmentExpression)); + StaticFieldDefinitions.Add(fieldOperation.Field, (fieldInfo.Name, typeDeclaration, assignmentExpression)); } else { @@ -403,7 +413,7 @@ internal sealed partial class ShaderSourceRewriter( } } - return IdentifierName(info.Name); + return IdentifierName(fieldInfo.Name); } } diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index 7aeba85e..5290fabf 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -507,6 +507,8 @@ public partial class ShaderRewriterTests Assert.AreEqual(444, results[9]); Assert.AreEqual(123, results[10]); Assert.AreEqual(666, results[11]); + Assert.AreEqual(3.14f, results[12]); + Assert.AreEqual(3.14f, results[13]); } [AutoConstructor] @@ -545,6 +547,10 @@ public partial class ShaderRewriterTests buffer[9] = C; buffer[10] = ExternalType.B; buffer[11] = ExternalType.C; + + // Access shader fields via a member access + buffer[12] = MixedStaticFieldsInExternalTypesShader.PI; + buffer[13] = ExternalType.ReadPI(); } } @@ -554,6 +560,11 @@ public partial class ShaderRewriterTests public static readonly int A = 42; public static int B; public static int C = 333; + + public static float ReadPI() + { + return MixedStaticFieldsInExternalTypesShader.PI; + } } // See https://github.com/Sergio0694/ComputeSharp/issues/278 From 5973921567f7d481fee3479b815e9d62c059d090 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Dec 2023 00:47:00 +0100 Subject: [PATCH 09/11] Handle identifier names for all static shader fields --- .../SyntaxRewriters/HlslSourceRewriter.cs | 2 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 96 ++++++++++++------- .../ComputeSharp.Tests/ShaderRewriterTests.cs | 12 ++- 3 files changed, 76 insertions(+), 34 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index 8f43912a..6c6bb244 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -390,7 +390,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter } /// - public sealed override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) { IdentifierNameSyntax updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index d4d9584f..e71d9f25 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading; @@ -333,6 +334,26 @@ internal sealed partial class ShaderSourceRewriter( } } + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + // Intercept identifier names to catch whether we are accessing a static field from its containing type. + // This needs special handling, as it would not go through the usual member access path. If we are doing + // this, then we rewrite it with the shared logic for all static fields, otherwise we return the normal + // visit. Before getting semantic information, we can pre-filter to exclude invocation expressions and + // member access expressions. This is safe, because those two parent nodes would already be handled. + // We also only process fields from external types, as those in shader types don't need handling here. + // This is because they're lowered to the same identifier name, without fully qualified names to rewrite. + if (node.Parent is not (InvocationExpressionSyntax or MemberAccessExpressionSyntax) && + SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation { Field.IsStatic: true } operation && + !SymbolEqualityComparer.Default.Equals(operation.Field.ContainingType, this.shaderType)) + { + return VisitExternalStaticFieldAccess(null, operation.Field) ?? base.VisitIdentifierName(node); + } + + return base.VisitIdentifierName(node); + } + /// public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { @@ -371,8 +392,6 @@ internal sealed partial class ShaderSourceRewriter( // Handle static fields, which can be either in the shader type itself, or in external types if (fieldOperation.Field.IsStatic) { - (string Name, string, string?) fieldInfo; - // Special case static fields in the shader type itself. Those are already discovered separately, when crawling // all members of the shader type. But, if this path was hit, it means that they are accessed via a member access // expression, which means they need to be rewritten to match the simple name they will have in the shader. This @@ -383,37 +402,8 @@ internal sealed partial class ShaderSourceRewriter( return IdentifierName(mappedFieldName ?? fieldOperation.Field.Name); } - else if (!StaticFieldDefinitions.TryGetValue(fieldOperation.Field, out fieldInfo)) - { - // Execute the same logic as for shader static fields, to process them and extract the relevant info. - // In this case, we use the fully qualified name of the field as identifier, not just the field name. - if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( - this.shaderType, - fieldOperation.Field, - SemanticModel, - DiscoveredTypes, - ConstantDefinitions, - StaticFieldDefinitions, - Diagnostics, - CancellationToken, - out _, - out string? typeDeclaration, - out string? assignmentExpression, - out _)) - { - fieldInfo.Name = fieldOperation.Field.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); - StaticFieldDefinitions.Add(fieldOperation.Field, (fieldInfo.Name, typeDeclaration, assignmentExpression)); - } - else - { - // We failed to process the field for whatever reason. Just stop rewriting it and return - // the current updated node. We'll have some diagnostic for this case emitted previously. - return updatedNode; - } - } - - return IdentifierName(fieldInfo.Name); + return VisitExternalStaticFieldAccess(updatedNode, fieldOperation.Field); } } @@ -770,6 +760,48 @@ internal sealed partial class ShaderSourceRewriter( return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); } + /// + /// Visits a static field access in an external type and rewrites it as needed. + /// + /// The current instance for the static field. + /// The instance for . + /// The rewritten static field expression. + [return: NotNullIfNotNull(nameof(node))] + private SyntaxNode? VisitExternalStaticFieldAccess(SyntaxNode? node, IFieldSymbol fieldSymbol) + { + if (!StaticFieldDefinitions.TryGetValue(fieldSymbol, out (string Name, string, string?) fieldInfo)) + { + // Execute the same logic as for shader static fields, to process them and extract the relevant info. + // In this case, we use the fully qualified name of the field as identifier, not just the field name. + if (HlslDefinitionsSyntaxProcessor.TryGetStaticField( + this.shaderType, + fieldSymbol, + SemanticModel, + DiscoveredTypes, + ConstantDefinitions, + StaticFieldDefinitions, + Diagnostics, + CancellationToken, + out _, + out string? typeDeclaration, + out string? assignmentExpression, + out _)) + { + fieldInfo.Name = fieldSymbol.GetFullyQualifiedMetadataName().ToHlslIdentifierName(); + + StaticFieldDefinitions.Add(fieldSymbol, (fieldInfo.Name, typeDeclaration, assignmentExpression)); + } + else + { + // We failed to process the field for whatever reason. Just stop rewriting it and return + // the current updated node. We'll have some diagnostic for this case emitted previously. + return node; + } + } + + return IdentifierName(fieldInfo.Name); + } + /// /// Rewrites a sampled texture access. /// diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index 5290fabf..1a36df60 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -5,7 +5,7 @@ using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; -#pragma warning disable IDE0007, IDE0008, IDE0009 +#pragma warning disable IDE0002, IDE0007, IDE0008, IDE0009 namespace ComputeSharp.Tests; @@ -509,6 +509,7 @@ public partial class ShaderRewriterTests Assert.AreEqual(666, results[11]); Assert.AreEqual(3.14f, results[12]); Assert.AreEqual(3.14f, results[13]); + Assert.AreEqual(6.28f, results[14]); } [AutoConstructor] @@ -551,6 +552,9 @@ public partial class ShaderRewriterTests // Access shader fields via a member access buffer[12] = MixedStaticFieldsInExternalTypesShader.PI; buffer[13] = ExternalType.ReadPI(); + + // Access an external field as an identifier name + buffer[14] = ExternalType.ReadPI2(); } } @@ -565,6 +569,12 @@ public partial class ShaderRewriterTests { return MixedStaticFieldsInExternalTypesShader.PI; } + + // See https://github.com/Sergio0694/ComputeSharp/issues/298 + public static float ReadPI2() + { + return PI2; + } } // See https://github.com/Sergio0694/ComputeSharp/issues/278 From 785f33258128740b9fb43a014f0ad3d18cbb1b08 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Dec 2023 00:48:40 +0100 Subject: [PATCH 10/11] Optimize HlslSourceRewriter.VisitIdentifierName --- .../SyntaxRewriters/HlslSourceRewriter.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index 6c6bb244..e035e44a 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -394,7 +394,11 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter { IdentifierNameSyntax updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - if (SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && + // Only gather constants directly accessed by name. We can also pre-filter to exclude invocations + // and member access expressions, as those will be handled separately. Doing so avoids unnecessarily + // retrieving semantic information for every identifier, which would otherwise be fairly expensive. + if (node.Parent is not (InvocationExpressionSyntax or MemberAccessExpressionSyntax) && + SemanticModel.For(node).GetOperation(node) is IFieldReferenceOperation operation && operation.Field.IsConst && operation.Type!.TypeKind != TypeKind.Enum) { From b832874e551c8403d3f471772899896419f61339 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Dec 2023 01:01:03 +0100 Subject: [PATCH 11/11] Track [D2DRequiresScenePosition] from external static fields --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 12 ++++-------- .../SyntaxRewriters/ShaderSourceRewriter.cs | 10 ++++++++-- .../SyntaxRewriters/ShaderSourceRewriter.cs | 8 +------- 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 4ddd4301..9b505839 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -29,18 +29,14 @@ partial class ShaderSourceRewriter } /// - private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) + partial void TrackKnownMethodInvocation(string metadataName) { - // No special tracking is needed for D2D1 shaders + NeedsD2DRequiresScenePositionAttribute |= HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName); } /// - private partial void TrackKnownMethodInvocation(string metadataName) + partial void TrackExternalStaticField(StaticFieldRewriter staticFieldRewriter) { - // Track whether the method needs [D2DRequiresScenePosition] - if (HlslKnownMethods.NeedsD2DRequiresScenePositionAttribute(metadataName)) - { - NeedsD2DRequiresScenePositionAttribute = true; - } + NeedsD2DRequiresScenePositionAttribute |= staticFieldRewriter.NeedsD2DRequiresScenePositionAttribute; } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs index e71d9f25..30ccf728 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -817,11 +817,17 @@ internal sealed partial class ShaderSourceRewriter( /// The instance for the operation. /// The instance for the operation. /// The mapped name for the property access. - private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName); + partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName); /// /// Tracks a method invocation for a known HLSL method. /// /// The metadata name of the method being invoked. - private partial void TrackKnownMethodInvocation(string metadataName); + partial void TrackKnownMethodInvocation(string metadataName); + + /// + /// Tracks an access to an external static field. + /// + /// The instance used to rewrite the field expression. + partial void TrackExternalStaticField(StaticFieldRewriter staticFieldRewriter); } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 4d684730..9a7b0748 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -48,7 +48,7 @@ partial class ShaderSourceRewriter } /// - private partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) + partial void TrackKnownPropertyAccess(IMemberReferenceOperation operation, MemberAccessExpressionSyntax node, string mappedName) { // Mark which dispatch properties have been used, to optimize the declaration afterwards if (operation.Member.IsStatic) @@ -88,10 +88,4 @@ partial class ShaderSourceRewriter } } } - - /// - private partial void TrackKnownMethodInvocation(string metadataName) - { - // No special tracking is needed for DX12 compute shaders - } } \ No newline at end of file