diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index 610a3f83..c1e55e3c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -1,5 +1,4 @@ using System.Collections.Immutable; -using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; @@ -83,73 +82,8 @@ partial class IShaderGenerator { using ImmutableArrayBuilder statements = new(); - StringBuilder textBuilder = new(); - int prologueStatements = 0; - int sizeHint = 64; - - void AppendLine(string text) - { - _ = textBuilder.Append(text); - } - - void AppendParsedStatement(string text) - { - FlushText(); - - statements.Add(ParseStatement(text)); - } - - void FlushText() - { - if (textBuilder.Length > 0) - { - string hlslSource = textBuilder.ToString(); - - _ = textBuilder.Append(hlslSource); - - sizeHint += textBuilder.Length; - - // The indentation level is the current depth + 2 (the method, and the return expression) - SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSource, hierarchyDepth + 2); - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))))); - - _ = textBuilder.Clear(); - } - } - - // 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); - - // Static fields and declared types - AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes); - - // Captured variables - AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations); - - // Captured methods - AppendLine(hlslSourceInfo.CapturedMethods); - - // Entry point - AppendLine(hlslSourceInfo.EntryPoint); - - FlushText(); - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); - statements.Insert( - prologueStatements, + statements.Add( ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, @@ -162,7 +96,16 @@ partial class IShaderGenerator .AddArgumentListArguments( Argument(LiteralExpression( SyntaxKind.NumericLiteralExpression, - Literal(sizeHint))))))); + Literal(hlslSourceInfo.HlslSource.Length))))))); + + // The indentation level is the current depth + 2 (the method, and the return expression) + SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSourceInfo.HlslSource, hierarchyDepth + 2); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))))); return statements.ToImmutable(); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index adffa7b0..80ab5c6c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -15,8 +15,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -#pragma warning disable CS0618 - namespace ComputeSharp.SourceGenerators; /// @@ -34,12 +32,16 @@ partial class IShaderGenerator /// The input object currently in use. /// The node to process. /// The for . + /// The info on the shader thread count size to use. + /// Indicates whether the current shader uses an implicit texture. /// The resulting info on the processed shader. public static HlslShaderSourceInfo GetInfo( ImmutableArrayBuilder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol) + INamedTypeSymbol structDeclarationSymbol, + ThreadIdsInfo threadIds, + out bool isImplicitTextureUsed) { // Detect invalid properties DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); @@ -71,8 +73,12 @@ partial class IShaderGenerator ImmutableArray<(string Name, string Definition)> declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods); ImmutableArray<(string Name, string Value)> definedConstants = GetDefinedConstants(constantDefinitions); + // Check whether an implicit texture is used in the shader + isImplicitTextureUsed = implicitTextureType is not null; + // Get the HLSL source data with the intermediate info return GetHlslSourceInfo( + threadIds, definedConstants, declaredTypes, resourceFields, @@ -538,6 +544,7 @@ partial class IShaderGenerator /// /// Produces the series of statements to build the current HLSL source. /// + /// The info on the shader thread count size to use. /// The sequence of defined constants for the shader. /// The sequence of declared types used by the shader. /// The sequence of resource instance fields for the current shader. @@ -551,6 +558,7 @@ partial class IShaderGenerator /// 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 HlslShaderSourceInfo GetHlslSourceInfo( + ThreadIdsInfo threadIds, ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, @@ -606,20 +614,11 @@ partial class IShaderGenerator // Group size constants AppendLF(); AppendLine("#define __GroupSize__get_X "); - - string headerAndThreadsX = FlushText(); - - AppendLF(); + AppendLineAndLF(threadIds.X.ToString()); AppendLine("#define __GroupSize__get_Y "); - - string threadsY = FlushText(); - - AppendLF(); + AppendLineAndLF(threadIds.Y.ToString()); AppendLine("#define __GroupSize__get_Z "); - - string threadsZ = FlushText(); - - AppendLF(); + AppendLineAndLF(threadIds.Z.ToString()); // Define declarations foreach ((string name, string value) in definedConstants) @@ -627,8 +626,6 @@ partial class IShaderGenerator AppendLineAndLF($"#define {name} {value}"); } - string defines = FlushText(); - // Static fields if (staticFields.Any()) { @@ -654,8 +651,6 @@ partial class IShaderGenerator AppendLineAndLF(typeDefinition); } - string staticFieldsAndDeclaredTypes = FlushText(); - // Captured variables AppendLF(); AppendLineAndLF("cbuffer _ : register(b0)"); @@ -733,8 +728,6 @@ partial class IShaderGenerator AppendLineAndLF(forwardDeclaration); } - string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); - // Captured methods foreach ((string _, string method) in processedMethods) { @@ -742,47 +735,14 @@ partial class IShaderGenerator AppendLineAndLF(method); } - string capturedMethods = FlushText(); - // Entry point AppendLF(); AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); AppendLineAndLF(executeMethod); - string entryPoint = FlushText(); + string hlslSource = FlushText(); - return new( - headerAndThreadsX, - threadsY, - threadsZ, - defines, - staticFieldsAndDeclaredTypes, - capturedFieldsAndResourcesAndForwardDeclarations, - capturedMethods, - entryPoint, - implicitTextureType, - isSamplerUsed, - declaredTypes.Select(static t => t.Name).ToImmutableArray(), - definedConstants.Select(static c => c.Name).ToImmutableArray(), - processedMethods.Select(static m => m.Signature).ToImmutableArray()); - } - - /// - /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). - /// - /// The input instance to use. - /// The non dynamic HLSL source code. - public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo) - { - return - hlslSourceInfo.HeaderAndThreadsX + "" + - hlslSourceInfo.ThreadsY + "" + - hlslSourceInfo.ThreadsZ + "" + - hlslSourceInfo.Defines + - hlslSourceInfo.StaticFieldsAndDeclaredTypes + - hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations + - hlslSourceInfo.CapturedMethods + - hlslSourceInfo.EntryPoint; + return new(hlslSource, isSamplerUsed); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 56ea8dab..1a29c02b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -47,10 +47,7 @@ partial class IShaderGenerator if (!structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName(typeof(EmbeddedBytecodeAttribute).FullName, out AttributeData? attribute)) { // Emit the diagnostics if dynamic shaders are not supported - if (!supportsDynamicShaders) - { - diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol); - } + diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol); return new(true, 0, 0, 0); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 29d98041..ed27be1b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -61,32 +61,34 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator token.ThrowIfCancellationRequested(); + // TryGetBytecode() info + ThreadIdsInfo threadIds = LoadBytecode.GetInfo( + diagnostics, + typeSymbol, + false); + + token.ThrowIfCancellationRequested(); + // BuildHlslSource() info HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo( diagnostics, context.SemanticModel.Compilation, typeDeclaration, - typeSymbol); + typeSymbol, + threadIds, + out bool isImplicitTextureUsed); token.ThrowIfCancellationRequested(); // GetDispatchMetadata() info DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo( root32BitConstantCount, - hlslSourceInfo.ImplicitTextureType is not null, + isImplicitTextureUsed, hlslSourceInfo.IsSamplerUsed, fieldInfos); token.ThrowIfCancellationRequested(); - // TryGetBytecode() info - ThreadIdsInfo threadIds = LoadBytecode.GetInfo( - diagnostics, - typeSymbol, - false); - - token.ThrowIfCancellationRequested(); - return new ShaderInfo( Hierarchy: HierarchyInfo.From(typeSymbol), DispatchData: new DispatchDataInfo( @@ -155,7 +157,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // Transform the raw HLSL source to compile (this step aggregates the HLSL source to ensure compilation is only done for actual HLSL changes) IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.HlslShaderSource), item.ThreadIds)); + .Select(static (item, token) => (item.Hierarchy, item.HlslShaderSource.HlslSource, item.ThreadIds)); // Compile the requested shader bytecodes IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs index eb418c38..e0220a50 100644 --- a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -1,34 +1,8 @@ -using ComputeSharp.SourceGeneration.Helpers; - namespace ComputeSharp.SourceGenerators.Models; /// /// A model for extracted info on a processed HLSL shader. /// -/// The shader generated header and threadsX count declaration. -/// The threadsY count declaration. -/// The threadsZ count declaration. -/// The define statements, if any. -/// The static fields and declared types, if any. -/// The captured fields, and method forward declarations. -/// The captured method implementations. -/// The shader entry point. -/// The type of the implicit texture type, if any. +/// The HLSL source for the shader. /// 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 HlslShaderSourceInfo( - string HeaderAndThreadsX, - string ThreadsY, - string ThreadsZ, - string Defines, - string StaticFieldsAndDeclaredTypes, - string CapturedFieldsAndResourcesAndForwardDeclarations, - string CapturedMethods, - string EntryPoint, - string? ImplicitTextureType, - bool IsSamplerUsed, - EquatableArray DefinedTypes, - EquatableArray DefinedConstants, - EquatableArray MethodSignatures); \ No newline at end of file +internal sealed record HlslShaderSourceInfo(string HlslSource, bool IsSamplerUsed); \ No newline at end of file