From 471d87cd02cc1738e49cfbddd6d2b28afd19d433 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 15 Oct 2023 18:54:12 +0200 Subject: [PATCH] Update D3D12 generator for new loading methods --- ...tor.CreateLoadDispatchDataMethod.Syntax.cs | 59 +++++++++++-------- ...rGenerator.CreateLoadDispatchDataMethod.cs | 8 +-- ...erator.CreateLoadDispatchMetadataMethod.cs | 2 - .../IShaderGenerator.cs | 8 +-- .../Models/ShaderInfo.cs | 2 +- .../Core/Interfaces/__Internals/IShader.cs | 2 +- .../Shaders/Loading/PipelineDataLoader{T}.cs | 5 +- 7 files changed, 50 insertions(+), 36 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index a6a3cd5b..652ee3ba 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -11,53 +11,43 @@ partial class IShaderGenerator partial class LoadDispatchData { /// - /// Writes the LoadDispatchData method. + /// Writes the LoadConstantBuffer method. /// /// The input instance with gathered shader info. /// The instance to write into. - public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) + public static void WriteLoadConstantBufferSyntax(ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine("/// "); writer.WriteGeneratedAttributes(GeneratorName); writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); - writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)"); + writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadConstantBuffer(ref TLoader loader, int x, int y, int z)"); using (writer.WriteBlock()) { - writer.WriteLine($"global::System.Span span0 = stackalloc uint[{info.ConstantBufferSizeInBytes}];"); - writer.WriteLineIf($"global::System.Span span1 = stackalloc ulong[{info.ResourceCount}];", info.ResourceCount > 0); - writer.WriteLine("ref uint r0 = ref span0[0];"); - writer.WriteLineIf("ref ulong r1 = ref span1[0];", info.ResourceCount > 0); + writer.WriteLine($"global::System.Span span = stackalloc byte[{info.ConstantBufferSizeInBytes}];"); // Append the statements for the dispatch ranges - writer.WriteLine("span0[0] = (uint)x;"); - writer.WriteLine("span0[1] = (uint)y;"); - writer.WriteLineIf("span0[2] = (uint)z;", !info.IsPixelShaderLike); + writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As(ref span[0]) = (uint)x;"); + writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As(ref span[4]) = (uint)y;"); + writer.WriteLineIf("global::System.Runtime.CompilerServices.Unsafe.As(ref span[8]) = (uint)z;", !info.IsPixelShaderLike); // Generate loading statements for each captured field foreach (FieldInfo fieldInfo in info.Fields) { switch (fieldInfo) { - case FieldInfo.Resource resource: - - // Validate the resource and get a handle for it - writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset}) = " + - $"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device);"); - break; case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: // Read a boolean value and cast it to Bool first, which will apply the correct size expansion writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset})) = " + + $"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{primitive.Offset}]) = " + $"(global::ComputeSharp.Bool){string.Join(".", primitive.FieldPath)};"); break; case FieldInfo.Primitive primitive: // Read a primitive value and serialize it into the target buffer writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset})) = " + + $"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{primitive.Offset}]) = " + $"{string.Join(".", primitive.FieldPath)};"); break; @@ -82,7 +72,7 @@ partial class IShaderGenerator for (int j = 0; j < matrix.Rows; j++) { writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]})) = " + + $"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{matrix.Offsets[j]}]) = " + $"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});"); } @@ -90,9 +80,32 @@ partial class IShaderGenerator } } - // Load the prepared buffers - writer.WriteLine("loader.LoadCapturedValues(span0);"); - writer.WriteLineIf("loader.LoadCapturedResources(span1);", info.ResourceCount > 0); + // Load the prepared buffer + writer.WriteLine("loader.LoadConstantBuffer(span);"); + } + } + + /// + /// Writes the LoadGraphicsResources method. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteLoadGraphicsResourcesSyntax(ShaderInfo info, IndentedTextWriter writer) + { + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadGraphicsResources(ref TLoader loader)"); + + using (writer.WriteBlock()) + { + // Generate loading statements for each captured resource + foreach (FieldInfo fieldInfo in info.Fields) + { + if (fieldInfo is FieldInfo.Resource resource) + { + writer.WriteLine($"loader.LoadGraphicsResource({resource.FieldName}, {resource.Offset});"); + } + } } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index a026863c..6048c79b 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -27,8 +27,8 @@ partial class IShaderGenerator /// /// The collection of produced instances. /// The current shader type being explored. - /// The size of the shader constant buffer. /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. + /// The size of the shader constant buffer. /// The total number of captured resources in the shader. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( @@ -108,7 +108,7 @@ partial class IShaderGenerator // the local variables is padded to a multiple of a 32 bit value. This is necessary to // enable loading all the dispatch data after reinterpreting it to a sequence of values // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. - constantBufferSizeInBytes = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int); + constantBufferSizeInBytes = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)); // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. // Loaded values in the root signature have the following costs: @@ -118,9 +118,9 @@ partial class IShaderGenerator // 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 rootSignatureDwordSize = constantBufferSizeInBytes + resourceCount; + int root32BitConstantCount = (constantBufferSizeInBytes / sizeof(int)) + resourceCount; - if (rootSignatureDwordSize > 64) + if (root32BitConstantCount > 64) { diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 4e448bdc..55741a13 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -16,13 +16,11 @@ partial class IShaderGenerator /// /// Gets the data related to the shader metadata for a given shader type. /// - /// The total number of needed 32 bit constants in the shader root signature. /// Indicates whether the current shader uses an implicit texture. /// Whether the static sampler is used by the shader. /// The sequence of captured fields for the shader. /// The metadata info for the shader. public static ImmutableArray GetInfo( - int root32BitConstantCount, bool isImplicitTextureUsed, bool isSamplerUsed, ImmutableArray capturedFields) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index 27f554a0..f1d5f259 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -59,7 +59,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator diagnostics, typeSymbol, isPixelShaderLike, - out int root32BitConstantCount, + out int constantBufferSizeInBytes, out int resourceCount); token.ThrowIfCancellationRequested(); @@ -92,7 +92,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator // GetDispatchMetadata() info ImmutableArray resourceDescriptors = LoadDispatchMetadata.GetInfo( - root32BitConstantCount, isImplicitTextureUsed, isSamplerUsed, fieldInfos); @@ -123,7 +122,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator ThreadsZ: threadsZ, IsPixelShaderLike: isPixelShaderLike, IsSamplerUsed: isSamplerUsed, - ConstantBufferSizeInBytes: root32BitConstantCount, + ConstantBufferSizeInBytes: constantBufferSizeInBytes, ResourceCount: resourceCount, Fields: fieldInfos, ResourceDescriptors: resourceDescriptors, @@ -153,7 +152,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator declaredMembers.Add(LoadDispatchMetadata.WriteSyntax); declaredMembers.Add(BuildHlslSource.WriteSyntax); declaredMembers.Add(LoadBytecode.WriteHlslBytecodeSyntax); - declaredMembers.Add(LoadDispatchData.WriteSyntax); + declaredMembers.Add(LoadDispatchData.WriteLoadConstantBufferSyntax); + declaredMembers.Add(LoadDispatchData.WriteLoadGraphicsResourcesSyntax); using ImmutableArrayBuilder> additionalTypes = new(); using ImmutableHashSetBuilder usingDirectives = new(); diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs index 70370257..4cf56167 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs @@ -12,7 +12,7 @@ namespace ComputeSharp.SourceGenerators.Models; /// The thread ids value for the Z axis. /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. /// Whether or not the static sampler is used. -/// /// The size of the shader constant buffer. +/// The size of the shader constant buffer. /// The total number of captured resources in the shader. /// The description on shader instance fields. /// The sequence of resource descriptors for the shader. diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs index 859829ed..1669dcc5 100644 --- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs +++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs @@ -32,7 +32,7 @@ public interface IShader /// /// Constant buffer data is bound to shaders via 32 bit root constants, and loaded before dispatching via /// ID3D12GraphicsCommandList::SetComputeRoot32BitConstants, - /// so the size must be a multiple of 4. + /// so the size must be a multiple of the size of a DWORD value (ie. 4 bytes). /// int ConstantBufferSize { get; } diff --git a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs index aa24d6ff..3366a4d6 100644 --- a/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Loading/PipelineDataLoader{T}.cs @@ -96,9 +96,12 @@ internal static unsafe class PipelineDataLoader d3D12DescriptorRange.OffsetInDescriptorsFromTableStart = D3D12.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; } + // Calculate the actual size of the constant buffer in DWORD values + int root32BitConstantCount = shader.ConstantBufferSize / sizeof(int); + // Create the D3D12 root signature *d3D12RootSignature = d3D12Device->CreateRootSignature( - shader.ConstantBufferSize, + root32BitConstantCount, d3D12DescriptorRanges, shader.IsStaticSamplerRequired).Get();