From b685f09d06e185d65238e99f1cd0f347ccb4be41 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 2 Dec 2023 19:13:26 +0100 Subject: [PATCH] Enable constructors support in DX12 shaders --- .../HlslDefinitionsSyntaxProcessor.cs | 10 +- .../SyntaxRewriters/HlslSourceRewriter.cs | 73 ++++++-- .../SyntaxRewriters/ShaderSourceRewriter.cs | 157 +++++++++++++++++- ...uteShaderDescriptorGenerator.HlslSource.cs | 8 +- .../Diagnostics/DiagnosticDescriptors.cs | 12 +- 5 files changed, 231 insertions(+), 29 deletions(-) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs index 74bb3aa0..98dd60fe 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslDefinitionsSyntaxProcessor.cs @@ -46,12 +46,14 @@ internal static class HlslDefinitionsSyntaxProcessor /// The type symbol for the shader type. /// The sequence of discovered custom types. /// The collection of discovered instance methods for custom struct types. + /// The collection of discovered constructors for custom struct types. /// A sequence of custom type definitions to add to the shader source. public static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes( ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, IEnumerable types, - IReadOnlyDictionary instanceMethods) + IReadOnlyDictionary instanceMethods, + IReadOnlyDictionary constructors) { using ImmutableArrayBuilder<(string, string)> builder = new(); @@ -104,6 +106,12 @@ internal static class HlslDefinitionsSyntaxProcessor structDeclaration = structDeclaration.AddMembers(method.Value); } + // Also do the same for all constructors + foreach (KeyValuePair methods in constructors.Where(pair => SymbolEqualityComparer.Default.Equals(pair.Key.ContainingType, type))) + { + structDeclaration = structDeclaration.AddMembers(methods.Value.Stub, methods.Value.Ctor); + } + // Insert the trailing ; right after the closing bracket (after normalization) builder.Add(( structType, diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs index 344ec29d..9ccbdbf5 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/HlslSourceRewriter.cs @@ -118,37 +118,64 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// The rewritten for the object creation expression. private SyntaxNode VisitObjectCreationExpression(BaseObjectCreationExpressionSyntax node, BaseObjectCreationExpressionSyntax updatedNode, TypeSyntax targetType) { - // Emit a diagnostic if the object being created is not valid (ie. it's a managed type) - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type) + ITypeSymbol? typeSymbol = SemanticModel.For(node).GetTypeInfo(node).Type; + + // Handle the edge case of the type being null (shouldn't really happen) + if (typeSymbol is null) { - Diagnostics.Add(InvalidObjectCreationExpression, node, type); + Diagnostics.Add(InvalidObjectCreationExpression, node, ""); + + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } + + // Emit a diagnostic if the object being created is not valid (ie. it's a managed type) + if (!typeSymbol.IsUnmanagedType) + { + Diagnostics.Add(InvalidObjectCreationExpression, node, typeSymbol); + + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } // Mutate the syntax like with explicit object creation expressions. This also handles object // initializer expressions. If those are used, the HLSL will just contain a default expression. // There is a diagnostic being emitted to inform the users if that path is hit. If users want // to create an object and immediately set some values, they should use a factory method. - if (updatedNode is not { ArgumentList.Arguments.Count: > 0, Initializer: null }) + if (updatedNode is not { ArgumentList.Arguments.Count: >= 0, Initializer: null }) { return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } - // Add explicit casts like with the explicit object creation expressions above - if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol matrixType && - HlslKnownTypes.IsMatrixType(matrixType.GetFullyQualifiedMetadataName())) - { - for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) - { - IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; - INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; + string typeName = typeSymbol.GetFullyQualifiedMetadataName(); - updatedNode = updatedNode.ReplaceNode( - updatedNode.ArgumentList!.Arguments[i].Expression, - CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); + if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + // Special when we have no arguments, ie. we're calling the default parameterless constructor. + // We need to add this check here because for user defined types, there may be explicit constructors. + if (updatedNode.ArgumentList.Arguments.Count == 0) + { + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); } + + // Add explicit casts to each individual argument + if (HlslKnownTypes.IsMatrixType(typeName)) + { + for (int i = 0; i < node.ArgumentList!.Arguments.Count; i++) + { + IArgumentOperation argumentOperation = (IArgumentOperation)SemanticModel.For(node).GetOperation(node.ArgumentList.Arguments[i])!; + INamedTypeSymbol elementType = (INamedTypeSymbol)argumentOperation.Parameter!.Type; + + updatedNode = updatedNode.ReplaceNode( + updatedNode.ArgumentList!.Arguments[i].Expression, + CastExpression(IdentifierName(HlslKnownTypes.GetMappedName(elementType)), updatedNode.ArgumentList.Arguments[i].Expression)); + } + } + + // In either case, for built-in HLSL types, we can just invoke the constructor directly + return InvocationExpression(targetType, updatedNode.ArgumentList!); } - return InvocationExpression(targetType, updatedNode.ArgumentList!); + // We're invoking a user defined constructor + return VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); } /// @@ -364,4 +391,18 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter return updatedToken.WithoutTrivia(); } + + /// + /// The original input instance. + /// The updated instance with tweaked syntax. + /// The for the object being created. + /// The rewritten for the object creation expression. + protected virtual SyntaxNode VisitUserDefinedObjectCreationExpression( + BaseObjectCreationExpressionSyntax node, + BaseObjectCreationExpressionSyntax updatedNode, + TypeSyntax targetType) + { + // By default, constructors are not supported, so just return an empty value + return CastExpression(targetType, LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0))); + } } \ 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 5d540445..206870e5 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxRewriters/ShaderSourceRewriter.cs @@ -13,8 +13,6 @@ using Microsoft.CodeAnalysis.Operations; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -#pragma warning disable IDE0052 - namespace ComputeSharp.SourceGeneration.SyntaxRewriters; /// @@ -37,6 +35,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// private readonly IDictionary instanceMethods; + /// + /// The collection of discovered constructors for custom struct types. + /// + private readonly IDictionary constructors; + /// /// The collection of processed local functions in the current tree. /// @@ -53,7 +56,8 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter private readonly bool isEntryPoint; /// - /// The identifier of the current or tree being visited. + /// The identifier of the current , + /// or tree being visited (used to rewrite local functions). /// private SyntaxToken currentMethodIdentifier; @@ -70,6 +74,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// 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 produced instances. /// Whether or not the current instance is processing a shader entry point. @@ -79,6 +84,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, + IDictionary constructors, IDictionary constantDefinitions, ImmutableArrayBuilder diagnostics, bool isEntryPoint) @@ -87,6 +93,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter this.shaderType = shaderType; this.staticMethods = staticMethods; this.instanceMethods = instanceMethods; + this.constructors = constructors; this.localFunctions = []; this.implicitVariables = []; this.isEntryPoint = isEntryPoint; @@ -99,6 +106,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// 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 produced instances. private ShaderSourceRewriter( @@ -106,12 +114,14 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, + IDictionary constructors, IDictionary constantDefinitions, ImmutableArrayBuilder diagnostics) : base(semanticModel, discoveredTypes, constantDefinitions, diagnostics) { this.staticMethods = staticMethods; this.instanceMethods = instanceMethods; + this.constructors = constructors; this.implicitVariables = []; this.localFunctions = []; } @@ -121,6 +131,37 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter /// public IReadOnlyDictionary LocalFunctions => this.localFunctions; + /// + public ConstructorDeclarationSyntax? Visit(ConstructorDeclarationSyntax? node) + { + if (node is null) + { + return null; + } + + this.currentMethodIdentifier = node.Identifier; + + // Constructors have no return type, so there is no return type identifier to replace. + // We simply track the type of the type being constructed and then continue normally. + // This is done separately where the constructor operation is being processed. + ConstructorDeclarationSyntax? updatedNode = (ConstructorDeclarationSyntax?)base.Visit(node)!; + + if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword))) + { + Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node); + } + + if (updatedNode is not null) + { + BlockSyntax implicitBlock = Block(this.implicitVariables.Select(static v => LocalDeclarationStatement(v)).ToArray()); + + // Add the tracked implicit declarations (at the start of the body) + updatedNode = updatedNode.WithBody(implicitBlock).AddBodyStatements([.. updatedNode.Body!.Statements]); + } + + return updatedNode; + } + /// public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) { @@ -481,7 +522,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) { - Diagnostics.Add(InvalidMethodCall, node, method); + Diagnostics.Add(InvalidMethodOrConstructorCall, node, method); return updatedNode; } @@ -491,6 +532,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter DiscoveredTypes, this.staticMethods, this.instanceMethods, + this.constructors, ConstantDefinitions, Diagnostics); @@ -534,7 +576,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter { if (method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not MethodDeclarationSyntax methodNode) { - Diagnostics.Add(InvalidMethodCall, node, method); + Diagnostics.Add(InvalidMethodOrConstructorCall, node, method); return updatedNode; } @@ -544,6 +586,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter DiscoveredTypes, this.instanceMethods, this.instanceMethods, + this.constructors, ConstantDefinitions, Diagnostics); @@ -591,6 +634,110 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter return updatedNode; } + /// + protected override SyntaxNode VisitUserDefinedObjectCreationExpression( + BaseObjectCreationExpressionSyntax node, + BaseObjectCreationExpressionSyntax updatedNode, + TypeSyntax targetType) + { + if (SemanticModel.For(node).GetOperation(node) is IObjectCreationOperation { Constructor: IMethodSymbol constructor, Type: INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol }) + { + DiscoveredTypes.Add(typeSymbol); + + // If there are no arguments, check that the constructor is explicitly defined and is not + // the default parameterless constructor. In that case, we just fallback to a default value. + if (updatedNode.ArgumentList is not { Arguments.Count: > 0 } && constructor.IsImplicitlyDeclared) + { + return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); + } + + string returnTypeHlslIdentifier = typeSymbol.GetFullyQualifiedName().ToHlslIdentifierName(); + + if (!this.constructors.ContainsKey(constructor)) + { + if (constructor.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not ConstructorDeclarationSyntax constructorNode) + { + Diagnostics.Add(InvalidMethodOrConstructorCall, node, constructor); + + return updatedNode; + } + + ShaderSourceRewriter shaderSourceRewriter = new( + SemanticModel, + DiscoveredTypes, + this.instanceMethods, + this.instanceMethods, + this.constructors, + ConstantDefinitions, + Diagnostics); + + ConstructorDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(constructorNode)!.WithoutTrivia(); + + // Extracts the arguments from the list of parameters of the current method + ArgumentSyntax[] ExtractArguments() + { + using ImmutableArrayBuilder arguments = new(); + + foreach (ParameterSyntax parameter in processedMethod.ParameterList.Parameters) + { + arguments.Add(Argument(IdentifierName(parameter.Identifier.Text))); + } + + return arguments.ToArray(); + } + + // Create a static method acting as the constructor stub: + // + // static __ctor() + // { + // __this; + // + // __this.__ctor__init(); + // + // return __this; + // } + MethodDeclarationSyntax stubNode = + MethodDeclaration(IdentifierName(returnTypeHlslIdentifier), "__ctor") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .WithParameterList(processedMethod.ParameterList) + .AddBodyStatements( + LocalDeclarationStatement( + VariableDeclaration(IdentifierName(returnTypeHlslIdentifier)) + .AddVariables(VariableDeclarator(Identifier("__this")))), + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__this"), + IdentifierName("__ctor__init"))) + .AddArgumentListArguments(ExtractArguments())), + ReturnStatement(IdentifierName("__this"))); + + // Create the actual constructor to invoke, as an instance method: + // + // void __ctor__init() + // { + // + // } + MethodDeclarationSyntax ctorNode = + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), "__ctor__init") + .WithParameterList(processedMethod.ParameterList) + .WithBody(processedMethod.Body); + + this.constructors.Add(constructor, (stubNode, ctorNode)); + } + + // Rewrite the expression to invoke the rewritten constructor: + // + // ::__ctor(...) + return + InvocationExpression(IdentifierName($"{returnTypeHlslIdentifier}::__ctor")) + .WithArgumentList(updatedNode.ArgumentList!); + } + + return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType); + } + /// /// Rewrites a sampled texture access. /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs index 0ee84697..f749251b 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslSource.cs @@ -57,6 +57,7 @@ partial class ComputeShaderDescriptorGenerator HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary instanceMethods = new(SymbolEqualityComparer.Default); + Dictionary constructors = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Setup the semantic model and basic properties @@ -90,6 +91,7 @@ partial class ComputeShaderDescriptorGenerator discoveredTypes, staticMethods, instanceMethods, + constructors, constantDefinitions, isComputeShader, token); @@ -112,7 +114,8 @@ partial class ComputeShaderDescriptorGenerator diagnostics, structDeclarationSymbol, discoveredTypes, - instanceMethods); + instanceMethods, + constructors); token.ThrowIfCancellationRequested(); @@ -359,6 +362,7 @@ partial class ComputeShaderDescriptorGenerator /// The collection of currently discovered 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. /// Indicates whether or not represents a compute shader. /// The used to cancel the operation, if needed. @@ -370,6 +374,7 @@ partial class ComputeShaderDescriptorGenerator ICollection discoveredTypes, IDictionary staticMethods, IDictionary instanceMethods, + IDictionary constructors, IDictionary constantDefinitions, bool isComputeShader, CancellationToken token) @@ -419,6 +424,7 @@ partial class ComputeShaderDescriptorGenerator discoveredTypes, staticMethods, instanceMethods, + constructors, constantDefinitions, diagnostics, isShaderEntryPoint); diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 3e77eb76..e4f5f35e 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -670,19 +670,19 @@ partial class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for a method invocation that is not valid from a shader. + /// Gets a for a method or constructor invocation that is not valid from a shader. /// - /// Format: "The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)". + /// Format: "The method or constructor {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)". /// /// - public static readonly DiagnosticDescriptor InvalidMethodCall = new( + public static readonly DiagnosticDescriptor InvalidMethodOrConstructorCall = new( id: "CMPS0049", - title: "Invalid method invocation from a shader", - messageFormat: "The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)", + title: "Invalid method or constructor invocation from a shader", + messageFormat: "The method or constructor {0} cannot be used in a shader (methods or constructors need to either be HLSL intrinsics or with source available for analysis)", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "Shaders can only invoke methods that are either HLSL intrinsics or with source available for analysis.", + description: "Shaders can only invoke methods or constructors that are either HLSL intrinsics or with source available for analysis.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); ///