Switch D3D12 generator to shared constant buffer logic

このコミットが含まれているのは:
Sergio Pedri committed 2023-11-20 21:11:44 +01:00
1 親 0a7dbb3cfb
コミット 3c7d5db340
5ファイル変更
+103 -93

検索条件に一致するファイルはありません

@@ -14,9 +14,9 @@ namespace ComputeSharp.D2D1.SourceGenerators;
partial class D2DPixelShaderDescriptorGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>ConstantBuffer</c> methods and additional types.
/// A helper with all logic to generate the constant buffer marshalling methods and additional types.
/// </summary>
private static partial class ConstantBuffer
private static class ConstantBuffer
{
/// <inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo"/>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
@@ -31,10 +31,12 @@ partial class D2DPixelShaderDescriptorGenerator
out int constantBufferSizeInBytes,
out ImmutableArray<FieldInfo> fields)
{
constantBufferSizeInBytes = 0;
ConstantBufferSyntaxProcessor.GetInfo(
compilation,
structDeclarationSymbol,
out constantBufferSizeInBytes,
ref constantBufferSizeInBytes,
out fields);
// The maximum size for a constant buffer is 64KB
+6 -10
ファイルの表示
@@ -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<FieldInfo> 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<FieldPathPart> fieldPath,
ref int rawDataOffset,
ref int constantBufferSizeInBytes,
ImmutableArrayBuilder<FieldInfo> 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<FieldPathPart> 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<FieldInfo> 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<FieldPathPart>.Empty,
ref rawDataOffset,
ref constantBufferSizeInBytes,
fieldBuilder);
constantBufferSizeInBytes = rawDataOffset;
fields = fieldBuilder.ToImmutable();
}
@@ -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;
/// <inheritdoc/>
partial class ComputeShaderDescriptorGenerator
{
/// <summary>
/// A helper with all logic to generate the constant buffer marshalling methods and additional types.
/// </summary>
private static class ConstantBuffer
{
/// <inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo"/>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="compilation"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='compilation']/node()"/></param>
/// <param name="structDeclarationSymbol"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='structDeclarationSymbol']/node()"/></param>
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="constantBufferSizeInBytes"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='constantBufferSizeInBytes']/node()"/></param>
/// <param name="fields"><inheritdoc cref="ConstantBufferSyntaxProcessor.GetInfo" path="/param[@name='fields']/node()"/></param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
ITypeSymbol structDeclarationSymbol,
bool isPixelShaderLike,
out int constantBufferSizeInBytes,
out ImmutableArray<FieldInfo> 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));
}
/// <summary>
/// Writes the <c>LoadConstantBuffer</c> method.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteLoadConstantBufferSyntax(ShaderInfo info, IndentedTextWriter writer)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(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<byte>(&buffer, sizeof(global::ComputeSharp.Generated.ConstantBuffer)));");
}
}
}
}
}
@@ -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
/// <inheritdoc/>
partial class DispatchDataLoading
{
/// <summary>
/// Writes the <c>LoadConstantBuffer</c> method.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteLoadConstantBufferSyntax(ShaderInfo info, IndentedTextWriter writer)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer<TLoader>(in {typeName} shader, ref TLoader loader, int x, int y, int z)");
using (writer.WriteBlock())
{
writer.WriteLine($"global::System.Span<byte> span = stackalloc byte[{info.ConstantBufferSizeInBytes}];");
// Append the statements for the dispatch ranges
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref span[0]) = (uint)x;");
writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(ref span[4]) = (uint)y;");
writer.WriteLineIf(!info.IsPixelShaderLike, "global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(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<byte, global::ComputeSharp.Bool>(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<byte, global::{primitive.TypeName}>(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 <ROW_TYPE> <ROW_NAME> = ref global::System.Runtime.CompilerServices.Unsafe.As<global::<TYPE_NAME>, <ROW_TYPE_NAME>>(
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in <FIELD_PATH>));
writer.WriteLine(
$"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(" +
$"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<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(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<uint, global::ComputeSharp.Float3>(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<byte, {rowTypeName}>(ref span[{matrix.Offsets[j]}]) = " +
$"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});");
}
break;
}
}
// Load the prepared buffer
writer.WriteLine("loader.LoadConstantBuffer(span);");
}
}
/// <summary>
/// Writes the <c>LoadGraphicsResources</c> method.
/// </summary>
+4 -1
ファイルの表示
@@ -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<IndentedTextWriter.Callback<ShaderInfo>> additionalTypes = new();
using ImmutableHashSetBuilder<string> usingDirectives = new();
ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.OneWay, item, additionalTypes, usingDirectives);
ResourceDescriptorRanges.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives);
HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);