diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Helpers.cs index b2bc0a1f..2eb8d6a5 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Helpers.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Helpers.cs @@ -10,9 +10,9 @@ partial class ComputeShaderDescriptorGenerator /// /// The input instance to check. /// The instance currently in use. - /// Whether is a "pixel shader like" type. + /// Whether is a "pixel shader like" type. /// Whether is a compute shader type at all. - private static bool TryGetIsPixelShaderLike(INamedTypeSymbol typeSymbol, Compilation compilation, out bool result) + private static bool TryGetIsPixelShaderLike(INamedTypeSymbol typeSymbol, Compilation compilation, out bool isPixelShaderLike) { INamedTypeSymbol computeShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader")!; INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader`1")!; @@ -21,19 +21,19 @@ partial class ComputeShaderDescriptorGenerator { if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol)) { - result = false; + isPixelShaderLike = false; return true; } else if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol)) { - result = true; + isPixelShaderLike = true; return true; } } - result = false; + isPixelShaderLike = false; return false; } diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs index e3b40133..50a3e545 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs @@ -3,11 +3,9 @@ using System.Collections.Immutable; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGeneration.SyntaxProcessors; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; -using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; @@ -22,19 +20,15 @@ partial class ComputeShaderDescriptorGenerator /// /// Gathers info on all resources captured by a given shader type. /// - /// The collection of produced instances. /// The input object currently in use. /// The current shader type being explored. /// Indicates whether the current shader uses an implicit texture. - /// The size of the shader constant buffer. /// The sequence of instances for all captured resources. /// The sequence of instances for all captured resources. public static void GetInfo( - ImmutableArrayBuilder diagnostics, Compilation compilation, ITypeSymbol structDeclarationSymbol, bool isImplicitTextureUsed, - int constantBufferSizeInBytes, out ImmutableArray resources, out ImmutableArray resourceDescriptors) { @@ -96,19 +90,6 @@ partial class ComputeShaderDescriptorGenerator resources = resourceBuilder.ToImmutable(); resourceDescriptors = resourceDescriptorBuilder.ToImmutable(); - - // 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. - if ((constantBufferSizeInBytes / sizeof(int)) + resourceBuilder.Count > 64) - { - diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); - } } /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index e2a576c9..d8e3b9b6 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -98,11 +98,9 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener // Get the resources info Resources.GetInfo( - diagnostics, context.SemanticModel.Compilation, typeSymbol, isImplicitTextureUsed, - constantBufferSizeInBytes, out ImmutableArray resourceInfo, out ImmutableArray resourceDescriptors); diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/ExcedeedComputeShaderDispatchDataSizeAnalyzer.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/ExcedeedComputeShaderDispatchDataSizeAnalyzer.cs new file mode 100644 index 00000000..aca40737 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/Analyzers/ExcedeedComputeShaderDispatchDataSizeAnalyzer.cs @@ -0,0 +1,153 @@ +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.Graphics.Helpers; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.SyntaxProcessors; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.SourceGenerators; + +/// +/// A diagnostic analyzer that generates errors when a compute shader exceeds the maximum root descriptor size. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class ExcedeedComputeShaderDispatchDataSizeAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(ShaderDispatchDataSizeExceeded); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the IComputeShader and IComputeShader symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader") is not { } computeShaderSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader`1") is not { } pixelShaderSymbol) + { + return; + } + + context.RegisterSymbolAction(context => + { + // Only struct types are possible targets + if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Struct } typeSymbol) + { + return; + } + + // If the type is not a compute shader type, immediately bail out + if (!TryGetIsPixelShaderLike(typeSymbol, computeShaderSymbol, pixelShaderSymbol, out bool isPixelShaderLike)) + { + return; + } + + // Setup the resource and byte offsets for tracking. This is the same logic as + // in ComputeShaderDescriptorGenerator.ConstantBuffer, see there for more info. + int constantBufferSizeInBytes = sizeof(int) * (isPixelShaderLike ? 2 : 3); + + // Run the fast-path constant buffer processor logic (same as in the equivalent D2D analyzer) + ConstantBufferSyntaxProcessor.GetInfo( + context.Compilation, + typeSymbol, + ref constantBufferSizeInBytes); + + // Pad the size to get the number of root DWORD constants (see more notes in the same method) + constantBufferSizeInBytes = AlignmentHelper.Pad(constantBufferSizeInBytes, sizeof(int)); + + // Also get the number of captured resources + int resourceCount = GetNumberOfResources(typeSymbol); + + // 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 numberOfDwordConstants = (constantBufferSizeInBytes / sizeof(int)) + resourceCount; + + // Emit an error in case we have in fact exceeded that limit + if (numberOfDwordConstants > 64) + { + context.ReportDiagnostic(Diagnostic.Create( + ShaderDispatchDataSizeExceeded, + typeSymbol.Locations.First(), + typeSymbol, + numberOfDwordConstants)); + } + }, SymbolKind.NamedType); + }); + } + + /// + /// Gets whether a given type is a compute shader type (ie. implements any of the interfaces). + /// + /// The input instance to check. + /// The for "ComputeSharp.IComputeShader". + /// The for "ComputeSharp.IComputeShader`1". + /// Whether is a "pixel shader like" type. + /// Whether is a compute shader type at all. + private static bool TryGetIsPixelShaderLike( + INamedTypeSymbol typeSymbol, + INamedTypeSymbol computeShaderSymbol, + INamedTypeSymbol pixelShaderSymbol, + out bool isPixelShaderLike) + { + foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces) + { + if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol)) + { + isPixelShaderLike = false; + + return true; + } + else if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol)) + { + isPixelShaderLike = true; + + return true; + } + } + + isPixelShaderLike = false; + + return false; + } + + /// + /// Gets the number of captured resources in a given compute shader type. + /// + /// The shader type to inspect. + /// The number of captured resources in the given shader type. + private static int GetNumberOfResources(ITypeSymbol typeSymbol) + { + int resourceCount = 0; + + foreach (ISymbol memberSymbol in typeSymbol.GetMembers()) + { + // Only process instance fields + if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol) + { + continue; + } + + string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName(); + + // Check if the field is a resource + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + resourceCount++; + } + } + + return resourceCount; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 5126f67f..077458cb 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -560,17 +560,17 @@ partial class DiagnosticDescriptors /// /// Gets a for a shader with a root signature that is too large. /// - /// Format: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources". + /// Format: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources (the maximum size for the root signature is 64 DWORD constants, but the actual size was {1})". /// /// public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new( id: "CMPS0041", title: "Shader dispatch data size exceeded", - messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources", + messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources (the maximum size for the root signature is 64 DWORD constants, but the actual size was {1})", category: "ComputeSharp.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources.", + description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources (the maximum size for the root signature is 64 DWORD constants).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); ///