Code refactoring in IShaderGenerator
このコミットが含まれているのは:
1 親
1262bf6e0e
コミット
0004353052
13ファイル変更
+1897
-1835
検索条件に一致するファイルはありません
+207
-203
@@ -14,241 +14,245 @@ namespace ComputeSharp.SourceGenerators;
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
|
||||
/// </summary>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo)
|
||||
/// <inheritdoc/>
|
||||
internal static partial class BuildHlslString
|
||||
{
|
||||
ImmutableArray<StatementSyntax> bodyStatements = GenerateRenderMethodBody(hlslSourceInfo);
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.VoidKeyword)),
|
||||
Identifier("BuildHlslString"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")),
|
||||
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
|
||||
.WithBody(Block(bodyStatements));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Produces the series of statements to build the current HLSL source.
|
||||
/// </summary>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
|
||||
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo)
|
||||
{
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
StringBuilder textBuilder = new();
|
||||
int capturedDelegates = 0;
|
||||
int prologueStatements = 0;
|
||||
int sizeHint = 64;
|
||||
|
||||
void AppendLF()
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
|
||||
/// </summary>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(HlslSourceInfo hlslSourceInfo)
|
||||
{
|
||||
textBuilder.Append('\n');
|
||||
ImmutableArray<StatementSyntax> bodyStatements = GenerateRenderMethodBody(hlslSourceInfo);
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.VoidKeyword)),
|
||||
Identifier("BuildHlslString"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")),
|
||||
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
|
||||
.WithBody(Block(bodyStatements));
|
||||
}
|
||||
|
||||
void AppendLine(string text)
|
||||
/// <summary>
|
||||
/// Produces the series of statements to build the current HLSL source.
|
||||
/// </summary>
|
||||
/// <param name="hlslSourceInfo">The input <see cref="HlslSourceInfo"/> instance to use.</param>
|
||||
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo)
|
||||
{
|
||||
textBuilder.Append(text);
|
||||
}
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
StringBuilder textBuilder = new();
|
||||
int capturedDelegates = 0;
|
||||
int prologueStatements = 0;
|
||||
int sizeHint = 64;
|
||||
|
||||
void AppendParsedStatement(string text)
|
||||
{
|
||||
FlushText();
|
||||
|
||||
statements.Add(ParseStatement(text));
|
||||
}
|
||||
|
||||
void FlushText()
|
||||
{
|
||||
if (textBuilder.Length > 0)
|
||||
void AppendLF()
|
||||
{
|
||||
string text = textBuilder.ToString();
|
||||
|
||||
textBuilder.Append(text);
|
||||
|
||||
sizeHint += textBuilder.Length;
|
||||
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text))))));
|
||||
|
||||
textBuilder.Clear();
|
||||
textBuilder.Append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
// Declare the hashsets to track imported members and types from delegates, if needed
|
||||
if (!hlslSourceInfo.Delegates.IsEmpty)
|
||||
{
|
||||
void DeclareMapping(int index, string name, IEnumerable<string> items)
|
||||
void AppendLine(string text)
|
||||
{
|
||||
// global::System.Collections.Generic.HashSet<string> <NAME> = new();
|
||||
statements.Insert(index,
|
||||
LocalDeclarationStatement(VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Collections.Generic.HashSet"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier(name))
|
||||
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
|
||||
textBuilder.Append(text);
|
||||
}
|
||||
|
||||
prologueStatements++;
|
||||
void AppendParsedStatement(string text)
|
||||
{
|
||||
FlushText();
|
||||
|
||||
// <NAME>.Add("<ITEM>");
|
||||
foreach (var item in items)
|
||||
statements.Add(ParseStatement(text));
|
||||
}
|
||||
|
||||
void FlushText()
|
||||
{
|
||||
if (textBuilder.Length > 0)
|
||||
{
|
||||
string text = textBuilder.ToString();
|
||||
|
||||
textBuilder.Append(text);
|
||||
|
||||
sizeHint += textBuilder.Length;
|
||||
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text))))));
|
||||
|
||||
textBuilder.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Declare the hashsets to track imported members and types from delegates, if needed
|
||||
if (!hlslSourceInfo.Delegates.IsEmpty)
|
||||
{
|
||||
void DeclareMapping(int index, string name, IEnumerable<string> items)
|
||||
{
|
||||
// global::System.Collections.Generic.HashSet<string> <NAME> = new();
|
||||
statements.Insert(index,
|
||||
LocalDeclarationStatement(VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Collections.Generic.HashSet"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier(name))
|
||||
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
|
||||
|
||||
prologueStatements++;
|
||||
|
||||
// <NAME>.Add("<ITEM>");
|
||||
foreach (var item in items)
|
||||
{
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(name),
|
||||
IdentifierName("Add")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
|
||||
|
||||
prologueStatements++;
|
||||
}
|
||||
}
|
||||
|
||||
DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes);
|
||||
DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
|
||||
DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);
|
||||
|
||||
// Go through all existing delegate fields, if any
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
// global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier($"__{fieldName}Attribute"))
|
||||
.WithInitializer(
|
||||
EqualsValueClause(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
|
||||
IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
|
||||
.AddArgumentListArguments(
|
||||
Argument(IdentifierName(fieldName)),
|
||||
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
|
||||
|
||||
capturedDelegates++;
|
||||
prologueStatements++;
|
||||
}
|
||||
}
|
||||
|
||||
// Header and thread ids
|
||||
AppendLine(hlslSourceInfo.HeaderAndThreadsX);
|
||||
AppendParsedStatement("builder.Append(threadsX);");
|
||||
AppendLine(hlslSourceInfo.ThreadsY);
|
||||
AppendParsedStatement("builder.Append(threadsY);");
|
||||
AppendLine(hlslSourceInfo.ThreadsZ);
|
||||
AppendParsedStatement("builder.Append(threadsZ);");
|
||||
|
||||
// Define declarations
|
||||
AppendLine(hlslSourceInfo.Defines);
|
||||
|
||||
// Defines from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
|
||||
}
|
||||
|
||||
// Static fields and declared types
|
||||
AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);
|
||||
|
||||
// Declared types from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
|
||||
}
|
||||
|
||||
// Captured variables
|
||||
AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);
|
||||
|
||||
// Forward declarations from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
|
||||
}
|
||||
|
||||
// Remove all forward declarations from methods that are embedded into the shader.
|
||||
// This is necessary to avoid duplicate definitions from methods from delegates.
|
||||
if (capturedDelegates > 0)
|
||||
{
|
||||
// <NAME>.Add("<ITEM>");
|
||||
foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
|
||||
{
|
||||
FlushText();
|
||||
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(name),
|
||||
IdentifierName("Add")))
|
||||
IdentifierName("__methodNames"),
|
||||
IdentifierName("Remove")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
|
||||
|
||||
prologueStatements++;
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
|
||||
}
|
||||
}
|
||||
|
||||
DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes);
|
||||
DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
|
||||
DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);
|
||||
// Captured methods
|
||||
AppendLine(hlslSourceInfo.CapturedMethods);
|
||||
|
||||
// Go through all existing delegate fields, if any
|
||||
// Captured methods from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
// global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier($"__{fieldName}Attribute"))
|
||||
.WithInitializer(
|
||||
EqualsValueClause(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
|
||||
IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
|
||||
.AddArgumentListArguments(
|
||||
Argument(IdentifierName(fieldName)),
|
||||
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
|
||||
|
||||
capturedDelegates++;
|
||||
prologueStatements++;
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
|
||||
}
|
||||
}
|
||||
|
||||
// Header and thread ids
|
||||
AppendLine(hlslSourceInfo.HeaderAndThreadsX);
|
||||
AppendParsedStatement("builder.Append(threadsX);");
|
||||
AppendLine(hlslSourceInfo.ThreadsY);
|
||||
AppendParsedStatement("builder.Append(threadsY);");
|
||||
AppendLine(hlslSourceInfo.ThreadsZ);
|
||||
AppendParsedStatement("builder.Append(threadsZ);");
|
||||
|
||||
// Define declarations
|
||||
AppendLine(hlslSourceInfo.Defines);
|
||||
|
||||
// Defines from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
|
||||
}
|
||||
|
||||
// Static fields and declared types
|
||||
AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);
|
||||
|
||||
// Declared types from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
|
||||
}
|
||||
|
||||
// Captured variables
|
||||
AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);
|
||||
|
||||
// Forward declarations from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
|
||||
}
|
||||
|
||||
// Remove all forward declarations from methods that are embedded into the shader.
|
||||
// This is necessary to avoid duplicate definitions from methods from delegates.
|
||||
if (capturedDelegates > 0)
|
||||
{
|
||||
// <NAME>.Add("<ITEM>");
|
||||
foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
|
||||
// Captured delegate methods
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
FlushText();
|
||||
AppendLF();
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
|
||||
AppendLF();
|
||||
}
|
||||
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
// Entry point
|
||||
AppendLine(hlslSourceInfo.EntryPoint);
|
||||
|
||||
FlushText();
|
||||
|
||||
// builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(<SIZE_HINT>);
|
||||
statements.Insert(
|
||||
prologueStatements,
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("builder"),
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("__methodNames"),
|
||||
IdentifierName("Remove")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
|
||||
}
|
||||
IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
|
||||
IdentifierName("Create")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(sizeHint)))))));
|
||||
|
||||
return statements.ToImmutable();
|
||||
}
|
||||
|
||||
// Captured methods
|
||||
AppendLine(hlslSourceInfo.CapturedMethods);
|
||||
|
||||
// Captured methods from captured delegates
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
|
||||
}
|
||||
|
||||
// Captured delegate methods
|
||||
foreach (string fieldName in hlslSourceInfo.Delegates)
|
||||
{
|
||||
AppendLF();
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
|
||||
AppendLF();
|
||||
}
|
||||
|
||||
// Entry point
|
||||
AppendLine(hlslSourceInfo.EntryPoint);
|
||||
|
||||
FlushText();
|
||||
|
||||
// builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(<SIZE_HINT>);
|
||||
statements.Insert(
|
||||
prologueStatements,
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("builder"),
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
|
||||
IdentifierName("Create")))
|
||||
.AddArgumentListArguments(
|
||||
Argument(LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(sizeHint)))))));
|
||||
|
||||
return statements.ToImmutable();
|
||||
}
|
||||
}
|
||||
ファイル差分が大きすぎるため表示されません。
差分を読み込み
+70
-66
@@ -13,82 +13,86 @@ namespace ComputeSharp.SourceGenerators;
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
|
||||
/// </summary>
|
||||
///<param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
|
||||
private static MethodDeclarationSyntax CreateGetDispatchIdMethod(ImmutableArray<string> delegateFieldNames)
|
||||
/// <inheritdoc/>
|
||||
private static partial class GetDispatchId
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("GetDispatchId"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithBody(GetShaderHashCodeBody(delegateFieldNames));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
|
||||
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
|
||||
[Pure]
|
||||
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
|
||||
{
|
||||
if (delegateFieldNames.Length == 0)
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
|
||||
/// </summary>
|
||||
///<param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> delegateFieldNames)
|
||||
{
|
||||
// return 0;
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
Block(ReturnStatement(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))));
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.IntKeyword)),
|
||||
Identifier("GetDispatchId"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.WithBody(GetShaderHashCodeBody(delegateFieldNames));
|
||||
}
|
||||
|
||||
List<StatementSyntax> blockStatements = new(4);
|
||||
|
||||
// global::System.HashCode hashCode = default;
|
||||
blockStatements.Add(LocalDeclarationStatement(
|
||||
VariableDeclaration(IdentifierName("global::System.HashCode"))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("hashCode"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
LiteralExpression(
|
||||
SyntaxKind.DefaultLiteralExpression,
|
||||
Token(SyntaxKind.DefaultKeyword)))))));
|
||||
|
||||
foreach (string fieldName in delegateFieldNames)
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
|
||||
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
|
||||
[Pure]
|
||||
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
|
||||
{
|
||||
// hashCode.Add(delegateField.Method);
|
||||
blockStatements.Add(ExpressionStatement(
|
||||
if (delegateFieldNames.Length == 0)
|
||||
{
|
||||
// return 0;
|
||||
return
|
||||
Block(ReturnStatement(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))));
|
||||
}
|
||||
|
||||
List<StatementSyntax> blockStatements = new(4);
|
||||
|
||||
// global::System.HashCode hashCode = default;
|
||||
blockStatements.Add(LocalDeclarationStatement(
|
||||
VariableDeclaration(IdentifierName("global::System.HashCode"))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("hashCode"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
LiteralExpression(
|
||||
SyntaxKind.DefaultLiteralExpression,
|
||||
Token(SyntaxKind.DefaultKeyword)))))));
|
||||
|
||||
foreach (string fieldName in delegateFieldNames)
|
||||
{
|
||||
// hashCode.Add(delegateField.Method);
|
||||
blockStatements.Add(ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("hashCode"),
|
||||
IdentifierName("Add")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(fieldName),
|
||||
IdentifierName("Method"))))));
|
||||
}
|
||||
|
||||
// return hashCode.ToHashCode();
|
||||
blockStatements.Add(ReturnStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("hashCode"),
|
||||
IdentifierName("Add")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(fieldName),
|
||||
IdentifierName("Method"))))));
|
||||
IdentifierName("ToHashCode")))));
|
||||
|
||||
return Block(blockStatements);
|
||||
}
|
||||
|
||||
// return hashCode.ToHashCode();
|
||||
blockStatements.Add(ReturnStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("hashCode"),
|
||||
IdentifierName("ToHashCode")))));
|
||||
|
||||
return Block(blockStatements);
|
||||
}
|
||||
}
|
||||
@@ -9,19 +9,25 @@ namespace ComputeSharp.SourceGenerators;
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the names of all instance fields of a <see cref="System.Delegate"/> type.
|
||||
/// A helper with all logic to generate the <c>GetDispatchId</c> method.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <returns>The names of all <see cref="System.Delegate"/> instance fields within <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static ImmutableArray<string> GetDelegateFieldNames(INamedTypeSymbol structDeclarationSymbol)
|
||||
private static partial class GetDispatchId
|
||||
{
|
||||
return
|
||||
structDeclarationSymbol
|
||||
.GetMembers()
|
||||
.OfType<IFieldSymbol>()
|
||||
.Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
|
||||
.Select(static member => member.Name)
|
||||
.ToImmutableArray();
|
||||
/// <summary>
|
||||
/// Extracts the names of all instance fields of a <see cref="System.Delegate"/> type.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <returns>The names of all <see cref="System.Delegate"/> instance fields within <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
public static ImmutableArray<string> GetInfo(INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
return
|
||||
structDeclarationSymbol
|
||||
.GetMembers()
|
||||
.OfType<IFieldSymbol>()
|
||||
.Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
|
||||
.Select(static member => member.Name)
|
||||
.ToImmutableArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
+189
-185
@@ -13,233 +13,237 @@ namespace ComputeSharp.SourceGenerators;
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
|
||||
/// </summary>
|
||||
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
|
||||
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
|
||||
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
|
||||
private static MethodDeclarationSyntax CreateLoadDispatchDataMethod(
|
||||
Type shaderInterfaceType,
|
||||
ImmutableArray<FieldInfo> fieldInfos,
|
||||
int resourceCount,
|
||||
int root32BitConstantsCount)
|
||||
/// <inheritdoc/>
|
||||
private static partial class LoadDispatchData
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TDataLoader>(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.VoidKeyword)),
|
||||
Identifier("LoadDispatchData"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("loader"))
|
||||
.AddModifiers(Token(SyntaxKind.RefKeyword))
|
||||
.WithType(IdentifierName("TDataLoader")),
|
||||
Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
|
||||
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
|
||||
.WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch data for a given shader.
|
||||
/// </summary>
|
||||
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
|
||||
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
|
||||
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(
|
||||
Type shaderInterfaceType,
|
||||
ImmutableArray<FieldInfo> fieldInfos,
|
||||
int resourceCount,
|
||||
int root32BitConstantsCount)
|
||||
{
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
|
||||
|
||||
// Append the statements for the dispatch ranges:
|
||||
//
|
||||
// span0[0] = (uint)x;
|
||||
// span0[1] = (uint)y;
|
||||
// span0[2] = (uint)z;
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
|
||||
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
|
||||
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
|
||||
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
|
||||
|
||||
// If the shader is a compute shader, also track the bounds on the Z axis
|
||||
if (isComputeShader)
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
|
||||
/// </summary>
|
||||
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
|
||||
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
|
||||
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(
|
||||
Type shaderInterfaceType,
|
||||
ImmutableArray<FieldInfo> fieldInfos,
|
||||
int resourceCount,
|
||||
int root32BitConstantsCount)
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TDataLoader>(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.VoidKeyword)),
|
||||
Identifier("LoadDispatchData"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("loader"))
|
||||
.AddModifiers(Token(SyntaxKind.RefKeyword))
|
||||
.WithType(IdentifierName("TDataLoader")),
|
||||
Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
|
||||
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
|
||||
.WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch data for a given shader.
|
||||
/// </summary>
|
||||
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
|
||||
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
|
||||
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(
|
||||
Type shaderInterfaceType,
|
||||
ImmutableArray<FieldInfo> fieldInfos,
|
||||
int resourceCount,
|
||||
int root32BitConstantsCount)
|
||||
{
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
|
||||
|
||||
// Append the statements for the dispatch ranges:
|
||||
//
|
||||
// span0[0] = (uint)x;
|
||||
// span0[1] = (uint)y;
|
||||
// span0[2] = (uint)z;
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
|
||||
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
|
||||
}
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
|
||||
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in fieldInfos)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
|
||||
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
|
||||
|
||||
// If the shader is a compute shader, also track the bounds on the Z axis
|
||||
if (isComputeShader)
|
||||
{
|
||||
case FieldInfo.Resource resource:
|
||||
|
||||
// Validate the resource and get a handle for it. This will generate:
|
||||
//
|
||||
// global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, <OFFSET>) =
|
||||
// global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(<FIELD_NAME>, device);
|
||||
statements.Add(ExpressionStatement(
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"),
|
||||
ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)"))));
|
||||
break;
|
||||
case FieldInfo.Primitive primitive:
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
|
||||
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
|
||||
}
|
||||
|
||||
// Read a primitive value and serialize it into the target buffer. This will generate:
|
||||
//
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::<TYPE_NAME>>(
|
||||
// ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = <FIELD_PATH>
|
||||
statements.Add(ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
|
||||
ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
|
||||
break;
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in fieldInfos)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
case FieldInfo.Resource resource:
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
|
||||
string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
|
||||
|
||||
// Declare a local to index into individual rows. This will generate:
|
||||
//
|
||||
// ref <ROW_TYPE> <ROW_NAME> = ref global::System.Runtime.CompilerServices.Unsafe.As<global::<TYPE_NAME>, <ROW_TYPE_NAME>>(
|
||||
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in <FIELD_PATH>));
|
||||
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
|
||||
|
||||
// Generate the loading code for each individual row, with proper alignment.
|
||||
// This will result in the following (assuming Float2x3 m):
|
||||
//
|
||||
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
// Validate the resource and get a handle for it. This will generate:
|
||||
//
|
||||
// global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, <OFFSET>) =
|
||||
// global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(<FIELD_NAME>, device);
|
||||
statements.Add(ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
|
||||
}
|
||||
break;
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"),
|
||||
ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)"))));
|
||||
break;
|
||||
case FieldInfo.Primitive primitive:
|
||||
|
||||
// Read a primitive value and serialize it into the target buffer. This will generate:
|
||||
//
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::<TYPE_NAME>>(
|
||||
// ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = <FIELD_PATH>
|
||||
statements.Add(ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
|
||||
ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
|
||||
break;
|
||||
|
||||
case FieldInfo.NonLinearMatrix matrix:
|
||||
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
|
||||
string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
|
||||
|
||||
// Declare a local to index into individual rows. This will generate:
|
||||
//
|
||||
// ref <ROW_TYPE> <ROW_NAME> = ref global::System.Runtime.CompilerServices.Unsafe.As<global::<TYPE_NAME>, <ROW_TYPE_NAME>>(
|
||||
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in <FIELD_PATH>));
|
||||
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
|
||||
|
||||
// Generate the loading code for each individual row, with proper alignment.
|
||||
// This will result in the following (assuming Float2x3 m):
|
||||
//
|
||||
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
|
||||
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
|
||||
for (int j = 0; j < matrix.Rows; j++)
|
||||
{
|
||||
statements.Add(ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// global::System.Span<uint> span0 = stackalloc uint[<VARIABLES>];
|
||||
statements.Insert(0,
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("span0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
StackAllocArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
|
||||
.AddRankSpecifiers(
|
||||
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
|
||||
|
||||
// ref uint r0 = ref span0[0];
|
||||
statements.Insert(1,
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// loader.LoadCapturedValues(span0);
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("loader"),
|
||||
IdentifierName("LoadCapturedValues")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
|
||||
|
||||
if (resourceCount > 0)
|
||||
{
|
||||
// global::System.Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
|
||||
statements.Insert(1,
|
||||
// global::System.Span<uint> span0 = stackalloc uint[<VARIABLES>];
|
||||
statements.Insert(0,
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("span1"))
|
||||
VariableDeclarator(Identifier("span0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
StackAllocArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
|
||||
.AddRankSpecifiers(
|
||||
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount)))))))))));
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
|
||||
|
||||
// ref ulong r1 = ref span1[0];
|
||||
statements.Insert(3,
|
||||
// ref uint r0 = ref span0[0];
|
||||
statements.Insert(1,
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
|
||||
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r1"))
|
||||
VariableDeclarator(Identifier("r0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span1"))
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// loader.LoadCapturedResources(span1);
|
||||
// loader.LoadCapturedValues(span0);
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("loader"),
|
||||
IdentifierName("LoadCapturedResources")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
|
||||
}
|
||||
IdentifierName("LoadCapturedValues")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
|
||||
|
||||
return statements.ToImmutable();
|
||||
if (resourceCount > 0)
|
||||
{
|
||||
// global::System.Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
|
||||
statements.Insert(1,
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("span1"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
StackAllocArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
|
||||
.AddRankSpecifiers(
|
||||
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount)))))))))));
|
||||
|
||||
// ref ulong r1 = ref span1[0];
|
||||
statements.Insert(3,
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r1"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span1"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// loader.LoadCapturedResources(span1);
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("loader"),
|
||||
IdentifierName("LoadCapturedResources")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
|
||||
}
|
||||
|
||||
return statements.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
+146
-140
@@ -17,171 +17,177 @@ namespace ComputeSharp.SourceGenerators;
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// A helper with all logic to generate the <c>LoadDispatchData</c> method.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
|
||||
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
|
||||
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
|
||||
private static ImmutableArray<FieldInfo> GetCapturedFieldInfos(
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
Type shaderInterfaceType,
|
||||
out int resourceCount,
|
||||
out int root32BitConstantCount,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
private static partial class LoadDispatchData
|
||||
{
|
||||
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
|
||||
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
|
||||
ITypeSymbol currentTypeSymbol,
|
||||
ImmutableArray<string> fieldPath,
|
||||
StrongBox<int> resourceOffset,
|
||||
StrongBox<int> rawDataOffset)
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
|
||||
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
|
||||
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
|
||||
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
|
||||
public static ImmutableArray<FieldInfo> GetInfo(
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
Type shaderInterfaceType,
|
||||
out int resourceCount,
|
||||
out int root32BitConstantCount,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
bool isFirstField = true;
|
||||
|
||||
foreach (
|
||||
IFieldSymbol fieldSymbol in
|
||||
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
|
||||
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
|
||||
!fieldSymbol.IsConst && !fieldSymbol.IsStatic &&
|
||||
!fieldSymbol.IsFixedSizeBuffer
|
||||
select fieldSymbol)
|
||||
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
|
||||
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
|
||||
ITypeSymbol currentTypeSymbol,
|
||||
ImmutableArray<string> fieldPath,
|
||||
StrongBox<int> resourceOffset,
|
||||
StrongBox<int> rawDataOffset)
|
||||
{
|
||||
string fieldName = fieldSymbol.Name;
|
||||
string typeName = fieldSymbol.Type.GetFullMetadataName();
|
||||
bool isFirstField = true;
|
||||
|
||||
// Disambiguates the name of target fields against the current input parameters
|
||||
if (fieldName is "loader" or "device" or "x" or "y" or "z")
|
||||
foreach (
|
||||
IFieldSymbol fieldSymbol in
|
||||
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
|
||||
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
|
||||
!fieldSymbol.IsConst && !fieldSymbol.IsStatic &&
|
||||
!fieldSymbol.IsFixedSizeBuffer
|
||||
select fieldSymbol)
|
||||
{
|
||||
fieldName = $"this.{fieldName}";
|
||||
}
|
||||
string fieldName = fieldSymbol.Name;
|
||||
string typeName = fieldSymbol.Type.GetFullMetadataName();
|
||||
|
||||
// The first item in each nested struct needs to be aligned to 16 bytes
|
||||
if (isFirstField && fieldPath.Length > 0)
|
||||
{
|
||||
rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16);
|
||||
|
||||
isFirstField = false;
|
||||
}
|
||||
|
||||
if (HlslKnownTypes.IsTypedResourceType(typeName))
|
||||
{
|
||||
yield return new FieldInfo.Resource(fieldName, typeName, resourceOffset.Value++);
|
||||
}
|
||||
else if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value);
|
||||
}
|
||||
else if (fieldSymbol.Type.IsUnmanagedType)
|
||||
{
|
||||
// Custom struct type defined by the user
|
||||
foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), resourceOffset, rawDataOffset))
|
||||
// Disambiguates the name of target fields against the current input parameters
|
||||
if (fieldName is "loader" or "device" or "x" or "y" or "z")
|
||||
{
|
||||
yield return fieldInfo;
|
||||
fieldName = $"this.{fieldName}";
|
||||
}
|
||||
|
||||
// The first item in each nested struct needs to be aligned to 16 bytes
|
||||
if (isFirstField && fieldPath.Length > 0)
|
||||
{
|
||||
rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16);
|
||||
|
||||
isFirstField = false;
|
||||
}
|
||||
|
||||
if (HlslKnownTypes.IsTypedResourceType(typeName))
|
||||
{
|
||||
yield return new FieldInfo.Resource(fieldName, typeName, resourceOffset.Value++);
|
||||
}
|
||||
else if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value);
|
||||
}
|
||||
else if (fieldSymbol.Type.IsUnmanagedType)
|
||||
{
|
||||
// Custom struct type defined by the user
|
||||
foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), resourceOffset, rawDataOffset))
|
||||
{
|
||||
yield return fieldInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
// Setup the resource and byte offsets for tracking. Pixel shaders have only two
|
||||
// implicitly captured int values, as they're always dispatched over a 2D texture.
|
||||
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
|
||||
int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
|
||||
StrongBox<int> resourceOffsetAsBox = new();
|
||||
StrongBox<int> rawDataOffsetAsBox = new(initialRawDataOffset);
|
||||
// Setup the resource and byte offsets for tracking. Pixel shaders have only two
|
||||
// implicitly captured int values, as they're always dispatched over a 2D texture.
|
||||
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
|
||||
int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
|
||||
StrongBox<int> resourceOffsetAsBox = new();
|
||||
StrongBox<int> rawDataOffsetAsBox = new(initialRawDataOffset);
|
||||
|
||||
// Traverse all shader fields and gather info, and update the tracking offsets
|
||||
ImmutableArray<FieldInfo> fieldInfos = GetCapturedFieldInfos(
|
||||
structDeclarationSymbol,
|
||||
ImmutableArray<string>.Empty,
|
||||
resourceOffsetAsBox,
|
||||
rawDataOffsetAsBox).ToImmutableArray();
|
||||
// Traverse all shader fields and gather info, and update the tracking offsets
|
||||
ImmutableArray<FieldInfo> fieldInfos = GetCapturedFieldInfos(
|
||||
structDeclarationSymbol,
|
||||
ImmutableArray<string>.Empty,
|
||||
resourceOffsetAsBox,
|
||||
rawDataOffsetAsBox).ToImmutableArray();
|
||||
|
||||
resourceCount = resourceOffsetAsBox.Value;
|
||||
resourceCount = resourceOffsetAsBox.Value;
|
||||
|
||||
// After all the captured fields have been processed, ansure the reported byte size for
|
||||
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
|
||||
// enable loading all the dispatch data after reinterpreting it to a sequence of values
|
||||
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
|
||||
root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int);
|
||||
// After all the captured fields have been processed, ansure the reported byte size for
|
||||
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
|
||||
// enable loading all the dispatch data after reinterpreting it to a sequence of values
|
||||
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
|
||||
root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int);
|
||||
|
||||
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
|
||||
// Loaded values in the root signature have the following costs:
|
||||
// - Root constants cost 1 DWORD each, since they are 32-bit values.
|
||||
// - Descriptor tables cost 1 DWORD each.
|
||||
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
|
||||
// So here we check whether the current signature respects that constraint,
|
||||
// and emit a build error otherwise. For more info on this, see the docs here:
|
||||
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
|
||||
int rootSignatureDwordSize = root32BitConstantCount + resourceCount;
|
||||
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
|
||||
// Loaded values in the root signature have the following costs:
|
||||
// - Root constants cost 1 DWORD each, since they are 32-bit values.
|
||||
// - Descriptor tables cost 1 DWORD each.
|
||||
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
|
||||
// So here we check whether the current signature respects that constraint,
|
||||
// and emit a build error otherwise. For more info on this, see the docs here:
|
||||
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
|
||||
int rootSignatureDwordSize = root32BitConstantCount + resourceCount;
|
||||
|
||||
if (rootSignatureDwordSize > 64)
|
||||
{
|
||||
builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return fieldInfos;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
|
||||
/// </summary>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="typeName">The type name currently being read.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
private static FieldInfo GetHlslKnownTypeFieldInfo(
|
||||
ImmutableArray<string> fieldPath,
|
||||
string typeName,
|
||||
ref int rawDataOffset)
|
||||
{
|
||||
// For scalar, vector and linear matrix types, serialize the value normally.
|
||||
// Only the initial alignment needs to be considered, while data is packed.
|
||||
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
|
||||
|
||||
// Check if the current type is a matrix type with more than one row. In this
|
||||
// case, each row is aligned as if it was a separate array, so the start of
|
||||
// each row needs to be at a multiple of 16 bytes (a float4 register).
|
||||
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
|
||||
{
|
||||
ImmutableArray<int>.Builder builder = ImmutableArray.CreateBuilder<int>(rows);
|
||||
|
||||
for (int j = 0; j < rows; j++)
|
||||
if (rootSignatureDwordSize > 64)
|
||||
{
|
||||
int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
builder.Add(startingRawDataOffset);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + fieldPack * columns;
|
||||
builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
return new FieldInfo.NonLinearMatrix(
|
||||
fieldPath,
|
||||
typeName,
|
||||
elementName!,
|
||||
rows,
|
||||
columns,
|
||||
builder.MoveToImmutable());
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return fieldInfos;
|
||||
}
|
||||
else
|
||||
|
||||
/// <summary>
|
||||
/// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
|
||||
/// </summary>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="typeName">The type name currently being read.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
private static FieldInfo GetHlslKnownTypeFieldInfo(
|
||||
ImmutableArray<string> fieldPath,
|
||||
string typeName,
|
||||
ref int rawDataOffset)
|
||||
{
|
||||
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
|
||||
// Since we're in a constant buffer, we need to both pad the starting offset
|
||||
// to be aligned to the packing size of the type, and also to align the initial
|
||||
// offset to ensure that values do not cross 16 bytes boundaries either.
|
||||
int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
|
||||
AlignmentHelper.Pad(rawDataOffset, fieldPack),
|
||||
fieldSize,
|
||||
16);
|
||||
// For scalar, vector and linear matrix types, serialize the value normally.
|
||||
// Only the initial alignment needs to be considered, while data is packed.
|
||||
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + fieldSize;
|
||||
// Check if the current type is a matrix type with more than one row. In this
|
||||
// case, each row is aligned as if it was a separate array, so the start of
|
||||
// each row needs to be at a multiple of 16 bytes (a float4 register).
|
||||
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
|
||||
{
|
||||
ImmutableArray<int>.Builder builder = ImmutableArray.CreateBuilder<int>(rows);
|
||||
|
||||
return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
|
||||
for (int j = 0; j < rows; j++)
|
||||
{
|
||||
int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
builder.Add(startingRawDataOffset);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + fieldPack * columns;
|
||||
}
|
||||
|
||||
return new FieldInfo.NonLinearMatrix(
|
||||
fieldPath,
|
||||
typeName,
|
||||
elementName!,
|
||||
rows,
|
||||
columns,
|
||||
builder.MoveToImmutable());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
|
||||
// Since we're in a constant buffer, we need to both pad the starting offset
|
||||
// to be aligned to the packing size of the type, and also to align the initial
|
||||
// offset to ensure that values do not cross 16 bytes boundaries either.
|
||||
int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
|
||||
AlignmentHelper.Pad(rawDataOffset, fieldPack),
|
||||
fieldSize,
|
||||
16);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + fieldSize;
|
||||
|
||||
return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
-110
@@ -13,120 +13,124 @@ namespace ComputeSharp.SourceGenerators;
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
|
||||
/// </summary>
|
||||
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
|
||||
private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo)
|
||||
/// <inheritdoc/>
|
||||
private static partial class LoadDispatchMetadata
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out global::System.IntPtr result)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.VoidKeyword)),
|
||||
Identifier("LoadDispatchMetadata"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("loader"))
|
||||
.AddModifiers(Token(SyntaxKind.RefKeyword))
|
||||
.WithType(IdentifierName("TMetadataLoader")),
|
||||
Parameter(Identifier("result"))
|
||||
.AddModifiers(Token(SyntaxKind.OutKeyword))
|
||||
.WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}")))
|
||||
.WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
|
||||
{
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
|
||||
// global::System.Span<byte> span0 = stackalloc byte[5];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("span0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
StackAllocArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
|
||||
.AddRankSpecifiers(
|
||||
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))));
|
||||
|
||||
// Compute the total number of resources
|
||||
int totalResourcesCount = metadataInfo.ResourceDescriptors.Length;
|
||||
|
||||
// Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[<ADJUSTED_COUNT>];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("span1"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
StackAllocArrayCreationExpression(
|
||||
ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
|
||||
.AddRankSpecifiers(
|
||||
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))));
|
||||
|
||||
// ref byte r0 = ref span0[0];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r1"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span1"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// Serialized shader metadata
|
||||
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});"));
|
||||
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});"));
|
||||
|
||||
|
||||
// Populate the sequence of resource descriptors
|
||||
foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors)
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
|
||||
/// </summary>
|
||||
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(DispatchMetadataInfo metadataInfo)
|
||||
{
|
||||
statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"));
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out global::System.IntPtr result)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.VoidKeyword)),
|
||||
Identifier("LoadDispatchMetadata"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("loader"))
|
||||
.AddModifiers(Token(SyntaxKind.RefKeyword))
|
||||
.WithType(IdentifierName("TMetadataLoader")),
|
||||
Parameter(Identifier("result"))
|
||||
.AddModifiers(Token(SyntaxKind.OutKeyword))
|
||||
.WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}")))
|
||||
.WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo)));
|
||||
}
|
||||
|
||||
// Invoke the value delegate to create the opaque root signature handle
|
||||
statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"));
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
|
||||
{
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
|
||||
return statements.ToImmutable();
|
||||
// global::System.Span<byte> span0 = stackalloc byte[5];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("span0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
StackAllocArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
|
||||
.AddRankSpecifiers(
|
||||
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))));
|
||||
|
||||
// Compute the total number of resources
|
||||
int totalResourcesCount = metadataInfo.ResourceDescriptors.Length;
|
||||
|
||||
// Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[<ADJUSTED_COUNT>];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(
|
||||
GenericName(Identifier("global::System.Span"))
|
||||
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("span1"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
StackAllocArrayCreationExpression(
|
||||
ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
|
||||
.AddRankSpecifiers(
|
||||
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))));
|
||||
|
||||
// ref byte r0 = ref span0[0];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
|
||||
statements.Add(
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r1"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span1"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// Serialized shader metadata
|
||||
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});"));
|
||||
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});"));
|
||||
|
||||
|
||||
// Populate the sequence of resource descriptors
|
||||
foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors)
|
||||
{
|
||||
statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"));
|
||||
}
|
||||
|
||||
// Invoke the value delegate to create the opaque root signature handle
|
||||
statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"));
|
||||
|
||||
return statements.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
-38
@@ -8,51 +8,57 @@ namespace ComputeSharp.SourceGenerators;
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the data related to the shader metadata for a given shader type.
|
||||
/// A helper with all logic to generate the <c>LoadDispatchMetadata</c> method.
|
||||
/// </summary>
|
||||
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <param name="isImplicitTextureUsed">Indicates whether the current shader uses an implicit texture.</param>
|
||||
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
|
||||
/// <param name="capturedFields">The sequence of captured fields for the shader.</param>
|
||||
/// <returns>The metadata info for the shader.</returns>
|
||||
private static DispatchMetadataInfo GetDispatchMetadataInfo(
|
||||
int root32BitConstantCount,
|
||||
bool isImplicitTextureUsed,
|
||||
bool isSamplerUsed,
|
||||
ImmutableArray<FieldInfo> capturedFields)
|
||||
private static partial class LoadDispatchMetadata
|
||||
{
|
||||
ImmutableArray<ResourceDescriptor>.Builder descriptors = ImmutableArray.CreateBuilder<ResourceDescriptor>();
|
||||
int constantBufferOffset = 1;
|
||||
int readOnlyResourceOffset = 0;
|
||||
int readWriteResourceOffset = 0;
|
||||
int resourceOffset = 0;
|
||||
|
||||
// Add the implicit texture descriptor, if needed
|
||||
if (isImplicitTextureUsed)
|
||||
/// <summary>
|
||||
/// Gets the data related to the shader metadata for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
|
||||
/// <param name="isImplicitTextureUsed">Indicates whether the current shader uses an implicit texture.</param>
|
||||
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
|
||||
/// <param name="capturedFields">The sequence of captured fields for the shader.</param>
|
||||
/// <returns>The metadata info for the shader.</returns>
|
||||
public static DispatchMetadataInfo GetInfo(
|
||||
int root32BitConstantCount,
|
||||
bool isImplicitTextureUsed,
|
||||
bool isSamplerUsed,
|
||||
ImmutableArray<FieldInfo> capturedFields)
|
||||
{
|
||||
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
|
||||
}
|
||||
ImmutableArray<ResourceDescriptor>.Builder descriptors = ImmutableArray.CreateBuilder<ResourceDescriptor>();
|
||||
int constantBufferOffset = 1;
|
||||
int readOnlyResourceOffset = 0;
|
||||
int readWriteResourceOffset = 0;
|
||||
int resourceOffset = 0;
|
||||
|
||||
// Populate the sequence of resource descriptors
|
||||
foreach (FieldInfo.Resource resource in capturedFields.OfType<FieldInfo.Resource>())
|
||||
{
|
||||
if (HlslKnownTypes.IsConstantBufferType(resource.TypeName))
|
||||
{
|
||||
descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++));
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName))
|
||||
{
|
||||
descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++));
|
||||
}
|
||||
else
|
||||
// Add the implicit texture descriptor, if needed
|
||||
if (isImplicitTextureUsed)
|
||||
{
|
||||
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
|
||||
}
|
||||
}
|
||||
|
||||
return new(
|
||||
root32BitConstantCount,
|
||||
isSamplerUsed,
|
||||
descriptors.ToImmutable());
|
||||
// Populate the sequence of resource descriptors
|
||||
foreach (FieldInfo.Resource resource in capturedFields.OfType<FieldInfo.Resource>())
|
||||
{
|
||||
if (HlslKnownTypes.IsConstantBufferType(resource.TypeName))
|
||||
{
|
||||
descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++));
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName))
|
||||
{
|
||||
descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++));
|
||||
}
|
||||
else
|
||||
{
|
||||
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
|
||||
}
|
||||
}
|
||||
|
||||
return new(
|
||||
root32BitConstantCount,
|
||||
isSamplerUsed,
|
||||
descriptors.ToImmutable());
|
||||
}
|
||||
}
|
||||
}
|
||||
+154
-150
@@ -14,174 +14,178 @@ namespace ComputeSharp.SourceGenerators;
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
|
||||
/// </summary>
|
||||
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
|
||||
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
private static MethodDeclarationSyntax CreateTryGetBytecodeMethod(EmbeddedBytecodeInfo bytecodeInfo, out Func<SyntaxNode, string> fixup)
|
||||
/// <inheritdoc/>
|
||||
private static partial class TryGetBytecode
|
||||
{
|
||||
BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
|
||||
|
||||
if (bytecodeLiterals is not null)
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
|
||||
/// </summary>
|
||||
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
|
||||
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func<SyntaxNode, string> fixup)
|
||||
{
|
||||
fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
|
||||
}
|
||||
else
|
||||
{
|
||||
fixup = static tree => tree.ToFullString();
|
||||
}
|
||||
BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan<byte> bytecode)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.BoolKeyword)),
|
||||
Identifier("TryGetBytecode"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan<byte>")))
|
||||
.WithBody(block);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
|
||||
/// </summary>
|
||||
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
|
||||
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
|
||||
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
|
||||
[Pure]
|
||||
private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
|
||||
{
|
||||
if (bytecodeInfo.Bytecode.IsEmpty)
|
||||
{
|
||||
bytecodeLiterals = null;
|
||||
if (bytecodeLiterals is not null)
|
||||
{
|
||||
fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
|
||||
}
|
||||
else
|
||||
{
|
||||
fixup = static tree => tree.ToFullString();
|
||||
}
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// bytecode = default;
|
||||
//
|
||||
// return false;
|
||||
// readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan<byte> bytecode)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
Block(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("bytecode"),
|
||||
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
|
||||
ReturnStatement(
|
||||
LiteralExpression(
|
||||
SyntaxKind.FalseLiteralExpression)));
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.BoolKeyword)),
|
||||
Identifier("TryGetBytecode"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddParameterListParameters(
|
||||
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
|
||||
Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan<byte>")))
|
||||
.WithBody(block);
|
||||
}
|
||||
|
||||
bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan());
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
|
||||
/// </summary>
|
||||
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
|
||||
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
|
||||
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
|
||||
[Pure]
|
||||
private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
|
||||
{
|
||||
if (bytecodeInfo.Bytecode.IsEmpty)
|
||||
{
|
||||
bytecodeLiterals = null;
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// if (threadsX == <X> && threadsY == <Y> && threadsZ == <Z>)
|
||||
// {
|
||||
// bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
|
||||
//
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// bytecode = default;
|
||||
//
|
||||
// return false;
|
||||
//
|
||||
// Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
|
||||
// is created by the generator. This greatly speeds up the code generation, as it avoids
|
||||
// having to create/parse tens of thousands of literal expression nodes for every shader.
|
||||
return
|
||||
Block(
|
||||
IfStatement(
|
||||
BinaryExpression(
|
||||
SyntaxKind.LogicalAndExpression,
|
||||
BinaryExpression(
|
||||
SyntaxKind.LogicalAndExpression,
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsX"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))),
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsY"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))),
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsZ"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))),
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// bytecode = default;
|
||||
//
|
||||
// return false;
|
||||
return
|
||||
Block(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("bytecode"),
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(
|
||||
InitializerExpression(
|
||||
SyntaxKind.ArrayInitializerExpression,
|
||||
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))),
|
||||
ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("bytecode"),
|
||||
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
|
||||
ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
|
||||
}
|
||||
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
|
||||
ReturnStatement(
|
||||
LiteralExpression(
|
||||
SyntaxKind.FalseLiteralExpression)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A mapping of precomputed literals for all <see cref="byte"/> values.
|
||||
/// </summary>
|
||||
private static readonly string[] formattedBytes =
|
||||
{
|
||||
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
|
||||
"0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
|
||||
"0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
|
||||
"0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
|
||||
"0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
|
||||
"0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
|
||||
"0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
|
||||
"0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
|
||||
"0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
|
||||
"0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
|
||||
"0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
|
||||
"0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
|
||||
"0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
|
||||
"0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
|
||||
"0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
|
||||
"0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
|
||||
};
|
||||
bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan());
|
||||
|
||||
/// <summary>
|
||||
/// Creates a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given shader data.
|
||||
/// </summary>
|
||||
/// <param name="bytecode">The input shader bytecode to serialize.</param>
|
||||
/// <returns>A formatted <see cref="string"/> with the serialized data.</returns>
|
||||
private static string BuildShaderBytecodeExpressionString(ReadOnlySpan<byte> bytecode)
|
||||
{
|
||||
//The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
|
||||
using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
|
||||
|
||||
builder.Append(formattedBytes[bytecode[0]]);
|
||||
|
||||
foreach (byte b in bytecode.Slice(1))
|
||||
{
|
||||
builder.Append(", ");
|
||||
builder.Append(formattedBytes[b]);
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// if (threadsX == <X> && threadsY == <Y> && threadsZ == <Z>)
|
||||
// {
|
||||
// bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
|
||||
//
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// bytecode = default;
|
||||
//
|
||||
// return false;
|
||||
//
|
||||
// Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
|
||||
// is created by the generator. This greatly speeds up the code generation, as it avoids
|
||||
// having to create/parse tens of thousands of literal expression nodes for every shader.
|
||||
return
|
||||
Block(
|
||||
IfStatement(
|
||||
BinaryExpression(
|
||||
SyntaxKind.LogicalAndExpression,
|
||||
BinaryExpression(
|
||||
SyntaxKind.LogicalAndExpression,
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsX"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))),
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsY"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))),
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsZ"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))),
|
||||
Block(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("bytecode"),
|
||||
ArrayCreationExpression(
|
||||
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
|
||||
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(
|
||||
InitializerExpression(
|
||||
SyntaxKind.ArrayInitializerExpression,
|
||||
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))),
|
||||
ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("bytecode"),
|
||||
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
|
||||
ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
|
||||
}
|
||||
|
||||
return builder.WrittenSpan.ToString();
|
||||
/// <summary>
|
||||
/// A mapping of precomputed literals for all <see cref="byte"/> values.
|
||||
/// </summary>
|
||||
private static readonly string[] formattedBytes =
|
||||
{
|
||||
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
|
||||
"0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
|
||||
"0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
|
||||
"0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
|
||||
"0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
|
||||
"0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
|
||||
"0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
|
||||
"0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
|
||||
"0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
|
||||
"0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
|
||||
"0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
|
||||
"0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
|
||||
"0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
|
||||
"0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
|
||||
"0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
|
||||
"0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Creates a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given shader data.
|
||||
/// </summary>
|
||||
/// <param name="bytecode">The input shader bytecode to serialize.</param>
|
||||
/// <returns>A formatted <see cref="string"/> with the serialized data.</returns>
|
||||
private static string BuildShaderBytecodeExpressionString(ReadOnlySpan<byte> bytecode)
|
||||
{
|
||||
//The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
|
||||
using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
|
||||
|
||||
builder.Append(formattedBytes[bytecode[0]]);
|
||||
|
||||
foreach (byte b in bytecode.Slice(1))
|
||||
{
|
||||
builder.Append(", ");
|
||||
builder.Append(formattedBytes[b]);
|
||||
}
|
||||
|
||||
return builder.WrittenSpan.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,196 +23,202 @@ namespace ComputeSharp.SourceGenerators;
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the thread ids values for a given shader type, if available.
|
||||
/// A helper with all logic to generate the <c>TryGetBytecode</c> method.
|
||||
/// </summary>
|
||||
/// <param name="embeddedBytecodeAttribute">The <see cref="INamedTypeSymbol"/> instance for the attribute.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The thread ids for the precompiled shader, if available.</returns>
|
||||
private static ThreadIdsInfo GetThreadIdsForEmbeddedShader(
|
||||
INamedTypeSymbol embeddedBytecodeAttribute,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
bool isDynamicShader,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
private static partial class TryGetBytecode
|
||||
{
|
||||
AttributeData? attribute = structDeclarationSymbol
|
||||
.GetAttributes()
|
||||
.FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, embeddedBytecodeAttribute));
|
||||
|
||||
if (attribute is null)
|
||||
/// <summary>
|
||||
/// Gets the thread ids values for a given shader type, if available.
|
||||
/// </summary>
|
||||
/// <param name="embeddedBytecodeAttribute">The <see cref="INamedTypeSymbol"/> instance for the attribute.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The thread ids for the precompiled shader, if available.</returns>
|
||||
public static ThreadIdsInfo GetInfo(
|
||||
INamedTypeSymbol embeddedBytecodeAttribute,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
bool isDynamicShader,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
diagnostics = ImmutableArray<Diagnostic>.Empty;
|
||||
AttributeData? attribute = structDeclarationSymbol
|
||||
.GetAttributes()
|
||||
.FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, embeddedBytecodeAttribute));
|
||||
|
||||
return new(true, 0, 0, 0);
|
||||
}
|
||||
if (attribute is null)
|
||||
{
|
||||
diagnostics = ImmutableArray<Diagnostic>.Empty;
|
||||
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
return new(true, 0, 0, 0);
|
||||
}
|
||||
|
||||
// Validate the thread number arguments
|
||||
if (attribute.ConstructorArguments[0].Value is not int threadsX ||
|
||||
attribute.ConstructorArguments[1].Value is not int threadsY ||
|
||||
attribute.ConstructorArguments[2].Value is not int threadsZ ||
|
||||
threadsX is < 1 or > 1024 ||
|
||||
threadsY is < 1 or > 1024 ||
|
||||
threadsZ is < 1 or > 64)
|
||||
{
|
||||
builder.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol);
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
// Validate the thread number arguments
|
||||
if (attribute.ConstructorArguments[0].Value is not int threadsX ||
|
||||
attribute.ConstructorArguments[1].Value is not int threadsY ||
|
||||
attribute.ConstructorArguments[2].Value is not int threadsZ ||
|
||||
threadsX is < 1 or > 1024 ||
|
||||
threadsY is < 1 or > 1024 ||
|
||||
threadsZ is < 1 or > 64)
|
||||
{
|
||||
builder.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol);
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return new(true, 0, 0, 0);
|
||||
}
|
||||
|
||||
// If the current shader is dynamic, emit a diagnostic error
|
||||
if (isDynamicShader)
|
||||
{
|
||||
builder.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return new(true, 0, 0, 0);
|
||||
}
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return new(true, 0, 0, 0);
|
||||
return new(false, threadsX, threadsY, threadsZ);
|
||||
}
|
||||
|
||||
// If the current shader is dynamic, emit a diagnostic error
|
||||
if (isDynamicShader)
|
||||
/// <summary>
|
||||
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
|
||||
/// </summary>
|
||||
private static bool areDxcLibrariesLoaded;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
|
||||
/// </summary>
|
||||
/// <param name="threadIds">The input <see cref="ThreadIdsInfo"/> instance to process.</param>
|
||||
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The <see cref="ImmutableArray{T}"/> instance with the compiled shader bytecode.</returns>
|
||||
[Pure]
|
||||
public static unsafe ImmutableArray<byte> GetBytecode(
|
||||
ThreadIdsInfo threadIds,
|
||||
string hlslSource,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
builder.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
|
||||
ImmutableArray<byte> bytecode = ImmutableArray<byte>.Empty;
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return new(true, 0, 0, 0);
|
||||
}
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return new(false, threadsX, threadsY, threadsZ);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
|
||||
/// </summary>
|
||||
private static bool areDxcLibrariesLoaded;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
|
||||
/// </summary>
|
||||
/// <param name="threadIds">The input <see cref="ThreadIdsInfo"/> instance to process.</param>
|
||||
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
|
||||
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The <see cref="ImmutableArray{T}"/> instance with the compiled shader bytecode.</returns>
|
||||
[Pure]
|
||||
private static unsafe ImmutableArray<byte> GetShaderBytecode(
|
||||
ThreadIdsInfo threadIds,
|
||||
string hlslSource,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
ImmutableArray<byte> bytecode = ImmutableArray<byte>.Empty;
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
// No embedded shader was requested
|
||||
if (threadIds.IsDefault)
|
||||
{
|
||||
goto End;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Try to load dxcompiler.dll and dxil.dll
|
||||
LoadNativeDxcLibraries();
|
||||
|
||||
// Replace the actual thread num values
|
||||
hlslSource = hlslSource
|
||||
.Replace("<THREADSX>", threadIds.X.ToString())
|
||||
.Replace("<THREADSY>", threadIds.Y.ToString())
|
||||
.Replace("<THREADSZ>", threadIds.Z.ToString());
|
||||
|
||||
// Compile the shader bytecode
|
||||
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan());
|
||||
|
||||
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
|
||||
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
|
||||
|
||||
byte[] array = new ReadOnlySpan<byte>(buffer, length).ToArray();
|
||||
|
||||
bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
|
||||
}
|
||||
catch (Win32Exception)
|
||||
{
|
||||
// TODO
|
||||
//builder.Add(
|
||||
// EmbeddedBytecodeFailedWithWin32Exception,
|
||||
// structDeclarationSymbol,
|
||||
// structDeclarationSymbol,
|
||||
// e.HResult,
|
||||
// e.Message);
|
||||
}
|
||||
catch (HlslCompilationException)
|
||||
{
|
||||
// TODO
|
||||
//builder.Add(
|
||||
// EmbeddedBytecodeFailedWithHlslCompilationException,
|
||||
// structDeclarationSymbol,
|
||||
// structDeclarationSymbol,
|
||||
// e.Message);
|
||||
}
|
||||
|
||||
End:
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return bytecode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts and loads the <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries.
|
||||
/// </summary>
|
||||
/// <exception cref="NotSupportedException">Thrown if the CPU architecture is not supported.</exception>
|
||||
/// <exception cref="Win32Exception">Thrown if a library fails to load.</exception>
|
||||
private static void LoadNativeDxcLibraries()
|
||||
{
|
||||
// Extracts a specified native library for a given runtime identifier
|
||||
static string ExtractLibrary(string rid, string name)
|
||||
{
|
||||
string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll";
|
||||
string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll");
|
||||
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(targetFilename));
|
||||
|
||||
using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename);
|
||||
// No embedded shader was requested
|
||||
if (threadIds.IsDefault)
|
||||
{
|
||||
goto End;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write);
|
||||
// Try to load dxcompiler.dll and dxil.dll
|
||||
LoadNativeDxcLibraries();
|
||||
|
||||
sourceStream.CopyTo(destinationStream);
|
||||
// Replace the actual thread num values
|
||||
hlslSource = hlslSource
|
||||
.Replace("<THREADSX>", threadIds.X.ToString())
|
||||
.Replace("<THREADSY>", threadIds.Y.ToString())
|
||||
.Replace("<THREADSZ>", threadIds.Z.ToString());
|
||||
|
||||
// Compile the shader bytecode
|
||||
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan());
|
||||
|
||||
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
|
||||
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
|
||||
|
||||
byte[] array = new ReadOnlySpan<byte>(buffer, length).ToArray();
|
||||
|
||||
bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
|
||||
}
|
||||
catch (IOException)
|
||||
catch (Win32Exception)
|
||||
{
|
||||
// TODO
|
||||
//builder.Add(
|
||||
// EmbeddedBytecodeFailedWithWin32Exception,
|
||||
// structDeclarationSymbol,
|
||||
// structDeclarationSymbol,
|
||||
// e.HResult,
|
||||
// e.Message);
|
||||
}
|
||||
catch (HlslCompilationException)
|
||||
{
|
||||
// TODO
|
||||
//builder.Add(
|
||||
// EmbeddedBytecodeFailedWithHlslCompilationException,
|
||||
// structDeclarationSymbol,
|
||||
// structDeclarationSymbol,
|
||||
// e.Message);
|
||||
}
|
||||
|
||||
return targetFilename;
|
||||
End:
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return bytecode;
|
||||
}
|
||||
|
||||
// Loads a target native library
|
||||
static unsafe void LoadLibrary(string filename)
|
||||
/// <summary>
|
||||
/// Extracts and loads the <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries.
|
||||
/// </summary>
|
||||
/// <exception cref="NotSupportedException">Thrown if the CPU architecture is not supported.</exception>
|
||||
/// <exception cref="Win32Exception">Thrown if a library fails to load.</exception>
|
||||
private static void LoadNativeDxcLibraries()
|
||||
{
|
||||
[DllImport("kernel32", ExactSpelling = true, SetLastError = true)]
|
||||
static extern void* LoadLibraryW(ushort* lpLibFileName);
|
||||
|
||||
fixed (char* p = filename)
|
||||
// Extracts a specified native library for a given runtime identifier
|
||||
static string ExtractLibrary(string rid, string name)
|
||||
{
|
||||
if (LoadLibraryW((ushort*)p) is null)
|
||||
{
|
||||
int hresult = Marshal.GetLastWin32Error();
|
||||
string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll";
|
||||
string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll");
|
||||
|
||||
throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}.");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(targetFilename));
|
||||
|
||||
using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename);
|
||||
|
||||
try
|
||||
{
|
||||
using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write);
|
||||
|
||||
sourceStream.CopyTo(destinationStream);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
|
||||
return targetFilename;
|
||||
}
|
||||
|
||||
// Loads a target native library
|
||||
static unsafe void LoadLibrary(string filename)
|
||||
{
|
||||
[DllImport("kernel32", ExactSpelling = true, SetLastError = true)]
|
||||
static extern void* LoadLibraryW(ushort* lpLibFileName);
|
||||
|
||||
fixed (char* p = filename)
|
||||
{
|
||||
if (LoadLibraryW((ushort*)p) is null)
|
||||
{
|
||||
int hresult = Marshal.GetLastWin32Error();
|
||||
|
||||
throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!areDxcLibrariesLoaded)
|
||||
{
|
||||
string rid = RuntimeInformation.ProcessArchitecture switch
|
||||
if (!areDxcLibrariesLoaded)
|
||||
{
|
||||
Architecture.X64 => "x64",
|
||||
Architecture.Arm64 => "arm64",
|
||||
_ => throw new NotSupportedException("Invalid process architecture")
|
||||
};
|
||||
string rid = RuntimeInformation.ProcessArchitecture switch
|
||||
{
|
||||
Architecture.X64 => "x64",
|
||||
Architecture.Arm64 => "arm64",
|
||||
_ => throw new NotSupportedException("Invalid process architecture")
|
||||
};
|
||||
|
||||
LoadLibrary(ExtractLibrary(rid, "dxil"));
|
||||
LoadLibrary(ExtractLibrary(rid, "dxcompiler"));
|
||||
LoadLibrary(ExtractLibrary(rid, "dxil"));
|
||||
LoadLibrary(ExtractLibrary(rid, "dxcompiler"));
|
||||
}
|
||||
|
||||
areDxcLibrariesLoaded = true;
|
||||
}
|
||||
|
||||
areDxcLibrariesLoaded = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using ComputeSharp.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the shader type for a given shader, if any.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
|
||||
/// <param name="iComputeShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IComputeShader"/>.</param>
|
||||
/// <param name="iPixelShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IPixelShader{TPixel}"/>.</param>
|
||||
/// <returns>Either <see cref="IComputeShader"/> or <see cref="IPixelShader{TPixel}"/>, or <see langword="null"/>.</returns>
|
||||
[Pure]
|
||||
private static Type? GetShaderType(
|
||||
INamedTypeSymbol typeSymbol,
|
||||
INamedTypeSymbol iComputeShaderSymbol,
|
||||
INamedTypeSymbol iPixelShaderSymbol)
|
||||
{
|
||||
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces)
|
||||
{
|
||||
if (interfaceSymbol.Name == nameof(IComputeShader) &&
|
||||
SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol))
|
||||
{
|
||||
return typeof(IComputeShader);
|
||||
}
|
||||
|
||||
if (interfaceSymbol.IsGenericType &&
|
||||
interfaceSymbol.Name == nameof(IPixelShader<byte>) &&
|
||||
SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol))
|
||||
{
|
||||
return typeof(IPixelShader<>);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
|
||||
/// </summary>
|
||||
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> item to insert.</param>
|
||||
/// <param name="canUseSkipLocalsInit">Whether <c>[SkipLocalsInit]</c> can be used.</param>
|
||||
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="methodDeclaration"/>.</returns>
|
||||
[Pure]
|
||||
private static CompilationUnitSyntax GetCompilationUnitFromMethod(
|
||||
HierarchyInfo hierarchyInfo,
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
bool canUseSkipLocalsInit)
|
||||
{
|
||||
// Method attributes
|
||||
List<AttributeListSyntax> attributes = new()
|
||||
{
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
|
||||
AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(
|
||||
SyntaxKind.StringLiteralExpression,
|
||||
Literal("This method is not intended to be used directly by user code"))))))
|
||||
};
|
||||
|
||||
// Add [SkipLocalsInit] if the target project allows it
|
||||
if (canUseSkipLocalsInit)
|
||||
{
|
||||
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
|
||||
}
|
||||
|
||||
// Create the partial shader type declaration with the given method implementation.
|
||||
// This code produces a struct declaration as follows:
|
||||
//
|
||||
// partial struct <SHADER_TYPE>
|
||||
// {
|
||||
// <METHOD>
|
||||
// }
|
||||
StructDeclarationSyntax structDeclarationSyntax =
|
||||
StructDeclaration(hierarchyInfo.Names[0])
|
||||
.AddModifiers(Token(SyntaxKind.PartialKeyword))
|
||||
.AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray()));
|
||||
|
||||
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
|
||||
|
||||
// Add all parent types in ascending order, if any
|
||||
foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
|
||||
{
|
||||
typeDeclarationSyntax =
|
||||
ClassDeclaration(parentType)
|
||||
.AddModifiers(Token(SyntaxKind.PartialKeyword))
|
||||
.AddMembers(typeDeclarationSyntax);
|
||||
}
|
||||
|
||||
// Create a static method to create the combined hashcode for a given shader type.
|
||||
// This code takes a block syntax and produces a compilation unit as follows:
|
||||
//
|
||||
// #pragma warning disable
|
||||
//
|
||||
// namespace <NAMESPACE>;
|
||||
//
|
||||
// <TYPE_HIERARCHY>
|
||||
return
|
||||
CompilationUnit().AddMembers(
|
||||
FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
|
||||
.AddMembers(typeDeclarationSyntax)
|
||||
.WithNamespaceKeyword(Token(TriviaList(
|
||||
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
|
||||
SyntaxKind.NamespaceKeyword,
|
||||
TriviaList())))
|
||||
.NormalizeWhitespace(eol: "\n");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
@@ -11,7 +10,6 @@ using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
@@ -61,13 +59,13 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
// Get the hierarchy info and delegate field names for each shader type
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo Info)> hierarchyAndDispatchIdInfo =
|
||||
shaderDeclarations
|
||||
.Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDelegateFieldNames(item.Symbol))))
|
||||
.Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDispatchId.GetInfo(item.Symbol))))
|
||||
.WithComparers(HierarchyInfo.Comparer.Default, DispatchIdInfo.Comparer.Default);
|
||||
|
||||
// Generate the GetDispatchId() methods
|
||||
context.RegisterSourceOutput(hierarchyAndDispatchIdInfo, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(item.Info.Delegates);
|
||||
MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.Info.Delegates);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, false);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
|
||||
@@ -86,8 +84,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
.Combine(embeddedBytecodeSymbol)
|
||||
.Select(static (item, token) =>
|
||||
{
|
||||
// GetDispatchId() data
|
||||
ImmutableArray<FieldInfo> fieldInfos = GetCapturedFieldInfos(
|
||||
// LoadDispatchData() info
|
||||
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
|
||||
item.Left.Left.Symbol,
|
||||
item.Left.Left.Type,
|
||||
out int resourceCount,
|
||||
@@ -103,14 +101,14 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
dispatchDataDiagnostics);
|
||||
|
||||
// BuildHlslString() info
|
||||
HlslSourceInfo hlslSourceInfo = GetNonDynamicHlslSourceInfo(
|
||||
HlslSourceInfo hlslSourceInfo = BuildHlslString.GetInfo(
|
||||
item.Left.Right,
|
||||
item.Left.Left.Syntax,
|
||||
item.Left.Left.Symbol,
|
||||
out ImmutableArray<Diagnostic> hlslSourceDiagnostics);
|
||||
|
||||
// TryGetBytecode() info
|
||||
ThreadIdsInfo threadIds = GetThreadIdsForEmbeddedShader(
|
||||
ThreadIdsInfo threadIds = TryGetBytecode.GetInfo(
|
||||
item.Right,
|
||||
item.Left.Left.Symbol,
|
||||
!hlslSourceInfo.Delegates.IsEmpty,
|
||||
@@ -142,7 +140,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
// Generate the LoadDispatchData() methods
|
||||
context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(
|
||||
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(
|
||||
item.Left.Type,
|
||||
item.Left.FieldInfos,
|
||||
item.Left.ResourceCount,
|
||||
@@ -161,7 +159,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
// Generate the BuildHlslString() methods
|
||||
context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(item.Left.SourceInfo);
|
||||
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslString.GetSyntax(item.Left.SourceInfo);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right);
|
||||
|
||||
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
|
||||
@@ -172,7 +170,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
shaderInfo
|
||||
.Select(static (item, token) => (
|
||||
item.Dispatch.Hierarchy,
|
||||
GetDispatchMetadataInfo(
|
||||
LoadDispatchMetadata.GetInfo(
|
||||
item.Dispatch.Root32BitConstantCount,
|
||||
item.Hlsl.ImplicitTextureType is not null,
|
||||
item.Hlsl.IsSamplerUsed,
|
||||
@@ -182,7 +180,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
// Generate the LoadDispatchMetadata() methods
|
||||
context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax buildHlslStringMethod = CreateLoadDispatchMetadataMethod(item.Left.MetadataInfo);
|
||||
MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.Left.MetadataInfo);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right);
|
||||
|
||||
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchMetadata", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
|
||||
@@ -191,7 +189,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
// Transform the raw HLSL source to compile
|
||||
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo =
|
||||
shaderInfo
|
||||
.Select(static (item, token) => (item.Dispatch.Hierarchy, GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds))
|
||||
.Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslString.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds))
|
||||
.WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer<string>.Default, ThreadIdsInfo.Comparer.Default);
|
||||
|
||||
// Compile the requested shader bytecodes
|
||||
@@ -199,7 +197,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
shaderBytecodeInfo
|
||||
.Select(static (item, token) =>
|
||||
{
|
||||
ImmutableArray<byte> bytecode = GetShaderBytecode(item.ThreadIds, item.Hlsl, out ImmutableArray<Diagnostic> diagnostics);
|
||||
ImmutableArray<byte> bytecode = TryGetBytecode.GetBytecode(item.ThreadIds, item.Hlsl, out ImmutableArray<Diagnostic> diagnostics);
|
||||
|
||||
EmbeddedBytecodeInfo bytecodeInfo = new(
|
||||
item.ThreadIds.X,
|
||||
@@ -222,123 +220,11 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
// Generate the TryGetBytecode() methods
|
||||
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(item.BytecodeInfo, out Func<SyntaxNode, string> fixup);
|
||||
MethodDeclarationSyntax tryGetBytecodeMethod = TryGetBytecode.GetSyntax(item.BytecodeInfo, out Func<SyntaxNode, string> fixup);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, false);
|
||||
string text = fixup(compilationUnit);
|
||||
|
||||
context.AddSource($"{item.Hierarchy.FilenameHint}.TryGetBytecode", SourceText.From(text, Encoding.UTF8));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader type for a given shader, if any.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
|
||||
/// <param name="iComputeShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IComputeShader"/>.</param>
|
||||
/// <param name="iPixelShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IPixelShader{TPixel}"/>.</param>
|
||||
/// <returns>Either <see cref="IComputeShader"/> or <see cref="IPixelShader{TPixel}"/>, or <see langword="null"/>.</returns>
|
||||
[Pure]
|
||||
private static Type? GetShaderType(
|
||||
INamedTypeSymbol typeSymbol,
|
||||
INamedTypeSymbol iComputeShaderSymbol,
|
||||
INamedTypeSymbol iPixelShaderSymbol)
|
||||
{
|
||||
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces)
|
||||
{
|
||||
if (interfaceSymbol.Name == nameof(IComputeShader) &&
|
||||
SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol))
|
||||
{
|
||||
return typeof(IComputeShader);
|
||||
}
|
||||
|
||||
if (interfaceSymbol.IsGenericType &&
|
||||
interfaceSymbol.Name == nameof(IPixelShader<byte>) &&
|
||||
SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol))
|
||||
{
|
||||
return typeof(IPixelShader<>);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
|
||||
/// </summary>
|
||||
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
|
||||
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> item to insert.</param>
|
||||
/// <param name="canUseSkipLocalsInit">Whether <c>[SkipLocalsInit]</c> can be used.</param>
|
||||
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="methodDeclaration"/>.</returns>
|
||||
[Pure]
|
||||
private static CompilationUnitSyntax GetCompilationUnitFromMethod(
|
||||
HierarchyInfo hierarchyInfo,
|
||||
MethodDeclarationSyntax methodDeclaration,
|
||||
bool canUseSkipLocalsInit)
|
||||
{
|
||||
// Method attributes
|
||||
List<AttributeListSyntax> attributes = new()
|
||||
{
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
|
||||
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
|
||||
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
|
||||
AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
|
||||
AttributeList(SingletonSeparatedList(
|
||||
Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
|
||||
AttributeArgument(LiteralExpression(
|
||||
SyntaxKind.StringLiteralExpression,
|
||||
Literal("This method is not intended to be used directly by user code"))))))
|
||||
};
|
||||
|
||||
// Add [SkipLocalsInit] if the target project allows it
|
||||
if (canUseSkipLocalsInit)
|
||||
{
|
||||
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
|
||||
}
|
||||
|
||||
// Create the partial shader type declaration with the given method implementation.
|
||||
// This code produces a struct declaration as follows:
|
||||
//
|
||||
// partial struct <SHADER_TYPE>
|
||||
// {
|
||||
// <METHOD>
|
||||
// }
|
||||
StructDeclarationSyntax structDeclarationSyntax =
|
||||
StructDeclaration(hierarchyInfo.Names[0])
|
||||
.AddModifiers(Token(SyntaxKind.PartialKeyword))
|
||||
.AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray()));
|
||||
|
||||
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
|
||||
|
||||
// Add all parent types in ascending order, if any
|
||||
foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
|
||||
{
|
||||
typeDeclarationSyntax =
|
||||
ClassDeclaration(parentType)
|
||||
.AddModifiers(Token(SyntaxKind.PartialKeyword))
|
||||
.AddMembers(typeDeclarationSyntax);
|
||||
}
|
||||
|
||||
// Create a static method to create the combined hashcode for a given shader type.
|
||||
// This code takes a block syntax and produces a compilation unit as follows:
|
||||
//
|
||||
// #pragma warning disable
|
||||
//
|
||||
// namespace <NAMESPACE>;
|
||||
//
|
||||
// <TYPE_HIERARCHY>
|
||||
return
|
||||
CompilationUnit().AddMembers(
|
||||
FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
|
||||
.AddMembers(typeDeclarationSyntax)
|
||||
.WithNamespaceKeyword(Token(TriviaList(
|
||||
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
|
||||
SyntaxKind.NamespaceKeyword,
|
||||
TriviaList())))
|
||||
.NormalizeWhitespace(eol: "\n");
|
||||
}
|
||||
}
|
||||
@@ -69,8 +69,8 @@ public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
|
||||
var processedTypes = IShaderGenerator.GetDeclaredTypes(discoveredTypes);
|
||||
var processedConstants = IShaderGenerator.GetDefinedConstants(constantDefinitions);
|
||||
var processedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes);
|
||||
var processedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions);
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする