Enable constructors support in DX12 shaders

このコミットが含まれているのは:
Sergio Pedri committed 2023-12-02 19:13:26 +01:00
1 親 f6a39ef48a
コミット b685f09d06
5ファイル変更
+231 -29

検索条件に一致するファイルはありません

@@ -46,12 +46,14 @@ internal static class HlslDefinitionsSyntaxProcessor
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
public static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
IEnumerable<INamedTypeSymbol> types,
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods)
IReadOnlyDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IReadOnlyDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> 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<IMethodSymbol, (MethodDeclarationSyntax Stub, MethodDeclarationSyntax Ctor)> 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,
+57 -16
ファイルの表示
@@ -118,37 +118,64 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <returns>The rewritten <see cref="SyntaxNode"/> for the object creation expression.</returns>
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, "<invalid>");
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);
}
/// <inheritdoc/>
@@ -364,4 +391,18 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
return updatedToken.WithoutTrivia();
}
/// <inheritdoc cref="VisitObjectCreationExpression(ObjectCreationExpressionSyntax)"/>
/// <param name="node">The original input <see cref="BaseObjectCreationExpressionSyntax"/> instance.</param>
/// <param name="updatedNode">The updated <see cref="BaseObjectCreationExpressionSyntax"/> instance with tweaked syntax.</param>
/// <param name="targetType">The <see cref="TypeSyntax"/> for the object being created.</param>
/// <returns>The rewritten <see cref="SyntaxNode"/> for the object creation expression.</returns>
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)));
}
}
+152 -5
ファイルの表示
@@ -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;
/// <summary>
@@ -37,6 +35,11 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// </summary>
private readonly IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods;
/// <summary>
/// The collection of discovered constructors for custom struct types.
/// </summary>
private readonly IDictionary<IMethodSymbol, (MethodDeclarationSyntax Stub, MethodDeclarationSyntax Ctor)> constructors;
/// <summary>
/// The collection of processed local functions in the current tree.
/// </summary>
@@ -53,7 +56,8 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
private readonly bool isEntryPoint;
/// <summary>
/// The identifier of the current <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> tree being visited.
/// The identifier of the current <see cref="ConstructorDeclarationSyntax"/>, <see cref="MethodDeclarationSyntax"/>
/// or <see cref="LocalFunctionStatementSyntax"/> tree being visited (used to rewrite local functions).
/// </summary>
private SyntaxToken currentMethodIdentifier;
@@ -70,6 +74,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
@@ -79,6 +84,7 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> 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
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
private ShaderSourceRewriter(
@@ -106,12 +114,14 @@ internal sealed partial class ShaderSourceRewriter : HlslSourceRewriter
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
ImmutableArrayBuilder<DiagnosticInfo> 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
/// </summary>
public IReadOnlyDictionary<string, LocalFunctionStatementSyntax> LocalFunctions => this.localFunctions;
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
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;
}
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
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;
}
/// <inheritdoc/>
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<ArgumentSyntax> 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 <TYPE_NAME> __ctor(<PARAMETERS>)
// {
// <TYPE_NAME> __this;
//
// __this.__ctor__init(<PARAMETERS>);
//
// 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(<PARAMETERS>)
// {
// <CONSTRUCTOR_STATEMENTS>
// }
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:
//
// <TYPE_NAME>::__ctor(...)
return
InvocationExpression(IdentifierName($"{returnTypeHlslIdentifier}::__ctor"))
.WithArgumentList(updatedNode.ArgumentList!);
}
return base.VisitUserDefinedObjectCreationExpression(node, updatedNode, targetType);
}
/// <summary>
/// Rewrites a sampled texture access.
/// </summary>
+7 -1
ファイルの表示
@@ -57,6 +57,7 @@ partial class ComputeShaderDescriptorGenerator
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> 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
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <param name="constructors">The collection of discovered constructors for custom struct types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
@@ -370,6 +374,7 @@ partial class ComputeShaderDescriptorGenerator
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods,
IDictionary<IMethodSymbol, (MethodDeclarationSyntax, MethodDeclarationSyntax)> constructors,
IDictionary<IFieldSymbol, string> constantDefinitions,
bool isComputeShader,
CancellationToken token)
@@ -419,6 +424,7 @@ partial class ComputeShaderDescriptorGenerator
discoveredTypes,
staticMethods,
instanceMethods,
constructors,
constantDefinitions,
diagnostics,
isShaderEntryPoint);
+6 -6
ファイルの表示
@@ -670,19 +670,19 @@ partial class DiagnosticDescriptors
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a method invocation that is not valid from a shader.
/// Gets a <see cref="DiagnosticDescriptor"/> for a method or constructor invocation that is not valid from a shader.
/// <para>
/// Format: <c>"The method {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)"</c>.
/// Format: <c>"The method or constructor {0} cannot be used in a shader (methods need to either be HLSL intrinsics or with source available for analysis)"</c>.
/// </para>
/// </summary>
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");
/// <summary>