From a736c3009d58f00e71409eb24909332479e99469 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 22 Oct 2023 23:56:37 +0200 Subject: [PATCH 1/3] Improve and optimize IsSimpleInputShader helper --- ...lShaderDescriptorGenerator.HlslBytecode.cs | 60 +++++++++++++++---- .../D2DPixelShaderDescriptorGenerator.cs | 2 +- 2 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs index 3a594262..24299b93 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Immutable; using System.ComponentModel; -using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using ComputeSharp.D2D1.Shaders.Translation; @@ -113,34 +112,71 @@ partial class D2DPixelShaderDescriptorGenerator /// /// Extracts the metadata definition for the current shader. /// + /// The input object currently in use. /// The input instance to process. /// The number of inputs for the shader. /// Whether the shader only has simple inputs. - public static bool IsSimpleInputShader(INamedTypeSymbol structDeclarationSymbol, int inputCount) + public static bool IsSimpleInputShader( + Compilation compilation, + INamedTypeSymbol structDeclarationSymbol, + int inputCount) { + return IsSimpleInputShader( + structDeclarationSymbol, + compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputSimpleAttribute")!, + inputCount); + } + + /// + /// Extracts the metadata definition for the current shader. + /// + /// The input instance to process. + /// The symbol for the [D2DInputSimple] attribute. + /// The number of inputs for the shader. + /// Whether the shader only has simple inputs. + public static bool IsSimpleInputShader( + INamedTypeSymbol structDeclarationSymbol, + INamedTypeSymbol d2DInputSimpleSymbolAttributeSymbol, + int inputCount) + { + // We cannot trust the input count to be valid at this point (it may be invalid and + // with diagnostic already emitted for it). So first, just clamp it in the right range. + inputCount = Math.Max(0, Math.Min(8, inputCount)); + // If there are no inputs, the shader is as if only had simple inputs if (inputCount == 0) { return true; } - // Build a map of all simple inputs (unmarked inputs default to being complex) - bool[] simpleInputsMap = new bool[inputCount]; + // Build a map of all simple inputs (unmarked inputs default to being complex). + // We can never have more than 8 inputs, and if there are it means the shader is + // not valid. Just ignore them, and the generator will emit a separate diagnostic. + Span simpleInputsMap = stackalloc bool[8]; + + // We first start with all inputs marked as complex (ie. not simple) + simpleInputsMap.Clear(); foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) { - switch (attributeData.AttributeClass?.GetFullyQualifiedMetadataName()) + // Only retrieve indices of simple inputs that are in range. If an input is out of + // range, the diagnostic for it will already be emitted by a previous generator step. + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, d2DInputSimpleSymbolAttributeSymbol) && + attributeData.ConstructorArguments is [{ Value: >= 0 and < 8 and int index }]) { - // Only retrieve indices of simple inputs that are in range. If an input is out of - // range, the diagnostic for it will already be emitted by a previous generator step. - case "ComputeSharp.D2D1.D2DInputSimpleAttribute" - when attributeData.ConstructorArguments[0].Value is int index && index < inputCount: - simpleInputsMap[index] = true; - break; + simpleInputsMap[index] = true; } } - return simpleInputsMap.All(static x => x); + bool isSimpleInputShader = true; + + // Validate all inputs in our range (filtered by the allowed one) + foreach (bool isSimpleInput in simpleInputsMap[..inputCount]) + { + isSimpleInputShader &= isSimpleInput; + } + + return isSimpleInputShader; } /// diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 8eddfaaa..dd88f388 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -145,7 +145,7 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene token.ThrowIfCancellationRequested(); // Get the shader profile and linking info for LoadBytecode() - bool isLinkingSupported = HlslBytecode.IsSimpleInputShader(typeSymbol, inputCount); + bool isLinkingSupported = HlslBytecode.IsSimpleInputShader(context.SemanticModel.Compilation, typeSymbol, inputCount); D2D1ShaderProfile? requestedShaderProfile = HlslBytecode.GetRequestedShaderProfile(typeSymbol); D2D1CompileOptions? requestedCompileOptions = HlslBytecode.GetRequestedCompileOptions(diagnostics, typeSymbol); D2D1ShaderProfile effectiveShaderProfile = HlslBytecode.GetEffectiveShaderProfile(requestedShaderProfile, out bool isCompilationEnabled); From e09007e910661e7e56fe483a0f46850faceaafe4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 22 Oct 2023 23:59:50 +0200 Subject: [PATCH 2/3] Add InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer --- .../AnalyzerReleases.Shipped.md | 1 + ...ptionsEnableLinkingOnShaderTypeAnalyzer.cs | 67 +++++++++++++++++++ .../Diagnostics/DiagnosticDescriptors.cs | 16 +++++ 3 files changed, 84 insertions(+) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 82766b2e..0dfa9366 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -75,3 +75,4 @@ CMPSD2D0065 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://gith CMPSD2D0066 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0067 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0068 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0069 | ComputeSharp.D2D1.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs new file mode 100644 index 00000000..9309950f --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/Analyzers/InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs @@ -0,0 +1,67 @@ +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever [D2DCompileOptions] is used on a shader type to request linking when not supported. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(InvalidD2D1CompileOptionsEnableLinkingOnShaderType); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + context.RegisterCompilationStartAction(static context => + { + // Get the [D2DCompileOptions], [D2DInputCount] and [D2DInputSimple] symbols + if (context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute") is not { } d2DCompileOptionsAttributeSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputCountAttribute") is not { } d2DInputCountAttributeSymbol || + context.Compilation.GetTypeByMetadataName("ComputeSharp.D2D1.D2DInputSimpleAttribute") is not { } d2DInputSimpleAttributeSymbol) + { + 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 using [D2DCompileOptions] with D2D1CompileOptions.EnableLinking, there's nothing to do + if (!typeSymbol.TryGetAttributeWithType(d2DCompileOptionsAttributeSymbol, out AttributeData? compileOptionsAttribute) || + !((D2D1CompileOptions)compileOptionsAttribute.ConstructorArguments[0].Value!).HasFlag(D2D1CompileOptions.EnableLinking)) + { + return; + } + + // Make sure we have the [D2DInputCount] (if not present, the shader is invalid anyway) and with a valid value + if (!typeSymbol.TryGetAttributeWithType(d2DInputCountAttributeSymbol, out AttributeData? inputCountAttribute) || + inputCountAttribute.ConstructorArguments is not [{ Value: >= 0 and < 8 and int inputCount }]) + { + return; + } + + // Emit a diagnostic if the compile options are not valid for the shader type + if (!D2DPixelShaderDescriptorGenerator.HlslBytecode.IsSimpleInputShader(typeSymbol, d2DInputSimpleAttributeSymbol, inputCount)) + { + context.ReportDiagnostic(Diagnostic.Create( + InvalidD2D1CompileOptionsEnableLinkingOnShaderType, + compileOptionsAttribute.GetLocation(), + typeSymbol)); + } + }, SymbolKind.NamedType); + }); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 206cf6d8..11179510 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1022,4 +1022,20 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "The [D2DGeneratedPixelShaderDescriptor] attribute requires the type of all fields of target types to be accessible from their containing assembly.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for an invalid use of [D2DCompileOptions] requesting to enable linking. + /// + /// Format: "The D2D1 shader of type {0} cannot use D2D1CompileOptions.EnableLinking in its [D2DCompileOptions] attribute, as it doesn't support linking (only D2D1 shaders with no complex inputs can use this option)". + /// + /// + public static readonly DiagnosticDescriptor InvalidD2D1CompileOptionsEnableLinkingOnShaderType = new( + id: "CMPSD2D0069", + title: "Invalid [D2DResourceTextureIndex] use", + messageFormat: """The D2D1 shader of type {0} cannot use D2D1CompileOptions.EnableLinking in its [D2DCompileOptions] attribute, as it doesn't support linking (only D2D1 shaders with no complex inputs can use this option)""", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: "A D2D1 shader cannot use D2D1CompileOptions.EnableLinking in its [D2DCompileOptions] attribute if it doesn't support linking (only D2D1 shaders with no complex inputs can use this option).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file From fe0f68d921e9e261b85276ddce40242e58537bf8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 23 Oct 2023 00:24:29 +0200 Subject: [PATCH 3/3] Add unit tests for new analyzer --- ...teSharp.D2D1.Tests.SourceGenerators.csproj | 5 + ...ptionsEnableLinkingOnShaderTypeAnalyzer.cs | 117 ++++++++++++++++++ ...lyzerWithLanguageVersionTest{TAnalyzer}.cs | 8 ++ 3 files changed, 130 insertions(+) create mode 100644 tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/ComputeSharp.D2D1.Tests.SourceGenerators.csproj b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/ComputeSharp.D2D1.Tests.SourceGenerators.csproj index 4bec77f9..2b3a0b74 100644 --- a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/ComputeSharp.D2D1.Tests.SourceGenerators.csproj +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/ComputeSharp.D2D1.Tests.SourceGenerators.csproj @@ -5,6 +5,7 @@ https://api.nuget.org/v3/index.json; https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json; + $(DefineConstants);D2D1_TESTS @@ -23,4 +24,8 @@ + + + + diff --git a/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs new file mode 100644 index 00000000..6cd4b336 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests.SourceGenerators/Test_InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer.cs @@ -0,0 +1,117 @@ +using System.Threading.Tasks; +using ComputeSharp.D2D1.SourceGenerators; +using ComputeSharp.Tests.SourceGenerators.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.D2D1.Tests.SourceGenerators; + +[TestClass] +public class Test_InvalidD2D1CompileOptionsEnableLinkingOnShaderTypeAnalyzer +{ + [TestMethod] + public async Task NoCompileOptionsDoesNotWarn() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + + public partial class Foo + { + [D2DInputCount(0)] + private partial struct MyShader : ID2D1PixelShader + { + public Float4 Execute() => 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task ValidCompileOptionsDoesNotWarn() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + + public partial class Foo + { + [D2DInputCount(0)] + [D2DCompileOptions(D2D1CompileOptions.PackMatrixRowMajor)] + private partial struct MyShader : ID2D1PixelShader + { + public Float4 Execute() => 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task EnableLinkingWithNoInputCountDoesNotWarn() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + + public partial class Foo + { + [D2DInputComplex(0)] + [D2DCompileOptions(D2D1CompileOptions.EnableLinking)] + private partial struct MyShader : ID2D1PixelShader + { + public Float4 Execute() => 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task EnableLinkingWithImplicitComplexInputWarns() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + + public partial class Foo + { + [D2DInputCount(2)] + [D2DInputSimple(1)] + [{|CMPSD2D0069:D2DCompileOptions(D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking)|}] + private partial struct MyShader : ID2D1PixelShader + { + public Float4 Execute() => 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } + + [TestMethod] + public async Task EnableLinkingWithExplicitComplexInputWarns() + { + const string source = """ + using ComputeSharp; + using ComputeSharp.D2D1; + + public partial class Foo + { + [D2DInputCount(2)] + [D2DInputSimple(0)] + [D2DInputComplex(1)] + [{|CMPSD2D0069:D2DCompileOptions(D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking)|}] + private partial struct MyShader : ID2D1PixelShader + { + public Float4 Execute() => 0; + } + } + """; + + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(source); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs index 44e3afb6..a19d3799 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs @@ -1,5 +1,9 @@ extern alias Core; +#if D2D1_TESTS +extern alias D2D1; +#else extern alias D3D12; +#endif using System.Threading; using System.Threading.Tasks; @@ -48,7 +52,11 @@ internal sealed class CSharpAnalyzerWithLanguageVersionTest : CSharpA test.TestState.ReferenceAssemblies = ReferenceAssemblies.Net.Net80; test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(Core::ComputeSharp.Hlsl).Assembly.Location)); +#if D2D1_TESTS + test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(D2D1::ComputeSharp.D2D1.ID2D1PixelShader).Assembly.Location)); +#else test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(D3D12::ComputeSharp.IComputeShader).Assembly.Location)); +#endif return test.RunAsync(CancellationToken.None); }