From 3c7d5db340496e3aba73a49203065f11eb5da06b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 21 Oct 2023 01:27:15 +0200 Subject: [PATCH] Switch D3D12 generator to shared constant buffer logic --- ...haderDescriptorGenerator.ConstantBuffer.cs | 8 +- .../ConstantBufferSyntaxProcessor.cs | 16 ++-- ...haderDescriptorGenerator.ConstantBuffer.cs | 88 +++++++++++++++++++ ...torGenerator.DispatchDataLoading.Syntax.cs | 79 ----------------- .../ComputeShaderDescriptorGenerator.cs | 5 +- 5 files changed, 103 insertions(+), 93 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ConstantBuffer.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs index 2add6b86..449c9833 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs @@ -14,9 +14,9 @@ namespace ComputeSharp.D2D1.SourceGenerators; partial class D2DPixelShaderDescriptorGenerator { /// - /// A helper with all logic to generate the ConstantBuffer methods and additional types. + /// A helper with all logic to generate the constant buffer marshalling methods and additional types. /// - private static partial class ConstantBuffer + private static class ConstantBuffer { /// /// The collection of produced instances. @@ -31,10 +31,12 @@ partial class D2DPixelShaderDescriptorGenerator out int constantBufferSizeInBytes, out ImmutableArray fields) { + constantBufferSizeInBytes = 0; + ConstantBufferSyntaxProcessor.GetInfo( compilation, structDeclarationSymbol, - out constantBufferSizeInBytes, + ref constantBufferSizeInBytes, out fields); // The maximum size for a constant buffer is 64KB diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs index deaad4ee..3d24fa41 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs @@ -33,7 +33,7 @@ internal static partial class ConstantBufferSyntaxProcessor public static void GetInfo( Compilation compilation, ITypeSymbol structDeclarationSymbol, - out int constantBufferSizeInBytes, + ref int constantBufferSizeInBytes, out ImmutableArray fields) { // Helper method that uses boxes instead of ref-s (illegal in enumerators) @@ -41,7 +41,7 @@ internal static partial class ConstantBufferSyntaxProcessor Compilation compilation, ITypeSymbol currentTypeSymbol, ImmutableArray fieldPath, - ref int rawDataOffset, + ref int constantBufferSizeInBytes, ImmutableArrayBuilder fields) { bool isFirstField = true; @@ -71,7 +71,7 @@ internal static partial class ConstantBufferSyntaxProcessor // The first item in each nested struct needs to be aligned to 16 bytes if (isFirstField && fieldPath.Length > 0) { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + constantBufferSizeInBytes = AlignmentHelper.Pad(constantBufferSizeInBytes, 16); isFirstField = false; } @@ -80,7 +80,7 @@ internal static partial class ConstantBufferSyntaxProcessor { ImmutableArray nestedFieldPath = fieldPath.Add(new FieldPathPart.Leaf(fieldName, unspeakableName)); - fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref rawDataOffset)); + fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref constantBufferSizeInBytes)); } else if (fieldSymbol.Type.IsUnmanagedType) { @@ -88,14 +88,11 @@ internal static partial class ConstantBufferSyntaxProcessor FieldPathPart fieldPathPart = new FieldPathPart.Nested(fieldName, unspeakableName, nestedTypeName); // Custom struct type defined by the user - GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref rawDataOffset, fields); + GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref constantBufferSizeInBytes, fields); } } } - // Setup the resource and byte offsets for tracking - int rawDataOffset = 0; - using ImmutableArrayBuilder fieldBuilder = new(); // Traverse all shader fields and gather info, and update the tracking offsets @@ -103,10 +100,9 @@ internal static partial class ConstantBufferSyntaxProcessor compilation, structDeclarationSymbol, ImmutableArray.Empty, - ref rawDataOffset, + ref constantBufferSizeInBytes, fieldBuilder); - constantBufferSizeInBytes = rawDataOffset; fields = fieldBuilder.ToImmutable(); } diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ConstantBuffer.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ConstantBuffer.cs new file mode 100644 index 00000000..c3219549 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ConstantBuffer.cs @@ -0,0 +1,88 @@ +using System.Collections.Immutable; +using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators; + +/// +partial class ComputeShaderDescriptorGenerator +{ + /// + /// A helper with all logic to generate the constant buffer marshalling methods and additional types. + /// + private static class ConstantBuffer + { + /// + /// The collection of produced instances. + /// + /// + /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. + /// + /// + public static void GetInfo( + ImmutableArrayBuilder diagnostics, + Compilation compilation, + ITypeSymbol structDeclarationSymbol, + bool isPixelShaderLike, + out int constantBufferSizeInBytes, + out ImmutableArray fields) + { + // Setup the resource and byte offsets for tracking. Pixel shaders have only two + // implicitly captured int values, as they're always dispatched over a 2D texture. + constantBufferSizeInBytes = sizeof(int) * (isPixelShaderLike ? 2 : 3); + + ConstantBufferSyntaxProcessor.GetInfo( + compilation, + structDeclarationSymbol, + ref constantBufferSizeInBytes, + out fields); + + // After all the captured fields have been processed, ensure the reported byte size for + // 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(constantBufferSizeInBytes, sizeof(int)); + } + + /// + /// Writes the LoadConstantBuffer method. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteLoadConstantBufferSyntax(ShaderInfo info, IndentedTextWriter writer) + { + string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; + + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); + writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader, int x, int y, int z)"); + + using (writer.WriteBlock()) + { + // If there are no fields, just load an empty buffer + if (info.Fields.IsEmpty) + { + writer.WriteLine("loader.LoadConstantBuffer(default);"); + } + else + { + // Otherwise, pass a span into the marshalled native layout buffer. + // Also load the artificially created fields with dispatch data. + writer.WriteLine("global::ComputeSharp.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.Generated.ConstantBuffer buffer);"); + writer.WriteLine(); + writer.WriteLine("buffer.__x = x;"); + writer.WriteLine("buffer.__y = y;"); + writer.WriteLineIf(!info.IsPixelShaderLike, "buffer.__z = z;"); + writer.WriteLineIf(!info.IsPixelShaderLike); + writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.Generated.ConstantBuffer)));"); + } + } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs index ccdd6076..33736b41 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs @@ -1,7 +1,5 @@ -using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; namespace ComputeSharp.SourceGenerators; @@ -12,83 +10,6 @@ partial class ComputeShaderDescriptorGenerator /// partial class DispatchDataLoading { - /// - /// Writes the LoadConstantBuffer method. - /// - /// The input instance with gathered shader info. - /// The instance to write into. - public static void WriteLoadConstantBufferSyntax(ShaderInfo info, IndentedTextWriter writer) - { - string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; - - writer.WriteLine("/// "); - writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); - writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader, int x, int y, int z)"); - - using (writer.WriteBlock()) - { - writer.WriteLine($"global::System.Span span = stackalloc byte[{info.ConstantBufferSizeInBytes}];"); - - // Append the statements for the dispatch ranges - 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(!info.IsPixelShaderLike, "global::System.Runtime.CompilerServices.Unsafe.As(ref span[8]) = (uint)z;"); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in info.Fields) - { - switch (fieldInfo) - { - 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 span[{primitive.Offset}]) = " + - $"(global::ComputeSharp.Bool)shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};"); - 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 span[{primitive.Offset}]) = " + - $"shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};"); - break; - - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; - string rowLocalName = $"__{string.Join("_", matrix.FieldPath.Select(static path => path.Name))}__row0"; - - // Declare a local to index into individual rows. This will generate: - // - // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( - // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); - writer.WriteLine( - $"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(" + - $"ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in shader.{string.Join(".", matrix.FieldPath.Select(static path => path.Name))}));"); - - // Generate the loading code for each individual row, with proper alignment. - // This will result in the following (assuming Float2x3 m): - // - // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); - for (int j = 0; j < matrix.Rows; j++) - { - writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{matrix.Offsets[j]}]) = " + - $"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});"); - } - - break; - } - } - - // Load the prepared buffer - writer.WriteLine("loader.LoadConstantBuffer(span);"); - } - } - /// /// Writes the LoadGraphicsResources method. /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index 7de05e5b..34906171 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -1,8 +1,10 @@ using System.Collections.Immutable; +using System.ComponentModel; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -159,12 +161,13 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener declaredMembers.Add(ResourceDescriptorRanges.WriteSyntax); declaredMembers.Add(HlslSource.WriteSyntax); declaredMembers.Add(HlslBytecode.WriteHlslBytecodeSyntax); - declaredMembers.Add(DispatchDataLoading.WriteLoadConstantBufferSyntax); + declaredMembers.Add(ConstantBuffer.WriteLoadConstantBufferSyntax); declaredMembers.Add(DispatchDataLoading.WriteLoadGraphicsResourcesSyntax); using ImmutableArrayBuilder> additionalTypes = new(); using ImmutableHashSetBuilder usingDirectives = new(); + ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.OneWay, item, additionalTypes, usingDirectives); ResourceDescriptorRanges.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives); HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);