From 5210c1ecd9c9e37c74008afb8867f10e8fd5f9d7 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 6 Dec 2021 13:03:25 +0100 Subject: [PATCH] Switch BuildHlslString() to incremental --- ...Incremental.CreateBuildHlslStringMethod.cs | 254 ++++++++++++++++++ ...ncremental.CreateLoadDispatchDataMethod.cs | 6 +- ...Incremental.GetNonDynamicHlslSourceInfo.cs | 31 ++- .../IShaderGenerator.Incremental.cs | 23 +- .../IShaderGenerator.cs | 2 +- .../Models/HierarchyInfo.cs | 53 ++-- ...micHlslSourceInfo.cs => HlslSourceInfo.cs} | 50 +++- 7 files changed, 367 insertions(+), 52 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs rename src/ComputeSharp.SourceGenerators/Models/{NonDynamicHlslSourceInfo.cs => HlslSourceInfo.cs} (59%) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs new file mode 100644 index 00000000..73116592 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateBuildHlslStringMethod.cs @@ -0,0 +1,254 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Text; +using ComputeSharp.__Internals; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618, RS1024 + +namespace ComputeSharp.SourceGenerators; + +/// +public sealed partial class IShaderGenerator2 +{ + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input instance to use. + /// The resulting instance for the BuildHlslString method. + private static MethodDeclarationSyntax CreateBuildHlslStringMethod(HlslSourceInfo hlslSourceInfo) + { + ImmutableArray bodyStatements = GenerateRenderMethodBody(hlslSourceInfo); + + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ) + // { + // + // } + 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)); + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The input instance to use. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static ImmutableArray GenerateRenderMethodBody(HlslSourceInfo hlslSourceInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + StringBuilder textBuilder = new(); + int capturedDelegates = 0; + int prologueStatements = 0; + int sizeHint = 64; + + void AppendLF() + { + textBuilder.Append('\n'); + } + + void AppendLine(string text) + { + textBuilder.Append(text); + } + + void AppendParsedStatement(string text) + { + FlushText(); + + statements.Add(ParseStatement(text)); + } + + void FlushText() + { + if (textBuilder.Length > 0) + { + string text = textBuilder.ToString(); + + textBuilder.Append(text); + + sizeHint += textBuilder.Length; + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text)))))); + + textBuilder.Clear(); + } + } + + // Declare the hashsets to track imported members and types from delegates, if needed + if (!hlslSourceInfo.Delegates.IsEmpty) + { + void DeclareMapping(int index, string name, IEnumerable items) + { + // global::System.Collections.Generic.HashSet = 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++; + + // .Add(""); + foreach (var item in items) + { + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(name), + IdentifierName("Add"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + + prologueStatements++; + } + } + + DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes); + DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants); + DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures); + + // Go through all existing delegate fields, if any + foreach (string fieldName in hlslSourceInfo.Delegates) + { + // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}")) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + prologueStatements++; + } + } + + // Header and thread ids + AppendLine(hlslSourceInfo.HeaderAndThreadsX); + AppendParsedStatement("builder.Append(threadsX);"); + AppendLine(hlslSourceInfo.ThreadsY); + AppendParsedStatement("builder.Append(threadsY);"); + AppendLine(hlslSourceInfo.ThreadsZ); + AppendParsedStatement("builder.Append(threadsZ);"); + + // Define declarations + AppendLine(hlslSourceInfo.Defines); + + // Defines from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); + } + + // Static fields and declared types + AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); + + // Declared types from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); + } + + // Captured variables + AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); + + // Forward declarations from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); + } + + // Remove all forward declarations from methods that are embedded into the shader. + // This is necessary to avoid duplicate definitions from methods from delegates. + if (capturedDelegates > 0) + { + // .Add(""); + foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures) + { + FlushText(); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__methodNames"), + IdentifierName("Remove"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); + } + } + + // Captured methods + AppendLine(hlslSourceInfo.CapturedMethods); + + // Captured methods from captured delegates + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); + } + + // Captured delegate methods + foreach (string fieldName in hlslSourceInfo.Delegates) + { + AppendLF(); + AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); + AppendLF(); + } + + // Entry point + AppendLine(hlslSourceInfo.EntryPoint); + + FlushText(); + + // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); + statements.Insert( + prologueStatements, + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("builder"), + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"), + IdentifierName("Create"))) + .AddArgumentListArguments( + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(sizeHint))))))); + + return statements.ToImmutable(); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs index ca058e47..5624caa2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.CreateLoadDispatchDataMethod.cs @@ -194,14 +194,12 @@ public sealed partial class IShaderGenerator2 /// /// Creates a instance for the LoadDispatchDataMethod method. /// - /// The input instance to use. /// The type of shader interface urrently being processed. /// The array of values for all captured fields. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The resulting instance for the LoadDispatchDataMethod method. private static MethodDeclarationSyntax CreateLoadDispatchDataMethod( - SourceProductionContext context, Type shaderInterfaceType, ImmutableArray fieldInfos, int resourceCount, @@ -228,20 +226,18 @@ public sealed partial class IShaderGenerator2 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, shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); + .WithBody(Block(GetDispatchDataLoadingStatements(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount))); } /// /// Gets a sequence of statements to load the dispatch data for a given shader. /// - /// The current generator context in use. /// The type of shader interface urrently being processed. /// The array of values for all captured fields. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The sequence of instances to load shader dispatch data. private static ImmutableArray GetDispatchDataLoadingStatements( - SourceProductionContext context, Type shaderInterfaceType, ImmutableArray fieldInfos, int resourceCount, diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs index bae405af..09ad0ef4 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.GetNonDynamicHlslSourceInfo.cs @@ -24,14 +24,14 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator2 { /// - /// Creates a instance for the BuildHlslString method. + /// Gathers all necessary information on a transpiled HLSL source for a given shader type. /// /// The input object currently in use. /// The node to process. /// The for . /// The resulting diagnostics from the processing operation. - /// The resulting instance for the BuildHlslString method. - private static (NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) GetNonDynamicHlslSourceInfo( + /// The resulting info on the processed shader. + private static HlslSourceInfo GetNonDynamicHlslSourceInfo( Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -58,7 +58,8 @@ public sealed partial class IShaderGenerator2 var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); var isComputeShader = pixelShaderSymbol is null; var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var instanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var nonDelegateInstanceFields = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var delegateInstanceFields = GetDelegateFieldNames(structDeclarationSymbol); var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); @@ -66,11 +67,14 @@ public sealed partial class IShaderGenerator2 var definedConstants = GetDefinedConstants(constantDefinitions); var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); + diagnostics = builder.ToImmutable(); + // Get the HLSL source data with the intermediate info - NonDynamicHlslSourceInfo sourceInfo = GetNonDynamicHlslSourceInfo( + return GetNonDynamicHlslSourceInfo( definedConstants, declaredTypes, - instanceFields, + nonDelegateInstanceFields, + delegateInstanceFields, staticFields, sharedBuffers, processedMethods, @@ -78,10 +82,6 @@ public sealed partial class IShaderGenerator2 implicitTextureType, isSamplerUsed, entryPoint); - - diagnostics = builder.ToImmutable(); - - return (sourceInfo, implicitTextureType, isSamplerUsed); } /// @@ -485,6 +485,7 @@ public sealed partial class IShaderGenerator2 /// The sequence of defined constants for the shader. /// The sequence of declared types used by the shader. /// The sequence of instance fields for the current shader. + /// The sequence of delegate fields for the current shader. /// The sequence of static fields referenced by the shader. /// The sequence of shared buffers declared by the shader. /// The sequence of processed methods used by the shader. @@ -493,10 +494,11 @@ public sealed partial class IShaderGenerator2 /// Whether the static sampler is used by the shader. /// The body of the entry point of the shader. /// The series of statements to build the HLSL source to compile to execute the current shader. - private static NonDynamicHlslSourceInfo GetNonDynamicHlslSourceInfo( + private static HlslSourceInfo GetNonDynamicHlslSourceInfo( ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> instanceFields, + ImmutableArray delegateInstanceFields, ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, ImmutableArray<(string Signature, string Definition)> processedMethods, @@ -703,6 +705,11 @@ public sealed partial class IShaderGenerator2 capturedFieldsAndResourcesAndForwardDeclarations, capturedMethods, entryPoint, - processedMethods.Select(static m => m.Signature).ToImmutableArray()); + implicitTextureType, + isSamplerUsed, + declaredTypes.Select(static t => t.Name).ToImmutableArray(), + definedConstants.Select(static c => c.Name).ToImmutableArray(), + processedMethods.Select(static m => m.Signature).ToImmutableArray(), + delegateInstanceFields); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs index 718576be..92484930 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Incremental.cs @@ -5,6 +5,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Diagnostics; +using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -104,7 +105,6 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) => { MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod( - context, item.Left.Type, item.Left.FieldInfos, item.Left.ResourceCount, @@ -115,24 +115,37 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator }); // Get the HLSL source info - IncrementalValuesProvider> hlslSourceInfo = + IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Result)> hlslSourceInfoWithErrors = shaderDeclarations .Combine(context.CompilationProvider) .Select(static (item, token) => { - (NonDynamicHlslSourceInfo SourceInfo, string? ImplicitTextureType, bool IsSamplerUsed) hlslInfo = GetNonDynamicHlslSourceInfo( + HlslSourceInfo hlslInfo = GetNonDynamicHlslSourceInfo( item.Right, item.Left.Syntax, item.Left.Symbol, out ImmutableArray diagnostics); - return new Result<(NonDynamicHlslSourceInfo, string?, bool)>(hlslInfo, diagnostics); + return (item.Left.Hierarchy, new Result(hlslInfo, diagnostics)); }); // Output the diagnostics - context.ReportDiagnostics(hlslSourceInfo.Select(static (item, token) => item.Errors)); + context.ReportDiagnostics(hlslSourceInfoWithErrors.Select(static (item, token) => item.Result.Errors)); + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslSourceInfo SourceInfo)> dynamicSourceInfo = + hlslSourceInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, item.Result.Value)) + .WithComparers(HierarchyInfo.Comparer.Default, HlslSourceInfo.Comparer.Default); + // Generate the BuildHlslString() methods + context.RegisterSourceOutput(dynamicSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(item.Left.SourceInfo); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8)); + }); } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 59bd0aae..5cee1604 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -68,7 +68,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator // getDispatchIdMethod, // loadDispatchDataMethod, loadDispatchMetadataMethod, - buildHlslStringMethod, + //buildHlslStringMethod, tryGetBytecodeMethod }; diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs index 6d098bed..dda30c69 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using ComputeSharp.SourceGenerators.Extensions; @@ -38,22 +39,44 @@ internal sealed record HierarchyInfo(string FilenameHint, string Namespace, Immu names.ToImmutable()); } - /// - [Pure] - public bool Equals(HierarchyInfo? other) + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer { - return - other is not null && - (ReferenceEquals(this, other) || - (Namespace == other.Namespace && - (Names == other.Names || - Names.AsSpan().SequenceEqual(other.Names.AsSpan())))); - } + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); - /// - [Pure] - public override int GetHashCode() - { - return HashCode.Combine(Namespace, Names, Names[0]); + /// + public bool Equals(HierarchyInfo? x, HierarchyInfo? 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.FilenameHint == y.FilenameHint && + x.Namespace == y.Namespace && + x.Names.AsSpan().SequenceEqual(y.Names.AsSpan()); + } + + /// + public int GetHashCode(HierarchyInfo obj) + { + return HashCode.Combine(obj.Namespace, obj.Names, obj.Names[0]); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs similarity index 59% rename from src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs rename to src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs index f479b642..3af250f0 100644 --- a/src/ComputeSharp.SourceGenerators/Models/NonDynamicHlslSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslSourceInfo.cs @@ -1,11 +1,12 @@ -using System; +using ComputeSharp.SourceGenerators.Extensions; +using System; using System.Collections.Generic; using System.Collections.Immutable; namespace ComputeSharp.SourceGenerators.Models; /// -/// A model for extracted info on a processed HLSL shader, excluding dynamic information. +/// A model for extracted info on a processed HLSL shader. /// /// The shader generated header and threadsX count declaration. /// The threadsY count declaration. @@ -15,8 +16,13 @@ namespace ComputeSharp.SourceGenerators.Models; /// The captured fields, and method forward declarations. /// The captured method implementations. /// The shader entry point. +/// The type of the implicit texture type, if any. +/// Whether or not the static sampler is used. +/// The names of declared types. +/// The names of defined constants. /// The signatures for captured methods. -internal sealed record NonDynamicHlslSourceInfo( +/// The list of delegate fields. +internal sealed record HlslSourceInfo( string HeaderAndThreadsX, string ThreadsY, string ThreadsZ, @@ -25,15 +31,25 @@ internal sealed record NonDynamicHlslSourceInfo( string CapturedFieldsAndResourcesAndForwardDeclarations, string CapturedMethods, string EntryPoint, - ImmutableArray MethodSignatures) + string? ImplicitTextureType, + bool IsSamplerUsed, + ImmutableArray DefinedTypes, + ImmutableArray DefinedConstants, + ImmutableArray MethodSignatures, + ImmutableArray Delegates) { /// - /// An implementation for . + /// An implementation for . /// - public sealed class Comparer : IEqualityComparer + public sealed class Comparer : IEqualityComparer { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + /// - public bool Equals(NonDynamicHlslSourceInfo? x, NonDynamicHlslSourceInfo? y) + public bool Equals(HlslSourceInfo? x, HlslSourceInfo? y) { if (x is null && y is null) { @@ -59,11 +75,16 @@ internal sealed record NonDynamicHlslSourceInfo( x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations && x.CapturedMethods == y.CapturedMethods && x.EntryPoint == y.EntryPoint && - x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan()); + x.ImplicitTextureType == y.ImplicitTextureType && + x.IsSamplerUsed == y.IsSamplerUsed && + x.DefinedTypes.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) && + x.DefinedConstants.AsSpan().SequenceEqual(y.DefinedTypes.AsSpan()) && + x.MethodSignatures.AsSpan().SequenceEqual(y.MethodSignatures.AsSpan()) && + x.Delegates.AsSpan().SequenceEqual(y.Delegates.AsSpan()); } /// - public int GetHashCode(NonDynamicHlslSourceInfo obj) + public int GetHashCode(HlslSourceInfo obj) { HashCode hashCode = default; @@ -75,11 +96,12 @@ internal sealed record NonDynamicHlslSourceInfo( hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations); hashCode.Add(obj.CapturedMethods); hashCode.Add(obj.EntryPoint); - - foreach (string signature in obj.MethodSignatures) - { - hashCode.Add(signature); - } + hashCode.Add(obj.ImplicitTextureType); + hashCode.Add(obj.IsSamplerUsed); + hashCode.AddRange(obj.DefinedTypes); + hashCode.AddRange(obj.DefinedConstants); + hashCode.AddRange(obj.MethodSignatures); + hashCode.AddRange(obj.Delegates); return hashCode.ToHashCode(); }