From ac66eb78275d1df7b2bd66efc79064ac6ddc72bd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 02:41:14 +0100 Subject: [PATCH 1/8] Add RequiresDoublePrecisionSupportAttribute --- .../RequiresDoublePrecisionSupportAttribute.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/ComputeSharp/Attributes/RequiresDoublePrecisionSupportAttribute.cs diff --git a/src/ComputeSharp/Attributes/RequiresDoublePrecisionSupportAttribute.cs b/src/ComputeSharp/Attributes/RequiresDoublePrecisionSupportAttribute.cs new file mode 100644 index 00000000..baf75a5e --- /dev/null +++ b/src/ComputeSharp/Attributes/RequiresDoublePrecisionSupportAttribute.cs @@ -0,0 +1,16 @@ +using System; + +namespace ComputeSharp; + +/// +/// An attribute for a compute shader indicating that the shader requires support for double precision operations. +/// +/// +/// This attribute does not map to any HLSL feature or compile option directly, but it is needed to make using double +/// precision operations opt-in. It is easy to accidentally introduce them in a shader when that is not intented, and +/// doing so can make the shader run slower and not being compatible with some GPUs (eg. many arm64 GPUs lack support +/// for double precision operations). To avoid this, support is disabled by default, and it is necessary to add this +/// attribute over a shader type to explicitly allow using these operations. +/// +[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] +public sealed class RequiresDoublePrecisionSupportAttribute : Attribute; \ No newline at end of file From 35bc8ce6494dc6d4e2e1bce3b97be80064faf3dc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 02:47:54 +0100 Subject: [PATCH 2/8] Minor code tweaks to DX12 generator --- ...lShaderDescriptorGenerator.HlslBytecode.cs | 8 +++--- ...eShaderDescriptorGenerator.HlslBytecode.cs | 16 ++++++++++-- .../Dxc/DxcShaderCompiler.cs | 26 +++++++++---------- 3 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs index bbe3d69c..334bb349 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs @@ -202,7 +202,7 @@ partial class D2DPixelShaderDescriptorGenerator token.ThrowIfCancellationRequested(); // Compile the shader bytecode using the effective parameters - using ComPtr dxcBlobBytecode = D3DCompiler.Compile( + using ComPtr d3DBlob = D3DCompiler.Compile( key.HlslSource.AsSpan(), key.ShaderProfile, key.CompileOptions); @@ -210,12 +210,12 @@ partial class D2DPixelShaderDescriptorGenerator token.ThrowIfCancellationRequested(); // Check whether double precision operations are required - bool requiresDoublePrecisionSupport = D3DCompiler.IsDoublePrecisionSupportRequired(dxcBlobBytecode.Get()); + bool requiresDoublePrecisionSupport = D3DCompiler.IsDoublePrecisionSupportRequired(d3DBlob.Get()); token.ThrowIfCancellationRequested(); - byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); - int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + byte* buffer = (byte*)d3DBlob.Get()->GetBufferPointer(); + int length = checked((int)d3DBlob.Get()->GetBufferSize()); byte[] array = new ReadOnlySpan(buffer, length).ToArray(); diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs index a5fd49c7..25652d20 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs @@ -10,6 +10,8 @@ using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Dxc; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; +using Windows.Win32; +using Windows.Win32.Graphics.Direct3D.Dxc; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; @@ -53,11 +55,21 @@ partial class ComputeShaderDescriptorGenerator token.ThrowIfCancellationRequested(); // Compile the shader bytecode - byte[] bytecode = DxcShaderCompiler.Instance.Compile(key.HlslSource.AsSpan(), key.CompileOptions, token); + using ComPtr dxcBlob = DxcShaderCompiler.Instance.Compile( + key.HlslSource.AsSpan(), + key.CompileOptions, + token); token.ThrowIfCancellationRequested(); - return new HlslBytecodeInfo.Success(Unsafe.As>(ref bytecode)); + byte* buffer = (byte*)dxcBlob.Get()->GetBufferPointer(); + int length = checked((int)dxcBlob.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + ImmutableArray bytecode = Unsafe.As>(ref array); + + return new HlslBytecodeInfo.Success(bytecode); } catch (Win32Exception e) { diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs index 9e2edff9..fef2d180 100644 --- a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs +++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; @@ -73,7 +74,7 @@ internal sealed unsafe class DxcShaderCompiler /// The compile options to use. /// The used to cancel the operation, if needed. /// The bytecode for the compiled shader. - public byte[] Compile(ReadOnlySpan source, CompileOptions compileOptions, CancellationToken token) + public ComPtr Compile(ReadOnlySpan source, CompileOptions compileOptions, CancellationToken token) { using ComPtr dxcResult = default; @@ -232,20 +233,18 @@ internal sealed unsafe class DxcShaderCompiler dxcResult.Get()->GetStatus(&status).Assert(); - // The compilation was successful, so we can extract the shader bytecode - if (status == 0) + // Throw an exception with the input messages, if the compilation fails + if (status != 0) { - using ComPtr dxcBlobBytecode = default; - - dxcResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert(); - - byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); - int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); - - return new ReadOnlySpan(buffer, length).ToArray(); + ThrowHslsCompilationException(dxcResult.Get()); } - return ThrowHslsCompilationException(dxcResult.Get()); + using ComPtr dxcBlobBytecode = default; + + // The compilation was successful, so we can extract the shader bytecode + dxcResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).Assert(); + + return dxcBlobBytecode.Move(); } /// @@ -253,8 +252,9 @@ internal sealed unsafe class DxcShaderCompiler /// /// The input (faulting) operation. /// This method always throws and never actually returs. + [DoesNotReturn] [MethodImpl(MethodImplOptions.NoInlining)] - private static byte[] ThrowHslsCompilationException(IDxcResult* dxcResult) + private static void ThrowHslsCompilationException(IDxcResult* dxcResult) { using ComPtr dxcBlobEncodingError = default; From 9bad2e99dbd0ddf92638a08c125fdc89cc3a9e06 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 02:55:27 +0100 Subject: [PATCH 3/8] Add double precision support check to DX12 generator --- .../ComputeSharp.D2D1.SourceGenerators.csproj | 1 - .../Fxc/D3DCompiler.cs | 2 +- .../Models/HlslBytecodeInfo.cs | 13 ++------- ...eShaderDescriptorGenerator.HlslBytecode.cs | 7 ++++- .../ComputeSharp.SourceGenerators.csproj | 1 - .../Dxc/DxcShaderCompiler.cs | 27 +++++++++++++++++++ .../NativeMethods.txt | 3 +++ 7 files changed, 39 insertions(+), 15 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index a17cda56..1644d727 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -1,7 +1,6 @@ netstandard2.0 - $(DefineConstants);D2D1_GENERATOR diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Fxc/D3DCompiler.cs b/src/ComputeSharp.D2D1.SourceGenerators/Fxc/D3DCompiler.cs index 41d105ca..0709fd22 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Fxc/D3DCompiler.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Fxc/D3DCompiler.cs @@ -26,7 +26,7 @@ partial class D3DCompiler pInterface: &iidOfID3D11ShaderReflection, ppReflector: (void**)d3D11ShaderReflection.GetAddressOf()).Assert(); - ulong doublePrecisionFlags = DirectX.D3D_SHADER_REQUIRES_DOUBLES | DirectX.D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS; + const ulong doublePrecisionFlags = DirectX.D3D_SHADER_REQUIRES_DOUBLES | DirectX.D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS; return (d3D11ShaderReflection.Get()->GetRequiresFlags() & doublePrecisionFlags) != 0; } diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Models/HlslBytecodeInfo.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Models/HlslBytecodeInfo.cs index 96a5601b..0ae53ca5 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Models/HlslBytecodeInfo.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Models/HlslBytecodeInfo.cs @@ -11,17 +11,8 @@ internal abstract record HlslBytecodeInfo /// A successfully compiled HLSL shader. /// /// The resulting HLSL bytecode. - public sealed record Success( -#if D3D12_GENERATOR - EquatableArray Bytecode) -#else - -#pragma warning disable CS1573 - EquatableArray Bytecode, - bool RequiresDoublePrecisionSupport) // Whether the shader requires support for double precision operations. -#pragma warning restore CS1573 -#endif - : HlslBytecodeInfo; + /// Whether the shader requires support for double precision operations. + public sealed record Success(EquatableArray Bytecode, bool RequiresDoublePrecisionSupport) : HlslBytecodeInfo; /// /// An HLSL shader that failed to compile due to a Win32 error. diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs index 25652d20..2d44b94d 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs @@ -62,6 +62,11 @@ partial class ComputeShaderDescriptorGenerator token.ThrowIfCancellationRequested(); + // Check whether double precision operations are required + bool requiresDoublePrecisionSupport = DxcShaderCompiler.Instance.IsDoublePrecisionSupportRequired(dxcBlob.Get()); + + token.ThrowIfCancellationRequested(); + byte* buffer = (byte*)dxcBlob.Get()->GetBufferPointer(); int length = checked((int)dxcBlob.Get()->GetBufferSize()); @@ -69,7 +74,7 @@ partial class ComputeShaderDescriptorGenerator ImmutableArray bytecode = Unsafe.As>(ref array); - return new HlslBytecodeInfo.Success(bytecode); + return new HlslBytecodeInfo.Success(bytecode, requiresDoublePrecisionSupport); } catch (Win32Exception e) { diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index c6ecff10..330353f5 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -1,7 +1,6 @@ netstandard2.0 - $(DefineConstants);D3D12_GENERATOR diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs index fef2d180..6b82a99f 100644 --- a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs +++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs @@ -6,6 +6,8 @@ using System.Threading; using Windows.Win32; using Windows.Win32.Foundation; using Windows.Win32.Graphics.Direct3D.Dxc; +using Windows.Win32.Graphics.Direct3D12; +using DirectX = Windows.Win32.PInvoke; namespace ComputeSharp.SourceGenerators.Dxc; @@ -247,6 +249,31 @@ internal sealed unsafe class DxcShaderCompiler return dxcBlobBytecode.Move(); } + /// + /// Checks whether double precision support is required. + /// + /// The input HLSL bytecode to inspect. + /// Whether double precision support is required for . + public bool IsDoublePrecisionSupportRequired(IDxcBlob* dxcBlob) + { + using ComPtr d3D12ShaderReflection = default; + + Guid iidOfID3D12ShaderReflection = ID3D12ShaderReflection.IID_Guid; + + DxcBuffer dxcBuffer = default; + dxcBuffer.Ptr = dxcBlob->GetBufferPointer(); + dxcBuffer.Size = dxcBlob->GetBufferSize(); + + this.dxcUtils.Get()->CreateReflection( + &dxcBuffer, + &iidOfID3D12ShaderReflection, + (void**)d3D12ShaderReflection.GetAddressOf()).Assert(); + + const ulong doublePrecisionFlags = DirectX.D3D_SHADER_REQUIRES_DOUBLES | DirectX.D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS; + + return (d3D12ShaderReflection.Get()->GetRequiresFlags() & doublePrecisionFlags) != 0; + } + /// /// Throws an exception when a shader compilation fails. /// diff --git a/src/ComputeSharp.SourceGenerators/NativeMethods.txt b/src/ComputeSharp.SourceGenerators/NativeMethods.txt index 00f34480..1c482b3e 100644 --- a/src/ComputeSharp.SourceGenerators/NativeMethods.txt +++ b/src/ComputeSharp.SourceGenerators/NativeMethods.txt @@ -1,6 +1,9 @@ CLSID_DxcCompiler CLSID_DxcLibrary DxcCreateInstance +D3D_SHADER_REQUIRES_DOUBLES +D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS +ID3D12ShaderReflection IDxcCompiler3 IDxcUtils IDxcResult From aa127b8f095dba222dfa7d7ab201d739e79257b9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 02:57:43 +0100 Subject: [PATCH 4/8] Move FixupExceptionMessage to DxcShaderCompiler --- ...eShaderDescriptorGenerator.HlslBytecode.cs | 24 ++----------------- .../Dxc/DxcShaderCompiler.cs | 20 ++++++++++++++++ 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs index 2d44b94d..e78440aa 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Immutable; using System.ComponentModel; using System.Runtime.CompilerServices; -using System.Text.RegularExpressions; using System.Threading; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; @@ -78,11 +77,11 @@ partial class ComputeShaderDescriptorGenerator } catch (Win32Exception e) { - return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, FixupExceptionMessage(e.Message)); + return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, DxcShaderCompiler.FixupExceptionMessage(e.Message)); } catch (DxcCompilationException e) { - return new HlslBytecodeInfo.CompilerError(FixupExceptionMessage(e.Message)); + return new HlslBytecodeInfo.CompilerError(DxcShaderCompiler.FixupExceptionMessage(e.Message)); } } @@ -140,24 +139,5 @@ partial class ComputeShaderDescriptorGenerator diagnostics.Add(diagnostic); } } - - /// - /// Fixes up an exception message to improve the way it's displayed in VS. - /// - /// The input exception message. - /// The updated exception message. - private static string FixupExceptionMessage(string message) - { - // Add square brackets around error headers - message = Regex.Replace(message, @"^(error|warning):", static m => $"[{m.Groups[1].Value}]:", RegexOptions.Multiline); - - // Remove lines with notes - message = Regex.Replace(message, @"^note:.+", string.Empty, RegexOptions.Multiline); - - // Remove syntax error indicators - message = Regex.Replace(message, @"^ +\^", string.Empty, RegexOptions.Multiline); - - return message.NormalizeToSingleLine(); - } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs index 6b82a99f..f3cdf3f1 100644 --- a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs +++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; +using ComputeSharp.SourceGeneration.Extensions; using Windows.Win32; using Windows.Win32.Foundation; using Windows.Win32.Graphics.Direct3D.Dxc; @@ -274,6 +275,25 @@ internal sealed unsafe class DxcShaderCompiler return (d3D12ShaderReflection.Get()->GetRequiresFlags() & doublePrecisionFlags) != 0; } + /// + /// Fixes up an exception message to improve the way it's displayed in VS. + /// + /// The input exception message. + /// The updated exception message. + public static string FixupExceptionMessage(string message) + { + // Add square brackets around error headers + message = Regex.Replace(message, @"^(error|warning):", static m => $"[{m.Groups[1].Value}]:", RegexOptions.Multiline); + + // Remove lines with notes + message = Regex.Replace(message, @"^note:.+", string.Empty, RegexOptions.Multiline); + + // Remove syntax error indicators + message = Regex.Replace(message, @"^ +\^", string.Empty, RegexOptions.Multiline); + + return message.NormalizeToSingleLine(); + } + /// /// Throws an exception when a shader compilation fails. /// From 2c6eb178d5f8c9634fa2bbb90a658234619b4883 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 03:08:21 +0100 Subject: [PATCH 5/8] Add [RequiresDoublePrecisionSupport] diagnostics --- .../Diagnostics/DiagnosticDescriptors.cs | 10 ++--- .../AnalyzerReleases.Shipped.md | 2 + ...eShaderDescriptorGenerator.HlslBytecode.cs | 38 +++++++++++++++++++ .../ComputeShaderDescriptorGenerator.cs | 1 + .../Diagnostics/DiagnosticDescriptors.cs | 32 ++++++++++++++++ 5 files changed, 78 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 9d9f0d36..23ce21bf 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -1194,21 +1194,21 @@ partial class DiagnosticDescriptors /// /// Gets a for a shader missing [D2DRequiresDoublePrecisionSupport]. /// - /// Format: "The shader {0} requires double precision support, but it does not have the [D2DRequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in into that functionality)". + /// Format: "The shader {0} requires double precision support, but it does not have the [D2DRequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in to that functionality)". /// /// public static readonly DiagnosticDescriptor MissingD2DRequiresDoublePrecisionSupportAttribute = new( id: "CMPSD2D0080", title: "Missing [D2DRequiresDoublePrecisionSupport] attribute", - messageFormat: "The shader {0} requires double precision support, but it does not have the [D2DRequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in into that functionality)", + messageFormat: "The shader {0} requires double precision support, but it does not have the [D2DRequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in to that functionality)", category: "ComputeSharp.D2D1.Shaders", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, - description: "Shaders performing double precision operations must be annotated with [D2DRequiresDoublePrecisionSupport] to explicitly opt-in into that functionality.", + description: "Shaders performing double precision operations must be annotated with [D2DRequiresDoublePrecisionSupport] to explicitly opt-in to that functionality.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for a shader is unnecessarily using [UnnecessaryD2DRequiresDoublePrecisionSupportAttribute]. + /// Gets a for a shader is unnecessarily using [D2DRequiresDoublePrecisionSupport]. /// /// Format: "The shader {0} does not require double precision support, but it has the [D2DRequiresDoublePrecisionSupport] attribute on it (using the attribute is not needed if the shader is not performing any double precision operations)". /// @@ -1224,7 +1224,7 @@ partial class DiagnosticDescriptors helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); /// - /// Gets a for a shader is using [UnnecessaryD2DRequiresDoublePrecisionSupportAttribute] incorrectly. + /// Gets a for a shader is using [D2DRequiresDoublePrecisionSupport] incorrectly. /// /// Format: "The shader {0} has the [D2DRequiresDoublePrecisionSupport] attribute on it, but it is not precompiled, so validation for use of double precision operations cannot be performed". /// diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 0dbb22ff..b211839f 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -69,3 +69,5 @@ CMPS0060 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Ser CMPS0061 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0062 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0063 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0064 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0065 | ComputeSharp.Shaders | Warning | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs index e78440aa..ab84b2fe 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs @@ -139,5 +139,43 @@ partial class ComputeShaderDescriptorGenerator diagnostics.Add(diagnostic); } } + + /// + /// Gets the diagnostics for when double precision support is configured incorrectly. + /// + /// The input instance to process. + /// The source instance. + /// The collection of produced instances. + public static void GetDoublePrecisionSupportDiagnostics( + INamedTypeSymbol structDeclarationSymbol, + HlslBytecodeInfo info, + ImmutableArrayBuilder diagnostics) + { + // If we have no compiled HLSL bytecode, there is nothing more to do + if (info is not HlslBytecodeInfo.Success success) + { + return; + } + + bool hasD2DRequiresDoublePrecisionSupportAttribute = structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName( + "ComputeSharp.RequiresDoublePrecisionSupportAttribute", + out AttributeData? attributeData); + + // Check the two cases where diagnostics are necessary (same as the D2D generator) + if (!hasD2DRequiresDoublePrecisionSupportAttribute && success.RequiresDoublePrecisionSupport) + { + diagnostics.Add(DiagnosticInfo.Create( + MissingRequiresDoublePrecisionSupportAttribute, + structDeclarationSymbol, + structDeclarationSymbol)); + } + else if (hasD2DRequiresDoublePrecisionSupportAttribute && !success.RequiresDoublePrecisionSupport) + { + diagnostics.Add(DiagnosticInfo.Create( + UnnecessaryRequiresDoublePrecisionSupportAttribute, + attributeData!.GetLocation(), + structDeclarationSymbol)); + } + } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index baa69f59..c218dd6e 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -122,6 +122,7 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener token.ThrowIfCancellationRequested(); HlslBytecode.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics); + HlslBytecode.GetDoublePrecisionSupportDiagnostics(typeSymbol, hlslInfo, diagnostics); token.ThrowIfCancellationRequested(); diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 99aab81a..ce9a2f6b 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -901,4 +901,36 @@ partial class DiagnosticDescriptors isEnabledByDefault: true, description: "Methods from the Math and MathF types cannot be used in a shader, and equivalent APIs from the Hlsl type should be used instead.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader missing [RequiresDoublePrecisionSupport]. + /// + /// Format: "The shader {0} requires double precision support, but it does not have the [RequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in to that functionality)". + /// + /// + public static readonly DiagnosticDescriptor MissingRequiresDoublePrecisionSupportAttribute = new( + id: "CMPS0064", + title: "Missing [RequiresDoublePrecisionSupport] attribute", + messageFormat: "The shader {0} requires double precision support, but it does not have the [RequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in to that functionality)", + category: "ComputeSharp.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "Shaders performing double precision operations must be annotated with [RequiresDoublePrecisionSupport] to explicitly opt-in to that functionality.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader is unnecessarily using [RequiresDoublePrecisionSupportAttribute]. + /// + /// Format: "The shader {0} does not require double precision support, but it has the [RequiresDoublePrecisionSupport] attribute on it (using the attribute is not needed if the shader is not performing any double precision operations)". + /// + /// + public static readonly DiagnosticDescriptor UnnecessaryRequiresDoublePrecisionSupportAttribute = new( + id: "CMPS0065", + title: "Unnecessary [RequiresDoublePrecisionSupport] attribute", + messageFormat: "The shader {0} does not require double precision support, but it has the [RequiresDoublePrecisionSupport] attribute on it (using the attribute is not needed if the shader is not performing any double precision operations)", + category: "ComputeSharp.Shaders", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: "Shaders not performing any double precision operations should not be annotated with [RequiresDoublePrecisionSupport], as the attribute is not needed in that case.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } \ No newline at end of file From a98f53d874f24b463e95e137d2780c355536cbc6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 03:08:29 +0100 Subject: [PATCH 6/8] Add diagnostic tests for [RequiresDoublePrecisionSupport] --- .../DiagnosticsTests.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 680aa668..d59807d4 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -1639,6 +1639,57 @@ public class DiagnosticsTests VerifyGeneratedDiagnostics(source, "CMPS0046"); } + [TestMethod] + public void MissingRequiresDoublePrecisionSupportAttribute() + { + const string source = """ + using ComputeSharp; + + namespace MyNamespace; + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MyShader : IComputeShader + { + private readonly ReadWriteBuffer results; + private readonly float time; + + public void Execute() + { + results[ThreadIds.X] = (float)(Hlsl.Abs(time * 2.0)); + } + } + """; + + VerifyGeneratedDiagnostics(source, "CMPS0064"); + } + + [TestMethod] + public void UnnecessaryRequiresDoublePrecisionSupportAttribute() + { + const string source = """ + using ComputeSharp; + + namespace MyNamespace; + + [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [RequiresDoublePrecisionSupport] + [GeneratedComputeShaderDescriptor] + internal readonly partial struct MyShader : IComputeShader + { + private readonly ReadWriteBuffer results; + private readonly float time; + + public void Execute() + { + results[ThreadIds.X] = (float)(time * 2.0f); + } + } + """; + + VerifyGeneratedDiagnostics(source, "CMPS0065"); + } + /// /// Verifies the output of a source generator. /// From cea25fbd4d2ad3c66ad8fcc61f5670bdb52c2b36 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 03:11:29 +0100 Subject: [PATCH 7/8] Add [RequiresDoublePrecisionSupport] to test shaders --- tests/ComputeSharp.Tests/BufferTests.cs | 1 + tests/ComputeSharp.Tests/ShaderCompilerTests.cs | 1 + tests/ComputeSharp.Tests/ShaderRewriterTests.cs | 2 ++ 3 files changed, 4 insertions(+) diff --git a/tests/ComputeSharp.Tests/BufferTests.cs b/tests/ComputeSharp.Tests/BufferTests.cs index ba855867..938586ea 100644 --- a/tests/ComputeSharp.Tests/BufferTests.cs +++ b/tests/ComputeSharp.Tests/BufferTests.cs @@ -375,6 +375,7 @@ public partial class BufferTests [AutoConstructor] [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [RequiresDoublePrecisionSupport] [GeneratedComputeShaderDescriptor] public readonly partial struct DoublePrecisionSupportShader : IComputeShader { diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 8c507492..2b83b52a 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -361,6 +361,7 @@ namespace ComputeSharp.Tests [AutoConstructor] [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [RequiresDoublePrecisionSupport] [GeneratedComputeShaderDescriptor] public readonly partial struct DoublePrecisionSupportShader : IComputeShader { diff --git a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs index b7a90ac5..a5bc0500 100644 --- a/tests/ComputeSharp.Tests/ShaderRewriterTests.cs +++ b/tests/ComputeSharp.Tests/ShaderRewriterTests.cs @@ -52,6 +52,7 @@ public partial class ShaderRewriterTests [AutoConstructor] [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [RequiresDoublePrecisionSupport] [GeneratedComputeShaderDescriptor] internal readonly partial struct NanAndInfiniteShader : IComputeShader { @@ -622,6 +623,7 @@ public partial class ShaderRewriterTests [AutoConstructor] [ThreadGroupSize(DefaultThreadGroupSizes.X)] + [RequiresDoublePrecisionSupport] [GeneratedComputeShaderDescriptor] internal readonly partial struct DoubleConstantsInShaderConstantFieldsShader : IComputeShader { From e27b7e4379bb1dc35d1be03f8b63c25d91481495 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Dec 2023 12:22:50 +0100 Subject: [PATCH 8/8] Minor tweaks to DiagnosticInfo --- ...DPixelShaderDescriptorGenerator.HlslBytecode.cs | 7 +++++-- .../D2DPixelShaderSourceGenerator.Execute.cs | 9 +++++++-- .../Models/DiagnosticInfo.cs | 14 ++++++++++++-- ...omputeShaderDescriptorGenerator.HlslBytecode.cs | 7 +++++-- 4 files changed, 29 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs index 334bb349..210e2ee1 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs @@ -257,14 +257,17 @@ partial class D2DPixelShaderDescriptorGenerator diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithWin32Exception, structDeclarationSymbol, - [structDeclarationSymbol, win32Error.HResult, win32Error.Message]); + structDeclarationSymbol, + win32Error.HResult, + win32Error.Message); } else if (info is HlslBytecodeInfo.CompilerError fxcError) { diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithFxcCompilationException, structDeclarationSymbol, - [structDeclarationSymbol, fxcError.Message]); + structDeclarationSymbol, + fxcError.Message); } if (diagnostic is not null) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index 78ed7ef1..0de6514d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -140,14 +140,19 @@ partial class D2DPixelShaderSourceGenerator diagnostic = DiagnosticInfo.Create( D2DPixelShaderSourceCompilationFailedWithWin32Exception, methodSymbol, - [methodSymbol, methodSymbol.ContainingType, win32Error.HResult, win32Error.Message]); + methodSymbol, + methodSymbol.ContainingType, + win32Error.HResult, + win32Error.Message); } else if (info is HlslBytecodeInfo.CompilerError fxcError) { diagnostic = DiagnosticInfo.Create( D2DPixelShaderSourceCompilationFailedWithFxcCompilationException, methodSymbol, - [methodSymbol, methodSymbol.ContainingType, fxcError.Message]); + methodSymbol, + methodSymbol.ContainingType, + fxcError.Message); } if (diagnostic is not null) diff --git a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs index 72970bd5..c5bfaeca 100644 --- a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs @@ -42,7 +42,17 @@ internal sealed record DiagnosticInfo( /// A new instance with the specified parameters. public static DiagnosticInfo Create(DiagnosticDescriptor descriptor, Location? location, params object[] args) { - return new(descriptor, location?.SourceTree, location?.SourceSpan ?? default, args.Select(static arg => arg.ToString()).ToImmutableArray()); + // The returned DiagnosticInfo instances will be used inside incremental collections. Because of + // that, we pre-transform all arguments with ToString(), so they are guaranteed to be equatable + // from the start and not to keep compilations alive (if eg. they happen to be symbol objects). + EquatableArray textArgs = args.Select(static arg => arg.ToString()).ToImmutableArray(); + + if (location is null) + { + return new(descriptor, null, default, textArgs); + } + + return new(descriptor, location.SourceTree, location.SourceSpan, textArgs); } /// @@ -54,7 +64,7 @@ internal sealed record DiagnosticInfo( /// A new instance with the specified parameters. public static DiagnosticInfo Create(DiagnosticDescriptor descriptor, ISymbol symbol, params object[] args) { - return Create(descriptor, symbol.Locations.First(), args); + return Create(descriptor, symbol.Locations.FirstOrDefault(), args); } /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs index ab84b2fe..298bffbd 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs @@ -124,14 +124,17 @@ partial class ComputeShaderDescriptorGenerator diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithWin32Exception, structDeclarationSymbol, - [structDeclarationSymbol, win32Error.HResult, win32Error.Message]); + structDeclarationSymbol, + win32Error.HResult, + win32Error.Message); } else if (info is HlslBytecodeInfo.CompilerError dxcError) { diagnostic = DiagnosticInfo.Create( HlslBytecodeFailedWithDxcCompilationException, structDeclarationSymbol, - [structDeclarationSymbol, dxcError.Message]); + structDeclarationSymbol, + dxcError.Message); } if (diagnostic is not null)