Delete non-incremental IShaderGenerator files
このコミットが含まれているのは:
1 親
07c0801911
コミット
a48f036518
19ファイル変更
+13
-2033
検索条件に一致するファイルはありません
@@ -1,834 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Helpers;
|
||||
using ComputeSharp.SourceGenerators.Mappings;
|
||||
using ComputeSharp.SourceGenerators.SyntaxRewriters;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
|
||||
|
||||
#pragma warning disable CS0618, RS1024
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
|
||||
GeneratorExecutionContext context,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out string? implicitTextureType,
|
||||
out bool isSamplerUsed,
|
||||
out string hlslSource)
|
||||
{
|
||||
// Properties are not supported
|
||||
DetectAndReportPropertyDeclarations(context, structDeclarationSymbol);
|
||||
|
||||
// We need to sets to track all discovered custom types and static methods
|
||||
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
|
||||
|
||||
// A given type can only represent a single shader type
|
||||
if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader<byte>) }) > 1)
|
||||
{
|
||||
context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
// Explore the syntax tree and extract the processed info
|
||||
var semanticModel = new SemanticModelProvider(context.Compilation);
|
||||
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
|
||||
var isComputeShader = pixelShaderSymbol is null;
|
||||
var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
|
||||
var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray();
|
||||
var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray();
|
||||
var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader);
|
||||
var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?);
|
||||
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
|
||||
var processedConstants = GetProcessedConstants(constantDefinitions);
|
||||
var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
|
||||
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
|
||||
string structName = structDeclaration.Identifier.Text;
|
||||
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
|
||||
IEnumerable<StatementSyntax> bodyStatements = GenerateRenderMethodBody(
|
||||
processedConstants,
|
||||
staticFields,
|
||||
processedTypes,
|
||||
isComputeShader,
|
||||
processedMembers,
|
||||
pixelShaderTextureType,
|
||||
accessesStaticSampler,
|
||||
sharedBuffers,
|
||||
processedMethods,
|
||||
entryPoint,
|
||||
out hlslSource);
|
||||
|
||||
implicitTextureType = pixelShaderTextureType;
|
||||
isSamplerUsed = accessesStaticSampler;
|
||||
|
||||
// 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>
|
||||
/// Gets a sequence of captured fields and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="types">The collection of currently discovered types.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> types,
|
||||
bool isComputeShader)
|
||||
{
|
||||
bool hlslResourceFound = false;
|
||||
|
||||
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
if (fieldSymbol.IsStatic) continue;
|
||||
|
||||
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
|
||||
|
||||
// Group shared fields must be static
|
||||
if (attribute is not null)
|
||||
{
|
||||
context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name);
|
||||
}
|
||||
|
||||
// Captured fields must be named type symbols
|
||||
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol)
|
||||
{
|
||||
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
string metadataName = typeSymbol.GetFullMetadataName();
|
||||
|
||||
// Allowed fields must be either resources, unmanaged values or delegates
|
||||
if (HlslKnownTypes.IsTypedResourceType(metadataName))
|
||||
{
|
||||
hlslResourceFound = true;
|
||||
|
||||
// Track the type of items in the current buffer
|
||||
if (HlslKnownTypes.IsStructuredBufferType(metadataName))
|
||||
{
|
||||
types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
|
||||
}
|
||||
}
|
||||
else if (!typeSymbol.IsUnmanagedType &&
|
||||
typeSymbol.TypeKind != TypeKind.Delegate)
|
||||
{
|
||||
// Shaders can only capture valid HLSL resource types or unmanaged types
|
||||
context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol);
|
||||
|
||||
continue;
|
||||
}
|
||||
else if (typeSymbol.IsUnmanagedType &&
|
||||
!HlslKnownTypes.IsKnownHlslType(metadataName))
|
||||
{
|
||||
// Track the type if it's a custom struct
|
||||
types.Add(typeSymbol);
|
||||
}
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
|
||||
|
||||
// Yield back the current mapping for the name (if the name used a reserved keyword)
|
||||
yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName);
|
||||
}
|
||||
|
||||
// If the shader is a compute one (so no implicit output texture), it has to contain at least one resource
|
||||
if (!hlslResourceFound && isComputeShader)
|
||||
{
|
||||
context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of shader static fields and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
|
||||
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
|
||||
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <returns>A sequence of static constant fields in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields(
|
||||
GeneratorExecutionContext context,
|
||||
SemanticModelProvider semanticModel,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
{
|
||||
foreach (var fieldDeclaration in structDeclaration.Members.OfType<FieldDeclarationSyntax>())
|
||||
{
|
||||
foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables)
|
||||
{
|
||||
IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!;
|
||||
|
||||
if (!fieldSymbol.IsStatic || fieldSymbol.IsConst)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
|
||||
|
||||
if (attribute is not null) continue;
|
||||
|
||||
// Constant properties must be of a primitive, vector or matrix type
|
||||
if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol ||
|
||||
!HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName()))
|
||||
{
|
||||
context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
|
||||
|
||||
string typeDeclaration = fieldSymbol.IsReadOnly switch
|
||||
{
|
||||
true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}",
|
||||
false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}"
|
||||
};
|
||||
|
||||
StaticFieldRewriter staticFieldRewriter = new(
|
||||
semanticModel,
|
||||
discoveredTypes,
|
||||
constantDefinitions,
|
||||
context);
|
||||
|
||||
string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString();
|
||||
|
||||
yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of captured members and their mapped names.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="types">The collection of currently discovered types.</param>
|
||||
/// <returns>A sequence of captured members in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> types)
|
||||
{
|
||||
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
if (!fieldSymbol.IsStatic) continue;
|
||||
|
||||
AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) });
|
||||
|
||||
if (attribute is null) continue;
|
||||
|
||||
if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol)
|
||||
{
|
||||
context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!typeSymbol.ElementType.IsUnmanagedType)
|
||||
{
|
||||
context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value;
|
||||
|
||||
string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol);
|
||||
|
||||
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
|
||||
|
||||
yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize);
|
||||
|
||||
types.Add((INamedTypeSymbol)typeSymbol.ElementType);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of processed methods declared within a given type.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The type symbol for the shader type.</param>
|
||||
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the current type.</param>
|
||||
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the type to process.</param>
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
|
||||
[Pure]
|
||||
private static (string EntryPoint, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods(
|
||||
GeneratorExecutionContext context,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
bool isComputeShader)
|
||||
{
|
||||
// Find all declared methods in the type
|
||||
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
|
||||
from syntaxNode in structDeclaration.DescendantNodes()
|
||||
where syntaxNode.IsKind(SyntaxKind.MethodDeclaration)
|
||||
select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
|
||||
|
||||
string? entryPoint = null;
|
||||
List<(string, string)> processedMethods = new();
|
||||
bool isSamplerUsed = false;
|
||||
|
||||
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
|
||||
{
|
||||
IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!;
|
||||
bool isShaderEntryPoint =
|
||||
(isComputeShader &&
|
||||
methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) &&
|
||||
methodDeclarationSymbol.ReturnsVoid &&
|
||||
methodDeclarationSymbol.TypeParameters.Length == 0 &&
|
||||
methodDeclarationSymbol.Parameters.Length == 0) ||
|
||||
(!isComputeShader &&
|
||||
methodDeclarationSymbol.Name == nameof(IPixelShader<byte>.Execute) &&
|
||||
methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type
|
||||
methodDeclarationSymbol.TypeParameters.Length == 0 &&
|
||||
methodDeclarationSymbol.Parameters.Length == 0);
|
||||
|
||||
// Create the source rewriter for the current method
|
||||
ShaderSourceRewriter shaderSourceRewriter = new(
|
||||
structDeclarationSymbol,
|
||||
semanticModel,
|
||||
discoveredTypes,
|
||||
staticMethods,
|
||||
constantDefinitions,
|
||||
context,
|
||||
isShaderEntryPoint);
|
||||
|
||||
// Rewrite the method syntax tree
|
||||
MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia();
|
||||
|
||||
// Track the implicit sampler, if used
|
||||
isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed;
|
||||
|
||||
// Emit the extracted local functions first
|
||||
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
|
||||
{
|
||||
processedMethods.Add((
|
||||
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
// If the method is the shader entry point, do additional processing
|
||||
if (isShaderEntryPoint)
|
||||
{
|
||||
processedMethod = isComputeShader switch
|
||||
{
|
||||
true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!,
|
||||
false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)!
|
||||
};
|
||||
|
||||
entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString();
|
||||
}
|
||||
else
|
||||
{
|
||||
processedMethods.Add((
|
||||
processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
}
|
||||
|
||||
// Process static methods as well
|
||||
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
|
||||
{
|
||||
processedMethods.Add((
|
||||
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
|
||||
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
|
||||
}
|
||||
|
||||
return (entryPoint!, processedMethods, isSamplerUsed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of discovered constants.
|
||||
/// </summary>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
|
||||
[Pure]
|
||||
internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
{
|
||||
foreach (var constant in constantDefinitions)
|
||||
{
|
||||
var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName();
|
||||
var constantName = $"__{ownerTypeName}__{constant.Key.Name}";
|
||||
|
||||
yield return (constantName, constant.Value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sequence of processed discovered custom types.
|
||||
/// </summary>
|
||||
/// <param name="types">The sequence of discovered custom types.</param>
|
||||
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
|
||||
internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
|
||||
{
|
||||
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
|
||||
{
|
||||
var structType = type.GetFullMetadataName().ToHlslIdentifierName();
|
||||
var structDeclaration = StructDeclaration(structType);
|
||||
|
||||
// Declare the fields of the current type
|
||||
foreach (var field in type.GetMembers().OfType<IFieldSymbol>())
|
||||
{
|
||||
if (field.IsStatic) continue;
|
||||
|
||||
INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type;
|
||||
|
||||
// Convert the name to the fully qualified HLSL version
|
||||
if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped))
|
||||
{
|
||||
mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName();
|
||||
}
|
||||
|
||||
structDeclaration = structDeclaration.AddMembers(
|
||||
FieldDeclaration(VariableDeclaration(
|
||||
IdentifierName(mapped!)).AddVariables(
|
||||
VariableDeclarator(Identifier(field.Name)))));
|
||||
}
|
||||
|
||||
// Insert the trailing ; right after the closing bracket (after normalization)
|
||||
yield return
|
||||
(structType,
|
||||
structDeclaration
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
|
||||
.ToFullString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds and reports all declared properties in a shader.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType<IPropertySymbol>())
|
||||
{
|
||||
context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Produces the series of statements to build the current HLSL source.
|
||||
/// </summary>
|
||||
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
|
||||
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
|
||||
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
|
||||
/// <param name="isComputeShader">Whether or not the current shader is a compute shader (or a pixel shader).</param>
|
||||
/// <param name="instanceFields">The sequence of instance fields for the current shader.</param>
|
||||
/// <param name="implicitTextureType">The type of the implicit target texture, if present.</param>
|
||||
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
|
||||
/// <param name="sharedBuffers">The sequence of shared buffers declared by the shader.</param>
|
||||
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
|
||||
/// <param name="executeMethod">The body of the entry point of the shader.</param>
|
||||
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
|
||||
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
|
||||
private static IEnumerable<StatementSyntax> GenerateRenderMethodBody(
|
||||
IEnumerable<(string Name, string Value)> definedConstants,
|
||||
IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
|
||||
IEnumerable<(string Name, string Definition)> declaredTypes,
|
||||
bool isComputeShader,
|
||||
IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
|
||||
string? implicitTextureType,
|
||||
bool isSamplerUsed,
|
||||
IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
|
||||
IEnumerable<(string Signature, string Definition)> processedMethods,
|
||||
string executeMethod,
|
||||
out string hlslSource)
|
||||
{
|
||||
List<StatementSyntax> statements = new();
|
||||
StringBuilder chunkedTextBuilder = new();
|
||||
StringBuilder aggregateTextBuilder = new();
|
||||
int capturedDelegates = 0;
|
||||
int prologueStatements = 0;
|
||||
int sizeHint = 64;
|
||||
|
||||
void AppendLF()
|
||||
{
|
||||
chunkedTextBuilder.Append('\n');
|
||||
}
|
||||
|
||||
void AppendLine(string text)
|
||||
{
|
||||
chunkedTextBuilder.Append(text);
|
||||
}
|
||||
|
||||
void AppendLineAndLF(string text)
|
||||
{
|
||||
chunkedTextBuilder.Append(text);
|
||||
chunkedTextBuilder.Append('\n');
|
||||
}
|
||||
|
||||
void AppendCharacterAndLF(char c)
|
||||
{
|
||||
chunkedTextBuilder.Append(c);
|
||||
chunkedTextBuilder.Append('\n');
|
||||
}
|
||||
|
||||
void AppendThreadNumIdentifier(string name)
|
||||
{
|
||||
aggregateTextBuilder.Append(name);
|
||||
}
|
||||
|
||||
void AppendParsedStatement(string text)
|
||||
{
|
||||
FlushText();
|
||||
|
||||
statements.Add(ParseStatement(text));
|
||||
}
|
||||
|
||||
void FlushText()
|
||||
{
|
||||
if (chunkedTextBuilder.Length > 0)
|
||||
{
|
||||
string chunkedText = chunkedTextBuilder.ToString();
|
||||
|
||||
aggregateTextBuilder.Append(chunkedText);
|
||||
|
||||
sizeHint += chunkedTextBuilder.Length;
|
||||
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(chunkedText))))));
|
||||
|
||||
chunkedTextBuilder.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Declare the hashsets to track imported members and types from delegates, if needed
|
||||
if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
|
||||
{
|
||||
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", declaredTypes.Select(static t => t.Name));
|
||||
DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name));
|
||||
DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature));
|
||||
|
||||
// Go through all existing delegate fields, if any
|
||||
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
|
||||
{
|
||||
// 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
|
||||
AppendLineAndLF("// ================================================");
|
||||
AppendLineAndLF("// AUTO GENERATED");
|
||||
AppendLineAndLF("// ================================================");
|
||||
AppendLineAndLF("// This shader was created by ComputeSharp.");
|
||||
AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp.");
|
||||
|
||||
// Group size constants
|
||||
AppendLF();
|
||||
AppendLine("#define __GroupSize__get_X ");
|
||||
AppendParsedStatement("builder.Append(threadsX);");
|
||||
AppendThreadNumIdentifier("<THREADSX>");
|
||||
AppendLF();
|
||||
AppendLine("#define __GroupSize__get_Y ");
|
||||
AppendParsedStatement("builder.Append(threadsY);");
|
||||
AppendThreadNumIdentifier("<THREADSY>");
|
||||
AppendLF();
|
||||
AppendLine("#define __GroupSize__get_Z ");
|
||||
AppendParsedStatement("builder.Append(threadsZ);");
|
||||
AppendThreadNumIdentifier("<THREADSZ>");
|
||||
AppendLF();
|
||||
|
||||
// Define declarations
|
||||
foreach (var (name, value) in definedConstants)
|
||||
{
|
||||
AppendLineAndLF($"#define {name} {value}");
|
||||
}
|
||||
|
||||
// Defines from captured delegates
|
||||
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
|
||||
}
|
||||
|
||||
// Static fields
|
||||
if (staticFields.Any())
|
||||
{
|
||||
AppendLF();
|
||||
|
||||
foreach (var field in staticFields)
|
||||
{
|
||||
if (field.Assignment is string assignment)
|
||||
{
|
||||
AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};");
|
||||
}
|
||||
else
|
||||
{
|
||||
AppendLineAndLF($"{field.TypeDeclaration} {field.Name};");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Declared types
|
||||
foreach (var (_, typeDefinition) in declaredTypes)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF(typeDefinition);
|
||||
}
|
||||
|
||||
// Declared types from captured delegates
|
||||
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
|
||||
}
|
||||
|
||||
// Captured variables
|
||||
AppendLF();
|
||||
AppendLineAndLF("cbuffer _ : register(b0)");
|
||||
AppendCharacterAndLF('{');
|
||||
AppendLineAndLF(" uint __x;");
|
||||
AppendLineAndLF(" uint __y;");
|
||||
|
||||
if (isComputeShader)
|
||||
{
|
||||
AppendLineAndLF(" uint __z;");
|
||||
}
|
||||
|
||||
// User-defined values
|
||||
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.IsUnmanagedType))
|
||||
{
|
||||
AppendLineAndLF($" {fieldType} {fieldName};");
|
||||
}
|
||||
|
||||
AppendCharacterAndLF('}');
|
||||
|
||||
int constantBuffersCount = 1;
|
||||
int readOnlyBuffersCount = 0;
|
||||
int readWriteBuffersCount = 0;
|
||||
|
||||
// Optional implicit texture field
|
||||
if (!isComputeShader)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});");
|
||||
}
|
||||
|
||||
// Optional sampler field
|
||||
if (isSamplerUsed)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF("SamplerState __sampler : register(s);");
|
||||
}
|
||||
|
||||
// Resources
|
||||
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields)
|
||||
{
|
||||
string metadataName = fieldSymbol.Type.GetFullMetadataName();
|
||||
|
||||
if (HlslKnownTypes.IsConstantBufferType(metadataName))
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})");
|
||||
AppendCharacterAndLF('{');
|
||||
AppendLineAndLF($" {fieldType} {fieldName}[2];");
|
||||
AppendCharacterAndLF('}');
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName))
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});");
|
||||
}
|
||||
else if (HlslKnownTypes.IsTypedResourceType(metadataName))
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});");
|
||||
}
|
||||
}
|
||||
|
||||
// Shared buffers
|
||||
foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers)
|
||||
{
|
||||
object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ";
|
||||
|
||||
AppendLF();
|
||||
AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];");
|
||||
}
|
||||
|
||||
// Forward declarations
|
||||
foreach (var (forwardDeclaration, _) in processedMethods)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF(forwardDeclaration);
|
||||
}
|
||||
|
||||
// Forward declarations from captured delegates
|
||||
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
|
||||
{
|
||||
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 (var (forwardDeclaration, _) in processedMethods)
|
||||
{
|
||||
FlushText();
|
||||
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("__methodNames"),
|
||||
IdentifierName("Remove")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
|
||||
}
|
||||
}
|
||||
|
||||
// Captured methods
|
||||
foreach (var (_, method) in processedMethods)
|
||||
{
|
||||
AppendLF();
|
||||
AppendLineAndLF(method);
|
||||
}
|
||||
|
||||
// Captured methods from captured delegates
|
||||
foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
|
||||
{
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
|
||||
}
|
||||
|
||||
// Captured delegate methods
|
||||
foreach (var (fieldSymbol, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate))
|
||||
{
|
||||
AppendLF();
|
||||
AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
|
||||
AppendLF();
|
||||
}
|
||||
|
||||
// Entry point
|
||||
AppendLF();
|
||||
AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
|
||||
AppendLineAndLF(executeMethod);
|
||||
|
||||
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)))))));
|
||||
|
||||
hlslSource = aggregateTextBuilder.ToString();
|
||||
|
||||
return statements;
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using ComputeSharp.__Internals;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
|
||||
{
|
||||
// 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(structDeclarationSymbol, out isDynamicShader));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
|
||||
/// </summary>
|
||||
/// <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>
|
||||
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
|
||||
[Pure]
|
||||
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
|
||||
{
|
||||
var delegateFields = structDeclarationSymbol
|
||||
.GetMembers()
|
||||
.OfType<IFieldSymbol>()
|
||||
.Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
|
||||
.ToImmutableArray();
|
||||
|
||||
isDynamicShader = delegateFields.Length > 0;
|
||||
|
||||
if (delegateFields.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 (IFieldSymbol fieldSymbol in delegateFields)
|
||||
{
|
||||
// hashCode.Add(delegateField.Method);
|
||||
blockStatements.Add(ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("hashCode"),
|
||||
IdentifierName("Add")))
|
||||
.AddArgumentListArguments(Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName(fieldSymbol.Name),
|
||||
IdentifierName("Method"))))));
|
||||
}
|
||||
|
||||
// return hashCode.ToHashCode();
|
||||
blockStatements.Add(ReturnStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("hashCode"),
|
||||
IdentifierName("ToHashCode")))));
|
||||
|
||||
return Block(blockStatements);
|
||||
}
|
||||
}
|
||||
@@ -1,335 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.Core.Helpers;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using ComputeSharp.SourceGenerators.Mappings;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out IReadOnlyCollection<string> discoveredResources,
|
||||
out 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(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch data for a given shader.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection<string> discoveredResources, out int root32BitConstantsCount)
|
||||
{
|
||||
List<StatementSyntax> statements = new();
|
||||
List<string> resources = new();
|
||||
|
||||
discoveredResources = resources;
|
||||
|
||||
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
|
||||
var isComputeShader = pixelShaderSymbol is null;
|
||||
int resourceOffset = 0;
|
||||
int rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
|
||||
|
||||
// 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 (isComputeShader)
|
||||
{
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
|
||||
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
|
||||
}
|
||||
|
||||
// Append the statements to load all fields (both resources and other captured values)
|
||||
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, resources, statements);
|
||||
|
||||
// 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.
|
||||
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
|
||||
root32BitConstantsCount = rawDataOffset / 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 = root32BitConstantsCount + resourceOffset;
|
||||
|
||||
if (rootSignatureDwordSize > 64)
|
||||
{
|
||||
context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
// 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 (resourceOffset > 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(resourceOffset)))))))))));
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <param name="currentTypeSymbol">The current type being explored.</param>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="resourceOffset">The current offset in the root table of loaded resources.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
/// <param name="resources">The target list of resources in the current shader type.</param>
|
||||
/// <param name="statements">The target list of statements being generated.</param>
|
||||
private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection<string> fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection<string> resources, ICollection<StatementSyntax> statements)
|
||||
{
|
||||
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)
|
||||
{
|
||||
string fieldName = fieldSymbol.Name;
|
||||
string typeName = fieldSymbol.Type.GetFullMetadataName();
|
||||
|
||||
// Disambiguates the name of target fields against the current input parameters
|
||||
if (fieldName is "loader" or "device" or "x" or "y" or "z")
|
||||
{
|
||||
fieldName = $"this.{fieldName}";
|
||||
}
|
||||
|
||||
// The first item in each nested struct needs to be aligned to 16 bytes
|
||||
if (isFirstField && fieldPath.Count > 0)
|
||||
{
|
||||
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
isFirstField = false;
|
||||
}
|
||||
|
||||
if (HlslKnownTypes.IsTypedResourceType(typeName))
|
||||
{
|
||||
resources.Add(typeName);
|
||||
|
||||
statements.Add(ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++})"),
|
||||
ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)"))));
|
||||
}
|
||||
else if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements);
|
||||
}
|
||||
else if (fieldSymbol.Type.IsUnmanagedType)
|
||||
{
|
||||
// Custom struct type defined by the user
|
||||
AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a loading statement for a known HLSL primitive type field (scalar, vector or 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>
|
||||
/// <param name="statements">The target list of statements being generated.</param>
|
||||
private static void AppendHlslKnownTypeField(IEnumerable<string> fieldPath, string typeName, ref int rawDataOffset, ICollection<StatementSyntax> statements)
|
||||
{
|
||||
// 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))
|
||||
{
|
||||
string rowTypeName = $"global::ComputeSharp.{elementName}{columns}";
|
||||
string rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
|
||||
|
||||
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{typeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", 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 < rows; j++)
|
||||
{
|
||||
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
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){rawDataOffset}))"),
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
|
||||
|
||||
rawDataOffset += fieldPack * columns;
|
||||
}
|
||||
}
|
||||
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.
|
||||
rawDataOffset = AlignmentHelper.AlignToBoundary(
|
||||
AlignmentHelper.Pad(rawDataOffset, fieldPack),
|
||||
fieldSize,
|
||||
16);
|
||||
|
||||
statements.Add(ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{typeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
|
||||
ParseExpression($"{string.Join(".", fieldPath)}"))));
|
||||
|
||||
rawDataOffset += fieldSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGenerators.Mappings;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
|
||||
string? implicitTextureType,
|
||||
IReadOnlyCollection<string> discoveredResources,
|
||||
int root32BitConstantsCount,
|
||||
bool isSamplerUsed)
|
||||
{
|
||||
// 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(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
|
||||
/// </summary>
|
||||
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
|
||||
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
|
||||
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
private static IEnumerable<StatementSyntax> GetDispatchMetadataLoadingStatements(
|
||||
string? implicitTextureType,
|
||||
IReadOnlyCollection<string> discoveredResources,
|
||||
int root32BitConstantsCount,
|
||||
bool isSamplerUsed)
|
||||
{
|
||||
// global::System.Span<byte> span0 = stackalloc byte[5];
|
||||
yield return
|
||||
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 (discovered ones and the implicit target texture, if present)
|
||||
int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0);
|
||||
|
||||
// Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[<ADJUSTED_COUNT>];
|
||||
yield return
|
||||
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];
|
||||
yield return
|
||||
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];
|
||||
yield return
|
||||
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
|
||||
yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {root32BitConstantsCount});");
|
||||
yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});");
|
||||
|
||||
int constantBufferOffset = 1;
|
||||
int readOnlyResourceOffset = 0;
|
||||
int readWriteResourceOffset = 0;
|
||||
int resourceOffset = 0;
|
||||
|
||||
// Add the implicit texture descriptor, if needed
|
||||
if (implicitTextureType is not null)
|
||||
{
|
||||
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
|
||||
}
|
||||
|
||||
// Populate the sequence of resource descriptors
|
||||
foreach (var resource in discoveredResources)
|
||||
{
|
||||
if (HlslKnownTypes.IsConstantBufferType(resource))
|
||||
{
|
||||
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(2, {constantBufferOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
|
||||
}
|
||||
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource))
|
||||
{
|
||||
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
|
||||
}
|
||||
else
|
||||
{
|
||||
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
|
||||
}
|
||||
}
|
||||
|
||||
// Invoke the value delegate to create the opaque root signature handle
|
||||
yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);");
|
||||
}
|
||||
}
|
||||
@@ -1,322 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.Exceptions;
|
||||
using ComputeSharp.Shaders.Translation;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
|
||||
/// </summary>
|
||||
private static bool areDxcLibrariesLoaded;
|
||||
|
||||
/// <inheritdoc/>
|
||||
private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
bool isDynamicShader,
|
||||
string hlslSource,
|
||||
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(GetShaderBytecodeBody(context, structDeclarationSymbol, isDynamicShader, hlslSource, out bytecodeLiterals));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
|
||||
/// </summary>
|
||||
/// <param name="context">The current generator context in use.</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="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
|
||||
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
|
||||
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
|
||||
[Pure]
|
||||
private static unsafe BlockSyntax GetShaderBytecodeBody(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
bool isDynamicShader,
|
||||
string hlslSource,
|
||||
out string? bytecodeLiterals)
|
||||
{
|
||||
AttributeData? attribute = structDeclarationSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(EmbeddedBytecodeAttribute) });
|
||||
|
||||
// No embedded shader was requested
|
||||
if (attribute is null)
|
||||
{
|
||||
goto Failure;
|
||||
}
|
||||
|
||||
// If the current shader is dynamic, emit a diagnostic error
|
||||
if (isDynamicShader)
|
||||
{
|
||||
context.ReportDiagnostic(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
|
||||
|
||||
goto Failure;
|
||||
}
|
||||
|
||||
// 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)
|
||||
{
|
||||
context.ReportDiagnostic(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol);
|
||||
|
||||
goto Failure;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Try to load dxcompiler.dll and dxil.dll
|
||||
LoadNativeDxcLibraries();
|
||||
|
||||
// Replace the actual thread num values
|
||||
hlslSource = hlslSource.Replace("<THREADSX>", threadsX.ToString()).Replace("<THREADSY>", threadsY.ToString()).Replace("<THREADSZ>", threadsZ.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());
|
||||
|
||||
// Build and set the text with the literal expressions
|
||||
bytecodeLiterals = BuildShaderBytecodeExpressionString(new ReadOnlySpan<byte>(buffer, length));
|
||||
|
||||
// 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(threadsX))),
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsY"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsY)))),
|
||||
BinaryExpression(
|
||||
SyntaxKind.EqualsExpression,
|
||||
IdentifierName("threadsZ"),
|
||||
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsZ)))),
|
||||
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)));
|
||||
}
|
||||
catch (Win32Exception e)
|
||||
{
|
||||
context.ReportDiagnostic(
|
||||
EmbeddedBytecodeFailedWithWin32Exception,
|
||||
structDeclarationSymbol,
|
||||
structDeclarationSymbol,
|
||||
e.HResult,
|
||||
e.Message);
|
||||
}
|
||||
catch (HlslCompilationException e)
|
||||
{
|
||||
context.ReportDiagnostic(
|
||||
EmbeddedBytecodeFailedWithHlslCompilationException,
|
||||
structDeclarationSymbol,
|
||||
structDeclarationSymbol,
|
||||
e.Message);
|
||||
}
|
||||
|
||||
Failure:
|
||||
bytecodeLiterals = null;
|
||||
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// bytecode = default;
|
||||
//
|
||||
// return false;
|
||||
return
|
||||
Block(
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
IdentifierName("bytecode"),
|
||||
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
|
||||
ReturnStatement(
|
||||
LiteralExpression(
|
||||
SyntaxKind.FalseLiteralExpression)));
|
||||
}
|
||||
|
||||
/// <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);
|
||||
|
||||
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
|
||||
{
|
||||
Architecture.X64 => "x64",
|
||||
Architecture.Arm64 => "arm64",
|
||||
_ => throw new NotSupportedException("Invalid process architecture")
|
||||
};
|
||||
|
||||
LoadLibrary(ExtractLibrary(rid, "dxil"));
|
||||
LoadLibrary(ExtractLibrary(rid, "dxcompiler"));
|
||||
}
|
||||
|
||||
areDxcLibrariesLoaded = true;
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -12,7 +12,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gathers all necessary information on a transpiled HLSL source for a given shader type.
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ using Microsoft.CodeAnalysis;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the names of all instance fields of a <see cref="System.Delegate"/> type.
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ using ComputeSharp.SourceGenerators.Models;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the data related to the shader metadata for a given shader type.
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator2
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the thread ids values for a given shader type, if available.
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace ComputeSharp.SourceGenerators;
|
||||
/// A source generator creating data loaders for <see cref="IComputeShader"/> and <see cref="IPixelShader{TPixel}"/> types.
|
||||
/// </summary>
|
||||
[Generator]
|
||||
public sealed partial class IShaderGenerator2 : IIncrementalGenerator
|
||||
public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class IShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
|
||||
/// </summary>
|
||||
private sealed class SyntaxReceiver : ISyntaxContextReceiver
|
||||
{
|
||||
/// <summary>
|
||||
/// The list of info gathered during exploration.
|
||||
/// </summary>
|
||||
private readonly List<Item> gatheredInfo = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of gathered info to process.
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
|
||||
{
|
||||
if (context.Node is StructDeclarationSyntax structDeclaration &&
|
||||
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
|
||||
structSymbol.Interfaces.Any(static interfaceSymbol =>
|
||||
interfaceSymbol.Name == nameof(IComputeShader) ||
|
||||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A model for a group of item representing a discovered type to process.
|
||||
/// </summary>
|
||||
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
|
||||
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
|
||||
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.SourceGenerators.Extensions;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
|
||||
|
||||
namespace ComputeSharp.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A source generator creating data loaders for <see cref="IComputeShader"/> and <see cref="IPixelShader{TPixel}"/> types.
|
||||
/// </summary>
|
||||
[Generator]
|
||||
public sealed partial class IShaderGenerator : ISourceGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
{
|
||||
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
// Get the syntax receiver with the candidate nodes
|
||||
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
|
||||
{
|
||||
try
|
||||
{
|
||||
OnExecute(context, item.StructDeclaration, item.StructSymbol);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes a given target type.
|
||||
/// </summary>
|
||||
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
|
||||
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
|
||||
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
|
||||
{
|
||||
// Create the required interface methods for the current shader type
|
||||
MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol, out bool isDynamicShader);
|
||||
MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants);
|
||||
MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out string hlslSource);
|
||||
MethodDeclarationSyntax loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed);
|
||||
MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(context, structDeclarationSymbol, isDynamicShader, hlslSource, out string? bytecodeLiterals);
|
||||
|
||||
// Reorder the method declarations to respect the order in the interface definition
|
||||
MethodDeclarationSyntax[] methods =
|
||||
{
|
||||
// getDispatchIdMethod,
|
||||
// loadDispatchDataMethod,
|
||||
//loadDispatchMetadataMethod,
|
||||
//buildHlslStringMethod,
|
||||
//tryGetBytecodeMethod
|
||||
};
|
||||
|
||||
// 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 and can access it
|
||||
if (context.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
|
||||
context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInit") is not null)
|
||||
{
|
||||
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
|
||||
}
|
||||
|
||||
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
|
||||
string structName = structDeclaration.Identifier.Text;
|
||||
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
|
||||
|
||||
// Create the partial shader type declaration with the hashcode interface method implementation.
|
||||
// This code produces a struct declaration as follows:
|
||||
//
|
||||
// public <MODIFIERS> struct ShaderType
|
||||
// {
|
||||
// <METHODS_LIST>
|
||||
// }
|
||||
var structDeclarationSyntax =
|
||||
StructDeclaration(structName)
|
||||
.WithModifiers(structModifiers)
|
||||
.AddMembers(methods.Select(m => m.AddAttributeLists(attributes.ToArray())).ToArray());
|
||||
|
||||
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
|
||||
|
||||
// Add all parent types in ascending order, if any
|
||||
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
|
||||
{
|
||||
typeDeclarationSyntax = parentType
|
||||
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
|
||||
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
|
||||
.WithBaseList(null)
|
||||
.WithAttributeLists(List<AttributeListSyntax>())
|
||||
.WithoutTrivia();
|
||||
}
|
||||
|
||||
// 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 <SHADER_NAMESPACE>;
|
||||
//
|
||||
// <SHADER_DECLARATION>
|
||||
var source =
|
||||
CompilationUnit().AddMembers(
|
||||
FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
|
||||
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
|
||||
.NormalizeWhitespace(eol: "\n")
|
||||
.ToFullString();
|
||||
|
||||
// Insert the bytecode literals, if needed
|
||||
if (bytecodeLiterals is not null)
|
||||
{
|
||||
source = source.Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
|
||||
}
|
||||
|
||||
// Add the method source attribute
|
||||
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
|
||||
/// </summary>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the input struct declaration.</param>
|
||||
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
|
||||
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
|
||||
/// </summary>
|
||||
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the input struct declaration.</param>
|
||||
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
|
||||
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out IReadOnlyCollection<string> discoveredResources,
|
||||
out int root32BitConstantsCount);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
|
||||
/// </summary>
|
||||
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
|
||||
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
|
||||
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
|
||||
/// <param name="isSamplerUsed">Whether or not the current shader type requires a static sampler to be available.</param>
|
||||
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
|
||||
GeneratorExecutionContext context,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
out string? implicitTextureType,
|
||||
out bool isSamplerUsed,
|
||||
out string hlslSource);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
|
||||
/// </summary>
|
||||
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
|
||||
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
|
||||
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
|
||||
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
|
||||
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
|
||||
string? implicitTextureType,
|
||||
IReadOnlyCollection<string> discoveredResources,
|
||||
int root32BitConstantsCount,
|
||||
bool isSamplerUsed);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
|
||||
/// </summary>
|
||||
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
|
||||
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type.</param>
|
||||
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
|
||||
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
|
||||
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
|
||||
private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
bool isDynamicShader,
|
||||
string hlslSource,
|
||||
out string? bytecodeLiterals);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ComputeSharp.__Internals;
|
||||
using ComputeSharp.SourceGenerators.Diagnostics;
|
||||
@@ -70,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.GetProcessedTypes(discoveredTypes).ToArray();
|
||||
var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions);
|
||||
var processedTypes = IShaderGenerator.GetDeclaredTypes(discoveredTypes);
|
||||
var processedConstants = IShaderGenerator.GetDefinedConstants(constantDefinitions);
|
||||
|
||||
// Create the compilation unit with the source attribute
|
||||
var source =
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする