diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs new file mode 100644 index 00000000..06531460 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchMetadataMethod.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Gets the data related to the shader metadata for a given shader type. + /// + /// The total number of needed 32 bit constants in the shader root signature. + /// Indicates whether the current shader uses an implicit texture. + /// Whether the static sampler is used by the shader. + /// The sequence of captured fields for the shader. + /// The metadata info for the shader. + private static DispatchMetadataInfo GetDispatchMetadataInfo( + int root32BitConstantCount, + bool isImplicitTextureUsed, + bool isSamplerUsed, + ImmutableArray capturedFields) + { + ImmutableArray.Builder descriptors = ImmutableArray.CreateBuilder(); + int constantBufferOffset = 1; + int readOnlyResourceOffset = 0; + int readWriteResourceOffset = 0; + int resourceOffset = 0; + + // Add the implicit texture descriptor, if needed + if (isImplicitTextureUsed) + { + descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); + } + + // Populate the sequence of resource descriptors + foreach (FieldInfo.Resource resource in capturedFields.OfType()) + { + if (HlslKnownTypes.IsConstantBufferType(resource.TypeName)) + { + descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++)); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName)) + { + descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++)); + } + else + { + descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++)); + } + } + + return new( + root32BitConstantCount, + isSamplerUsed, + descriptors.ToImmutable()); + } + + /// + /// Creates a instance for the LoadDispatchMetadata method. + /// + /// The dispatch metadata for the current shader.. + /// The resulting instance for the LoadDispatchMetadata method. + private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchMetadata")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader"))) + .AddParameterListParameters( + Parameter(Identifier("loader")) + .AddModifiers(Token(SyntaxKind.RefKeyword)) + .WithType(IdentifierName("TMetadataLoader")), + Parameter(Identifier("result")) + .AddModifiers(Token(SyntaxKind.OutKeyword)) + .WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}"))) + .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo))); + } + + /// + /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// + /// The dispatch metadata for the current shader.. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // global::System.Span span0 = stackalloc byte[5]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("span0")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); + + // Compute the total number of resources + int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; + + // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("span1")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))))); + + // ref byte r0 = ref span0[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("r0")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span0")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; + statements.Add( + LocalDeclarationStatement( + VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) + .AddVariables( + VariableDeclarator(Identifier("r1")) + .WithInitializer(EqualsValueClause( + RefExpression( + ElementAccessExpression(IdentifierName("span1")) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))))))))); + + // Serialized shader metadata + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});")); + + + // Populate the sequence of resource descriptors + foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors) + { + statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));")); + } + + // Invoke the value delegate to create the opaque root signature handle + statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);")); + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 9afca133..178bb83d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -148,6 +148,30 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); }); + + // Get the dispatch metadata info + IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo MetadataInfo)> dispatchMetadataInfo = + dispatchDataInfo + .Collect() + .Combine(dynamicSourceInfo.Collect()) + .SelectMany(static (item, token) => item.Left.Zip(item.Right, static (left, right) => (DataInfo: left, right.SourceInfo))) + .Select(static (item, token) => ( + item.DataInfo.Hierarchy, + GetDispatchMetadataInfo( + item.DataInfo.Root32BitConstantCount, + item.SourceInfo.ImplicitTextureType is not null, + item.SourceInfo.IsSamplerUsed, + item.DataInfo.FieldInfos))) + .WithComparers(HierarchyInfo.Comparer.Default, DispatchMetadataInfo.Comparer.Default); + + // Generate the LoadDispatchMetadata() methods + context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax buildHlslStringMethod = CreateLoadDispatchMetadataMethod(item.Left.MetadataInfo); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchMetadata", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 5cee1604..a8f28918 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -67,7 +67,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator { // getDispatchIdMethod, // loadDispatchDataMethod, - loadDispatchMetadataMethod, + //loadDispatchMetadataMethod, //buildHlslStringMethod, tryGetBytecodeMethod }; diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs new file mode 100644 index 00000000..cbf3bc4f --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model containing info on shader dispatch metadata. +/// +/// The size of the shader root signature, in 32 bit constants. +/// Whether or not the static sampler is used. +/// The sequence of resource descriptors for the shader. +internal sealed record DispatchMetadataInfo( + int Root32BitConstantCount, + bool IsSamplerUsed, + ImmutableArray ResourceDescriptors) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(DispatchMetadataInfo? x, DispatchMetadataInfo? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.Root32BitConstantCount == y.Root32BitConstantCount && + x.IsSamplerUsed == y.IsSamplerUsed && + x.ResourceDescriptors.SequenceEqual(y.ResourceDescriptors, ResourceDescriptor.Comparer.Default); + } + + /// + public int GetHashCode(DispatchMetadataInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.Root32BitConstantCount); + hashCode.Add(obj.IsSamplerUsed); + hashCode.AddRange(obj.ResourceDescriptors, ResourceDescriptor.Comparer.Default); + + return hashCode.ToHashCode(); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs new file mode 100644 index 00000000..bb5070c4 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A resource descriptor for a captured resource in a shader. +/// +/// The type id for the resource. +/// The offset of the resource in its containing register. +/// The offset of the resource descriptor in the shader root signature. +internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + public bool Equals(ResourceDescriptor? x, ResourceDescriptor? y) + { + if (x is null && y is null) + { + return true; + } + + if (x is null || y is null) + { + return false; + } + + if (ReferenceEquals(x, y)) + { + return true; + } + + return + x.TypeId == y.TypeId && + x.RegisterOffset == y.RegisterOffset && + x.Offset == y.Offset; + } + + /// + public int GetHashCode(ResourceDescriptor obj) + { + return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset); + } + } +}