Merge pull request #614 from Sergio0694/dev/indented-text-writer2

Rewrite D3D12 generator to use indented writer, dynamic cache, unified pipeline
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-10-14 01:43:01 +02:00
コミット 9605be3715
31ファイル変更
+447 -1023

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

@@ -2,6 +2,7 @@ using System.Linq;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1.SourceGenerators;
@@ -148,7 +148,7 @@ partial class D2DPixelShaderDescriptorGenerator
/// </summary>
/// <param name="key">The <see cref="HlslBytecodeInfoKey"/> instance for the shader to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns></returns>
/// <returns>The <see cref="HlslBytecodeInfo"/> instance for the current shader.</returns>
public static HlslBytecodeInfo GetInfo(ref HlslBytecodeInfoKey key, CancellationToken token)
{
static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token)
@@ -188,7 +188,7 @@ partial class D2DPixelShaderDescriptorGenerator
}
catch (FxcCompilationException e)
{
return new HlslBytecodeInfo.FxcError(D3DCompiler.PrettifyFxcErrorMessage(e.Message));
return new HlslBytecodeInfo.CompilerError(D3DCompiler.PrettifyFxcErrorMessage(e.Message));
}
}
@@ -218,7 +218,7 @@ partial class D2DPixelShaderDescriptorGenerator
structDeclarationSymbol,
new object[] { structDeclarationSymbol, win32Error.HResult, win32Error.Message });
}
else if (info is HlslBytecodeInfo.FxcError fxcError)
else if (info is HlslBytecodeInfo.CompilerError fxcError)
{
diagnostic = DiagnosticInfo.Create(
EmbeddedBytecodeFailedWithFxcCompilationException,
+1 -1
ファイルの表示
@@ -142,7 +142,7 @@ partial class D2DPixelShaderSourceGenerator
methodSymbol,
new object[] { methodSymbol, methodSymbol.ContainingType, win32Error.HResult, win32Error.Message });
}
else if (info is HlslBytecodeInfo.FxcError fxcError)
else if (info is HlslBytecodeInfo.CompilerError fxcError)
{
diagnostic = DiagnosticInfo.Create(
D2DPixelShaderSourceCompilationFailedWithFxcCompilationException,
+1 -1
ファイルの表示
@@ -14,7 +14,6 @@
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SyntaxNodeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SemanticModelProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SyntaxFormattingHelper.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SyntaxTokenHelper.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownFields.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownKeywords.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownMethods.cs" />
@@ -22,6 +21,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownProperties.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownSizes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Mappings\HlslKnownTypes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\HlslBytecodeInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\HlslSourceRewriter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\HlslSourceRewriter.Diagnostics.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxRewriters\ShaderSourceRewriter.cs" />
-24
ファイルの表示
@@ -91,28 +91,4 @@ internal static class SyntaxFormattingHelper
span = span.Slice(6);
}
}
/// <summary>
/// Creates a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given content.
/// </summary>
/// <param name="bytecode">The input byte content to serialize.</param>
/// <returns>A formatted <see cref="string"/> with the specified data.</returns>
/// <remarks>
/// This function will produce raw byte initialization expressions, such as:
/// <c>[1, 2, 3, 4, 5]</c> => <c>0x01, 0x02, 0x03, 0x04, 0x05</c>.
/// </remarks>
public static string BuildByteArrayInitializationExpressionString(ReadOnlySpan<byte> bytecode)
{
using ImmutableArrayBuilder<char> builder = new();
builder.AddRange(FormattedBytes[bytecode[0]].AsSpan());
foreach (byte b in bytecode.Slice(1))
{
builder.AddRange(", ".AsSpan());
builder.AddRange(FormattedBytes[b].AsSpan());
}
return builder.ToString();
}
}
-33
ファイルの表示
@@ -1,33 +0,0 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGeneration.Helpers;
/// <summary>
/// Helpers to create and work with <see cref="SyntaxToken"/>-s.
/// </summary>
internal static class SyntaxTokenHelper
{
/// <summary>
/// Creates a <see cref="SyntaxToken"/> representing a raw multiline string literal with the given text.
/// </summary>
/// <param name="text">The text to use for the created raw multiline string literal token.</param>
/// <param name="indentationLevel">The current indentation level to use.</param>
/// <returns>A <see cref="SyntaxToken"/> representing a raw multiline string literal with the value of <paramref name="text"/>.</returns>
public static SyntaxToken CreateRawMultilineStringLiteral(string text, int indentationLevel)
{
// Create a token to represent the raw multiline string literal expression. An extra newline and indentation
// has to be added to the raw text when there is no trailing newline, as not doing so would otherwise case
// the terminating """ token to fall on the same line, which is invalid syntax. This is only needed to make
// the code valid, as the actual literal context of the string is not affected and remains the same.
string indentation = new(' ', 4 * indentationLevel);
return Token(
TriviaList(),
SyntaxKind.MultiLineRawStringLiteralToken,
$"\"\"\"\n{indentation}{text.Replace("\n", $"\n{indentation}")}{(text.EndsWith("\n") ? "" : $"\n{indentation}")}\"\"\"",
text,
TriviaList());
}
}
@@ -1,6 +1,6 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
namespace ComputeSharp.SourceGeneration.Models;
/// <summary>
/// A model representing info on compiled HLSL bytecode, if available.
@@ -21,10 +21,10 @@ internal abstract record HlslBytecodeInfo
public sealed record Win32Error(int HResult, string Message) : HlslBytecodeInfo;
/// <summary>
/// An HLSL shader that failed to compile due to an FXC compiler error.
/// An HLSL shader that failed to compile due to a compiler error.
/// </summary>
/// <param name="Message">The error message from compiling the shader.</param>
public sealed record FxcError(string Message) : HlslBytecodeInfo;
public sealed record CompilerError(string Message) : HlslBytecodeInfo;
/// <summary>
/// No HLSL bytecode is available (ie. compilation was not requested or some other error was detected).
-1
ファイルの表示
@@ -26,7 +26,6 @@
<Compile Include="$(MSBuildThisFileDirectory)Helpers\ImmutableArrayBuilder{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\IndentedTextWriter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\ObjectPool{T}.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\DeferredDiagnosticInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\DiagnosticInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\HierarchyInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\TypeInfo.cs" />
-42
ファイルの表示
@@ -55,46 +55,4 @@ internal static class CompilationExtensions
{
return compilation.Options is CSharpCompilationOptions { AllowUnsafe: true };
}
/// <summary>
/// <para>
/// Checks whether or not a type with a specified metadata name is accessible from a given <see cref="Compilation"/> instance.
/// </para>
/// <para>
/// This method enumerates candidate type symbols to find a match in the following order:
/// <list type="number">
/// <item><description>
/// If only one type with the given name is found within the compilation and its referenced assemblies, check its accessibility.
/// </description></item>
/// <item><description>
/// If the current <paramref name="compilation"/> defines the symbol, check its accessibility.
/// </description></item>
/// <item><description>
/// Otherwise, check whether the type exists and is accessible from any of the referenced assemblies.
/// </description></item>
/// </list>
/// </para>
/// </summary>
/// <param name="compilation">The <see cref="Compilation"/> to consider for analysis.</param>
/// <param name="fullyQualifiedMetadataName">The fully-qualified metadata type name to find.</param>
/// <returns>Whether a type with the specified metadata name can be accessed from the given compilation.</returns>
public static bool HasAccessibleTypeWithMetadataName(this Compilation compilation, string fullyQualifiedMetadataName)
{
// If there is only a single matching symbol, check its accessibility
if (compilation.GetTypeByMetadataName(fullyQualifiedMetadataName) is INamedTypeSymbol typeSymbol)
{
return compilation.IsSymbolAccessibleWithin(typeSymbol, compilation.Assembly);
}
// Otherwise, check all available types
foreach (INamedTypeSymbol currentTypeSymbol in compilation.GetTypesByMetadataName(fullyQualifiedMetadataName))
{
if (compilation.IsSymbolAccessibleWithin(currentTypeSymbol, compilation.Assembly))
{
return true;
}
}
return false;
}
}
-10
ファイルの表示
@@ -41,16 +41,6 @@ internal static class DiagnosticsExtensions
diagnostics.Add(DiagnosticInfo.Create(descriptor, node, args));
}
/// <summary>
/// Registers an output node into an <see cref="IncrementalGeneratorInitializationContext"/> to output diagnostics.
/// </summary>
/// <param name="context">The input <see cref="IncrementalGeneratorInitializationContext"/> instance.</param>
/// <param name="diagnostics">The input <see cref="IncrementalValuesProvider{TValues}"/> sequence of diagnostics.</param>
public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider<DiagnosticInfo> diagnostics)
{
context.RegisterSourceOutput(diagnostics, static (context, diagnostic) => context.ReportDiagnostic(diagnostic.ToDiagnostic()));
}
/// <summary>
/// Registers an output node into an <see cref="IncrementalGeneratorInitializationContext"/> to output diagnostics.
/// </summary>
+32
ファイルの表示
@@ -1,4 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGeneration.Extensions;
@@ -52,6 +53,37 @@ internal static class IndentedTextWriterExtensions
}
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="content">The content to write.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(this IndentedTextWriter writer, string content, bool condition)
{
if (condition)
{
writer.WriteLine(content);
}
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="handler">The interpolated string handler with content to write.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(
this IndentedTextWriter writer,
[InterpolatedStringHandlerArgument(nameof(writer))] ref IndentedTextWriter.WriteInterpolatedStringHandler handler,
bool condition)
{
if (condition)
{
writer.WriteLine(ref handler);
}
}
/// <summary>
/// Writes a series of members separated by one line between each of them.
/// </summary>
-25
ファイルの表示
@@ -1,25 +0,0 @@
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGeneration.Models;
/// <summary>
/// A model for a serializeable diagnostic info to be reconstructed later in a pipeline.
/// </summary>
/// <param name="Descriptor">The wrapped <see cref="DiagnosticDescriptor"/> instance.</param>
/// <param name="Arguments">The diagnostic arguments.</param>
internal sealed record DeferredDiagnosticInfo(DiagnosticDescriptor Descriptor, EquatableArray<string> Arguments)
{
/// <summary>
/// Creates a new <see cref="DeferredDiagnosticInfo"/> instance with the specified parameters.
/// </summary>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
/// <returns>A new <see cref="DeferredDiagnosticInfo"/> instance with the specified parameters.</returns>
public static DeferredDiagnosticInfo Create(DiagnosticDescriptor descriptor, params object[] args)
{
return new(descriptor, args.Select(static arg => arg.ToString()).ToImmutableArray());
}
}
+5 -1
ファイルの表示
@@ -13,7 +13,11 @@ namespace ComputeSharp.SourceGeneration.Models;
/// <param name="SyntaxTree">The tree to use as location for the diagnostic, if available.</param>
/// <param name="TextSpan">The span to use as location for the diagnostic.</param>
/// <param name="Arguments">The diagnostic arguments.</param>
internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, SyntaxTree? SyntaxTree, TextSpan TextSpan, EquatableArray<string> Arguments)
internal sealed record DiagnosticInfo(
DiagnosticDescriptor Descriptor,
SyntaxTree? SyntaxTree,
TextSpan TextSpan,
EquatableArray<string> Arguments)
{
/// <summary>
/// Creates a new <see cref="Diagnostic"/> instance with the state from this model.
+17 -34
ファイルの表示
@@ -1,12 +1,6 @@
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -17,36 +11,25 @@ partial class IShaderGenerator
partial class BuildHlslSource
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.
/// Writes the <c>BuildHlslSource</c> method.
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth)
/// <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 WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
// The indentation level is the current depth + 2 (the method, and the return expression)
SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSourceInfo.HlslSource, hierarchyDepth + 2);
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)");
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)
// {
// hlslSource = <HLSL_SOURCE>;
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("BuildHlslSource"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword))))
.WithBody(Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("hlslSource"),
LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression)))));
using (writer.WriteBlock())
{
writer.WriteLine("hlslSource =");
writer.IncreaseIndent();
writer.WriteLine("\"\"\"");
writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true);
writer.WriteLine("\"\"\";");
writer.DecreaseIndent();
}
}
}
}
+29 -27
ファイルの表示
@@ -7,7 +7,6 @@ using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Mappings;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGeneration.SyntaxRewriters;
using ComputeSharp.SourceGenerators.Models;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
@@ -32,16 +31,23 @@ partial class IShaderGenerator
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="threadIds">The info on the shader thread count size to use.</param>
/// <param name="threadsX">The thread ids value for the X axis.</param>
/// <param name="threadsY">The thread ids value for the Y axis.</param>
/// <param name="threadsZ">The thread ids value for the Z axis.</param>
/// <param name="isImplicitTextureUsed">Indicates whether the current shader uses an implicit texture.</param>
/// <returns>The resulting info on the processed shader.</returns>
public static HlslShaderSourceInfo GetInfo(
/// <param name="isSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="hlslSource">The resulting HLSL source for the current shader.</param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
ThreadIdsInfo threadIds,
out bool isImplicitTextureUsed)
int threadsX,
int threadsY,
int threadsZ,
out bool isImplicitTextureUsed,
out bool isSamplerUsed,
out string hlslSource)
{
// Detect invalid properties
DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol);
@@ -65,7 +71,7 @@ partial class IShaderGenerator
string? implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
(ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, ImmutableArray<(string Name, string HlslType)> valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader);
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes);
(string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, bool isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader);
(string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader);
(string, string)? implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions);
@@ -77,8 +83,10 @@ partial class IShaderGenerator
isImplicitTextureUsed = implicitTextureType is not null;
// Get the HLSL source data with the intermediate info
return GetHlslSourceInfo(
threadIds,
hlslSource = GetHlslSourceInfo(
threadsX,
threadsY,
threadsZ,
definedConstants,
declaredTypes,
resourceFields,
@@ -544,7 +552,9 @@ partial class IShaderGenerator
/// <summary>
/// Produces the series of statements to build the current HLSL source.
/// </summary>
/// <param name="threadIds">The info on the shader thread count size to use.</param>
/// <param name="threadsX">The thread ids value for the X axis.</param>
/// <param name="threadsY">The thread ids value for the Y axis.</param>
/// <param name="threadsZ">The thread ids value for the Z axis.</param>
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="resourceFields">The sequence of resource instance fields for the current shader.</param>
@@ -556,9 +566,11 @@ partial class IShaderGenerator
/// <param name="implicitTextureType">The type of the implicit target texture, if present.</param>
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
/// <param name="executeMethod">The body of the entry point of the shader.</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static HlslShaderSourceInfo GetHlslSourceInfo(
ThreadIdsInfo threadIds,
/// <returns>The HLSL source for the current shader.</returns>
private static string GetHlslSourceInfo(
int threadsX,
int threadsY,
int threadsZ,
ImmutableArray<(string Name, string Value)> definedConstants,
ImmutableArray<(string Name, string Definition)> declaredTypes,
ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields,
@@ -578,11 +590,6 @@ partial class IShaderGenerator
hlslBuilder.Add('\n');
}
void AppendLine(string text)
{
hlslBuilder.AddRange(text.AsSpan());
}
void AppendLineAndLF(string text)
{
hlslBuilder.AddRange(text.AsSpan());
@@ -613,12 +620,9 @@ partial class IShaderGenerator
// Group size constants
AppendLF();
AppendLine("#define __GroupSize__get_X ");
AppendLineAndLF(threadIds.X.ToString());
AppendLine("#define __GroupSize__get_Y ");
AppendLineAndLF(threadIds.Y.ToString());
AppendLine("#define __GroupSize__get_Z ");
AppendLineAndLF(threadIds.Z.ToString());
AppendLineAndLF($"#define __GroupSize__get_X {threadsX}");
AppendLineAndLF($"#define __GroupSize__get_Y {threadsY}");
AppendLineAndLF($"#define __GroupSize__get_Z {threadsZ}");
// Define declarations
foreach ((string name, string value) in definedConstants)
@@ -740,9 +744,7 @@ partial class IShaderGenerator
AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
AppendLineAndLF(executeMethod);
string hlslSource = FlushText();
return new(hlslSource, isSamplerUsed);
return FlushText();
}
}
}
+29 -119
ファイルの表示
@@ -1,15 +1,7 @@
using System;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -20,120 +12,38 @@ partial class IShaderGenerator
partial class LoadBytecode
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// Writes the <c>LoadBytecode</c> method.
/// </summary>
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func<SyntaxNode, SourceText> fixup)
/// <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 WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode<TLoader>(ref TLoader loader, int threadsX, int threadsY, int threadsZ)");
if (bytecodeLiterals is not null)
using (writer.WriteBlock())
{
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
// If there is no HLSL bytecode, there's nothing left to do
if (info.HlslInfo is not HlslBytecodeInfo.Success success)
{
return;
}
// Check that the [numthreads] values match
writer.WriteLine($"if (threadsX == {info.ThreadsX} && threadsY == {info.ThreadsY} && threadsZ == {info.ThreadsZ})");
using (writer.WriteBlock())
{
writer.Write("global::System.ReadOnlySpan<byte> bytecode = new byte[] { ");
SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(success.Bytecode.AsSpan(), writer);
writer.WriteLine(" };");
writer.WriteLine();
writer.WriteLine("loader.LoadEmbeddedBytecode(bytecode);");
}
}
else
{
fixup = static tree => tree.GetText(Encoding.UTF8);
}
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode<TLoader>(ref TLoader loader, int threadsX, int threadsY, int threadsZ)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadBytecode"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TLoader")),
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(block);
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// </summary>
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
{
if (bytecodeInfo.Bytecode.IsEmpty)
{
bytecodeLiterals = null;
// Faulting path
return Block();
}
bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
// This code produces a branch as follows:
//
// if (threadsX == <X> && threadsY == <Y> && threadsZ == <Z>)
// {
// global::System.ReadOnlySpan<byte> bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
// loader.LoadEmbeddedBytecode(bytecode);
// }
//
// Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
// is created by the generator. This greatly speeds up the code generation, as it avoids
// having to create/parse tens of thousands of literal expression nodes for every shader.
IfStatementSyntax embeddedBranch =
IfStatement(
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsX"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsY"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsZ"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))),
Block(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.ReadOnlySpan"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("bytecode"))
.WithInitializer(
EqualsValueClause(
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))),
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadEmbeddedBytecode")))
.AddArgumentListArguments(Argument(IdentifierName("bytecode"))))));
// If there is no dynamic shader support, add the faulting path after the branch
return Block(embeddedBranch.WithElse(ElseClause(Block())));
}
}
}
+104 -76
ファイルの表示
@@ -1,7 +1,6 @@
using System;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -14,7 +13,6 @@ using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
@@ -31,17 +29,32 @@ partial class IShaderGenerator
/// </summary>
private static partial class LoadBytecode
{
/// <summary>
/// The shared cache of <see cref="HlslBytecodeInfo"/> values.
/// </summary>
private static readonly DynamicCache<HlslBytecodeInfoKey, HlslBytecodeInfo> HlslBytecodeCache = new();
/// <summary>
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
/// </summary>
private static volatile bool areDxcLibrariesLoaded;
/// <summary>
/// Gets the thread ids values for a given shader type, if available.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <returns>The thread ids for the precompiled shader, if available.</returns>
public static ThreadIdsInfo GetInfo(
/// <param name="threadsX">The thread ids value for the X axis.</param>
/// <param name="threadsY">The thread ids value for the Y axis.</param>
/// <param name="threadsZ">The thread ids value for the Z axis.</param>
/// <param name="isCompilationEnabled">Whether compilation should be attempted for the current info.</param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool supportsDynamicShaders)
out int threadsX,
out int threadsY,
out int threadsZ,
out bool isCompilationEnabled)
{
// Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced)
if (!structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName(typeof(EmbeddedBytecodeAttribute).FullName, out AttributeData? attribute))
@@ -49,12 +62,11 @@ partial class IShaderGenerator
// Emit the diagnostics if dynamic shaders are not supported
diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol);
return new(true, 0, 0, 0);
}
threadsX = threadsY = threadsZ = 0;
isCompilationEnabled = false;
int threadsX;
int threadsY;
int threadsZ;
return;
}
// Check for a dispatch axis argument first
if (attribute.ConstructorArguments.Length == 1)
@@ -78,8 +90,13 @@ partial class IShaderGenerator
{
diagnostics.Add(InvalidEmbeddedBytecodeDispatchAxis, structDeclarationSymbol, structDeclarationSymbol);
return new(true, 0, 0, 0);
threadsX = threadsY = threadsZ = 0;
isCompilationEnabled = false;
return;
}
isCompilationEnabled = true;
}
else if (
attribute.ConstructorArguments.Length != 3 ||
@@ -93,91 +110,102 @@ partial class IShaderGenerator
// Failed to validate the thread number arguments
diagnostics.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol);
return new(true, 0, 0, 0);
threadsX = threadsY = threadsZ = 0;
isCompilationEnabled = false;
return;
}
else
{
threadsX = explicitThreadsX;
threadsY = explicitThreadsY;
threadsZ = explicitThreadsZ;
isCompilationEnabled = true;
}
// Ensure the bytecode generation is disabled if any errors are present. This step is done last to ensure that
// all available diagnostics are still emitted correctly before reaching this point, instead of being disabled.
if (diagnostics.Count > 0)
{
return new(true, 0, 0, 0);
}
return new(false, threadsX, threadsY, threadsZ);
}
/// <summary>
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
/// Gets the <see cref="HlslBytecodeInfo"/> instance for the input shader info.
/// </summary>
private static volatile bool areDxcLibrariesLoaded;
/// <param name="key">The <see cref="HlslBytecodeInfoKey"/> instance for the shader to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>The <see cref="HlslBytecodeInfo"/> instance for the current shader.</returns>
public static unsafe HlslBytecodeInfo GetBytecode(ref HlslBytecodeInfoKey key, CancellationToken token)
{
static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token)
{
// Skip even attempting to compile if compilation is disabled (see comments in D2D1 generator)
if (!key.IsCompilationEnabled)
{
return HlslBytecodeInfo.Missing.Instance;
}
try
{
// Try to load dxcompiler.dll and dxil.dll
LoadNativeDxcLibraries();
token.ThrowIfCancellationRequested();
// Compile the shader bytecode
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.Compile(key.HlslSource.AsSpan());
token.ThrowIfCancellationRequested();
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
byte[] array = new ReadOnlySpan<byte>(buffer, length).ToArray();
ImmutableArray<byte> bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
return new HlslBytecodeInfo.Success(bytecode);
}
catch (Win32Exception e)
{
return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, FixupExceptionMessage(e.Message));
}
catch (DxcCompilationException e)
{
return new HlslBytecodeInfo.CompilerError(FixupExceptionMessage(e.Message));
}
}
return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token);
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// Gets any diagnostics from a processed <see cref="HlslBytecodeInfo"/> instance.
/// </summary>
/// <param name="threadIds">The input <see cref="ThreadIdsInfo"/> instance to process.</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <param name="diagnostic">The resulting diagnostic from the processing operation, if any.</param>
/// <returns>The <see cref="ImmutableArray{T}"/> instance with the compiled shader bytecode.</returns>
public static unsafe ImmutableArray<byte> GetBytecode(
ThreadIdsInfo threadIds,
string hlslSource,
CancellationToken token,
out DeferredDiagnosticInfo? diagnostic)
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="info">The source <see cref="HlslBytecodeInfo"/> instance.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public static void GetInfoDiagnostics(
INamedTypeSymbol structDeclarationSymbol,
HlslBytecodeInfo info,
ImmutableArrayBuilder<DiagnosticInfo> diagnostics)
{
ImmutableArray<byte> bytecode = ImmutableArray<byte>.Empty;
DiagnosticInfo? diagnostic = null;
// No embedded shader was requested
if (threadIds.IsDefault)
if (info is HlslBytecodeInfo.Win32Error win32Error)
{
diagnostic = null;
goto End;
diagnostic = DiagnosticInfo.Create(
EmbeddedBytecodeFailedWithWin32Exception,
structDeclarationSymbol,
new object[] { structDeclarationSymbol, win32Error.HResult, win32Error.Message });
}
else if (info is HlslBytecodeInfo.CompilerError dxcError)
{
diagnostic = DiagnosticInfo.Create(
EmbeddedBytecodeFailedWithDxcCompilationException,
structDeclarationSymbol,
new object[] { structDeclarationSymbol, dxcError.Message });
}
try
if (diagnostic is not null)
{
// Try to load dxcompiler.dll and dxil.dll
LoadNativeDxcLibraries();
token.ThrowIfCancellationRequested();
// Replace the actual thread num values
hlslSource = hlslSource
.Replace("<THREADSX>", threadIds.X.ToString(CultureInfo.InvariantCulture))
.Replace("<THREADSY>", threadIds.Y.ToString(CultureInfo.InvariantCulture))
.Replace("<THREADSZ>", threadIds.Z.ToString(CultureInfo.InvariantCulture));
// Compile the shader bytecode
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.Compile(hlslSource.AsSpan());
token.ThrowIfCancellationRequested();
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
byte[] array = new ReadOnlySpan<byte>(buffer, length).ToArray();
bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
diagnostic = null;
diagnostics.Add(diagnostic);
}
catch (Win32Exception e)
{
diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message));
}
catch (DxcCompilationException e)
{
diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message));
}
End:
return bytecode;
}
/// <summary>
+68 -237
ファイルの表示
@@ -1,12 +1,6 @@
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -17,252 +11,89 @@ partial class IShaderGenerator
partial class LoadDispatchData
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// Writes the <c>LoadDispatchData</c> method.
/// </summary>
/// <param name="shaderType">The type of shader interface currently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(
ShaderType shaderType,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
/// <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 WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TLoader>(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(GetDispatchDataLoadingStatements(shaderType, fieldInfos, resourceCount, root32BitConstantsCount)));
}
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TLoader>(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)");
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="shaderType">The type of shader interface currently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(
ShaderType shaderType,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
{
using ImmutableArrayBuilder<StatementSyntax> statements = new();
// global::System.Span<uint> span0 = stackalloc uint[<VARIABLES>];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
if (resourceCount > 0)
using (writer.WriteBlock())
{
// global::System.Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount)))))))))));
}
writer.WriteLine($"global::System.Span<uint> span0 = stackalloc uint[{info.Root32BitConstantCount}];");
writer.WriteLineIf($"global::System.Span<ulong> 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);
// ref uint r0 = ref span0[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// 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);
if (resourceCount > 0)
{
// ref ulong r1 = ref span1[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
}
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
// If the shader is a compute shader, also track the bounds on the Z axis:
//
// span0[2] = (uint)z;
if (shaderType == ShaderType.ComputeShader)
{
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
}
// Generate loading statements for each captured field
foreach (FieldInfo fieldInfo in fieldInfos)
{
switch (fieldInfo)
// Generate loading statements for each captured field
foreach (FieldInfo fieldInfo in info.Fields)
{
case FieldInfo.Resource resource:
switch (fieldInfo)
{
case FieldInfo.Resource resource:
// Validate the resource and get a handle for it. This will generate:
//
// global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, <OFFSET>) =
// global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(<FIELD_NAME>, device);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"),
ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)"))));
break;
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
// 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. This will generate the following:
//
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Bool>(
// ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = (global::ComputeSharp.Bool)<FIELD_PATH>
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Bool>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
ParseExpression($"(global::ComputeSharp.Bool){string.Join(".", primitive.FieldPath)}"))));
break;
case FieldInfo.Primitive 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<uint, global::ComputeSharp.Bool>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){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. This will generate:
//
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::<TYPE_NAME>>(
// ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = <FIELD_PATH>
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
break;
// Read a primitive value and serialize it into the target buffer
writer.WriteLine(
$"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset})) = " +
$"{string.Join(".", primitive.FieldPath)};");
break;
case FieldInfo.NonLinearMatrix matrix:
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
case FieldInfo.NonLinearMatrix matrix:
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__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>));
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
// 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 {string.Join(".", matrix.FieldPath)}));");
// 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++)
{
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
}
// 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<uint, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]})) = " +
$"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});");
}
break;
break;
}
}
// Load the prepared buffers
writer.WriteLine("loader.LoadCapturedValues(span0);");
writer.WriteLineIf("loader.LoadCapturedResources(span1);", info.ResourceCount > 0);
}
// loader.LoadCapturedValues(span0);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedValues")))
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
if (resourceCount > 0)
{
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
return statements.ToImmutable();
}
}
}
+3 -4
ファイルの表示
@@ -27,14 +27,14 @@ partial class IShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="shaderType">The type of shader currently being processed.</param>
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
ITypeSymbol structDeclarationSymbol,
ShaderType shaderType,
bool isPixelShaderLike,
out int resourceCount,
out int root32BitConstantCount)
{
@@ -91,8 +91,7 @@ partial class IShaderGenerator
// 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.
bool isComputeShader = shaderType == ShaderType.ComputeShader;
int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
int initialRawDataOffset = sizeof(int) * (isPixelShaderLike ? 2 : 3);
StrongBox<int> resourceOffsetAsBox = new();
StrongBox<int> rawDataOffsetAsBox = new(initialRawDataOffset);
@@ -1,14 +1,7 @@
using System;
using System.Collections.Immutable;
using System.Globalization;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -19,119 +12,40 @@ partial class IShaderGenerator
partial class LoadDispatchMetadata
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
/// Writes the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(DispatchMetadataInfo metadataInfo)
/// <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 WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TLoader>(ref TLoader loader, out global::System.IntPtr result)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchMetadata"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TLoader")),
Parameter(Identifier("result"))
.AddModifiers(Token(SyntaxKind.OutKeyword))
.WithType(IdentifierName($"global::System.{nameof(IntPtr)}")))
.WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo)));
}
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TLoader>(ref TLoader loader, out global::System.IntPtr result)");
/// <summary>
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
/// </summary>
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
{
using ImmutableArrayBuilder<StatementSyntax> statements = new();
// global::System.Span<byte> span0 = stackalloc byte[5];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))));
// Compute the total number of resources
int totalResourcesCount = metadataInfo.ResourceDescriptors.Length;
// Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[<ADJUSTED_COUNT>];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))));
// ref byte r0 = ref span0[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// Serialized shader metadata
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});"));
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()});"));
// Populate the sequence of resource descriptors
foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors)
using (writer.WriteBlock())
{
statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"));
// Compute the total number of resources
int totalResourcesCount = info.ResourceDescriptors.Length;
writer.WriteLine("global::System.Span<byte> span0 = stackalloc byte[5];");
writer.WriteLine($"global::System.Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[{totalResourcesCount}];");
writer.WriteLine("ref byte r0 = ref span0[0];");
writer.WriteLine("ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];");
// Write the serialized shader metadata
writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {info.Root32BitConstantCount});");
writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {info.IsSamplerUsed.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()});");
// Populate the sequence of resource descriptors
foreach (ResourceDescriptor descriptor in info.ResourceDescriptors)
{
writer.WriteLine($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));");
}
// Invoke the value delegate to create the opaque root signature handle
writer.WriteLine("loader.LoadMetadataHandle(span0, span1, out result);");
}
// Invoke the value delegate to create the opaque root signature handle
statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"));
return statements.ToImmutable();
}
}
}
+2 -5
ファイルの表示
@@ -21,7 +21,7 @@ partial class IShaderGenerator
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
/// <param name="capturedFields">The sequence of captured fields for the shader.</param>
/// <returns>The metadata info for the shader.</returns>
public static DispatchMetadataInfo GetInfo(
public static ImmutableArray<ResourceDescriptor> GetInfo(
int root32BitConstantCount,
bool isImplicitTextureUsed,
bool isSamplerUsed,
@@ -57,10 +57,7 @@ partial class IShaderGenerator
}
}
return new(
root32BitConstantCount,
isSamplerUsed,
descriptors.ToImmutable());
return descriptors.ToImmutable();
}
}
}
+16 -61
ファイルの表示
@@ -1,10 +1,4 @@
using System.Collections.Generic;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators;
@@ -12,75 +6,36 @@ namespace ComputeSharp.SourceGenerators;
partial class IShaderGenerator
{
/// <summary>
/// Gets the shader type for a given shader, if any.
/// Gets whether a given type is a compute shader type (ie. implements any of the interfaces).
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>The shader type for <paramref name="typeSymbol"/>, or <see langword="null"/>.</returns>
private static ShaderType? GetShaderType(INamedTypeSymbol typeSymbol, Compilation compilation)
/// <param name="result">Whether <paramref name="typeSymbol"/> is a "pixel shader like" type.</param>
/// <returns>Whether <paramref name="typeSymbol"/> is a compute shader type at all.</returns>
private static bool TryGetIsPixelShaderLike(INamedTypeSymbol typeSymbol, Compilation compilation, out bool result)
{
INamedTypeSymbol computeShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader")!;
INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!;
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces)
{
if (interfaceSymbol.Name == nameof(IComputeShader))
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol))
{
INamedTypeSymbol computeShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader")!;
result = false;
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol))
{
return ShaderType.ComputeShader;
}
return true;
}
else if (interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) })
else if (interfaceSymbol is { IsGenericType: true } &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol))
{
INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!;
result = true;
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol))
{
return ShaderType.PixelShader;
}
return true;
}
}
return null;
}
result = false;
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> item to insert.</param>
/// <param name="addSkipLocalsInitAttribute">Whether <c>[SkipLocalsInit]</c> should be used.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="methodDeclaration"/>.</returns>
private static CompilationUnitSyntax GetCompilationUnitFromMethod(
HierarchyInfo hierarchyInfo,
MethodDeclarationSyntax methodDeclaration,
bool addSkipLocalsInitAttribute)
{
// Method attributes
List<AttributeListSyntax> attributes = new()
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
// Add [SkipLocalsInit] if needed
if (addSkipLocalsInitAttribute)
{
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
}
return hierarchyInfo.GetSyntax(methodDeclaration.AddAttributeLists(attributes.ToArray()));
return false;
}
}
+71 -118
ファイルの表示
@@ -1,7 +1,6 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
@@ -9,7 +8,6 @@ using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace ComputeSharp.SourceGenerators;
@@ -19,11 +17,16 @@ namespace ComputeSharp.SourceGenerators;
[Generator(LanguageNames.CSharp)]
public sealed partial class IShaderGenerator : IIncrementalGenerator
{
/// <summary>
/// The name of generator to include in the generated code.
/// </summary>
private const string GeneratorName = "ComputeSharp.IShaderGenerator";
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Discover all shader types and extract all the necessary info from each of them
IncrementalValuesProvider<ShaderInfo> shaderInfoWithErrors =
IncrementalValuesProvider<ShaderInfo> shaderInfo =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes<StructDeclarationSyntax>(),
@@ -43,8 +46,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
return default;
}
// Get the shader type, or return if none is present
if (GetShaderType(typeSymbol, context.SemanticModel.Compilation) is not ShaderType shaderType)
// Check whether type is a compute shader, and if so, if it's pixel shader like
if (!TryGetIsPixelShaderLike(typeSymbol, context.SemanticModel.Compilation, out bool isPixelShaderLike))
{
return default;
}
@@ -55,157 +58,107 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
typeSymbol,
shaderType,
isPixelShaderLike,
out int resourceCount,
out int root32BitConstantCount);
token.ThrowIfCancellationRequested();
// TryGetBytecode() info
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
LoadBytecode.GetInfo(
diagnostics,
typeSymbol,
false);
out int threadsX,
out int threadsY,
out int threadsZ,
out bool isCompilationEnabled);
token.ThrowIfCancellationRequested();
// BuildHlslSource() info
HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo(
BuildHlslSource.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeDeclaration,
typeSymbol,
threadIds,
out bool isImplicitTextureUsed);
threadsX,
threadsY,
threadsZ,
out bool isImplicitTextureUsed,
out bool isSamplerUsed,
out string hlslSource);
token.ThrowIfCancellationRequested();
// GetDispatchMetadata() info
DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo(
ImmutableArray<ResourceDescriptor> resourceDescriptors = LoadDispatchMetadata.GetInfo(
root32BitConstantCount,
isImplicitTextureUsed,
hlslSourceInfo.IsSamplerUsed,
isSamplerUsed,
fieldInfos);
token.ThrowIfCancellationRequested();
// Prepare the lookup key for the HLSL shader bytecode
HlslBytecodeInfoKey hlslInfoKey = new(hlslSource, isCompilationEnabled);
// Try to get the HLSL bytecode
HlslBytecodeInfo hlslInfo = LoadBytecode.GetBytecode(ref hlslInfoKey, token);
token.ThrowIfCancellationRequested();
LoadBytecode.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics);
token.ThrowIfCancellationRequested();
// Also get the hierarchy too
HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol);
token.ThrowIfCancellationRequested();
return new ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
DispatchData: new DispatchDataInfo(
shaderType,
fieldInfos,
resourceCount,
root32BitConstantCount),
DispatchMetadata: dispatchMetadataInfo,
HlslShaderSource: hlslSourceInfo,
ThreadIds: threadIds,
Hierarchy: hierarchyInfo,
ThreadsX: threadsX,
ThreadsY: threadsY,
ThreadsZ: threadsZ,
IsPixelShaderLike: isPixelShaderLike,
IsSamplerUsed: isSamplerUsed,
Fields: fieldInfos,
ResourceDescriptors: resourceDescriptors,
ResourceCount: resourceCount,
Root32BitConstantCount: root32BitConstantCount,
HlslInfoKey: hlslInfoKey,
HlslInfo: hlslInfo,
Diagnostcs: diagnostics.ToImmutable());
})
.Where(static item => item is not null)!;
// Split the diagnostics, and drop them from the output provider (see more notes in the D2D1 generator)
IncrementalValuesProvider<EquatableArray<DiagnosticInfo>> diagnosticInfo = shaderInfo.Select(static (item, _) => item.Diagnostcs);
IncrementalValuesProvider<ShaderInfo> outputInfo = shaderInfo.Select(static (item, _) => item with { Diagnostcs = default });
// Output the diagnostics, if any
context.ReportDiagnostics(
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
context.ReportDiagnostics(diagnosticInfo);
// Get the LoadDispatchData() info (hierarchy and dispatch data info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo DispatchData)> dispatchDataInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.DispatchData));
// Generate the LoadDispatchData() methods
context.RegisterSourceOutput(dispatchDataInfo, static (context, item) =>
// Generate the source files, if any
context.RegisterSourceOutput(outputInfo, static (context, item) =>
{
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(
item.DispatchData.Type,
item.DispatchData.FieldInfos,
item.DispatchData.ResourceCount,
item.DispatchData.Root32BitConstantCount);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, addSkipLocalsInitAttribute: true);
using ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> declaredMembers = new();
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
declaredMembers.Add(LoadDispatchData.WriteSyntax);
declaredMembers.Add(LoadDispatchMetadata.WriteSyntax);
declaredMembers.Add(BuildHlslSource.WriteSyntax);
declaredMembers.Add(LoadBytecode.WriteSyntax);
// Get the BuildHlslSource info (hierarchy, HLSL source and parsing options)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource)> hlslSourceInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource));
using IndentedTextWriter writer = new();
// Generate the BuildHlslSource() methods
context.RegisterSourceOutput(hlslSourceInfo, static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslShaderSource, item.Hierarchy.Hierarchy.Length);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true);
item.Hierarchy.WriteSyntax(
state: item,
writer: writer,
baseTypes: ReadOnlySpan<string>.Empty,
memberCallbacks: declaredMembers.WrittenSpan);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the LoadDispatchMetadata() info (hierarchy and dispatch metadata info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo DispatchMetadata)> dispatchMetadataInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.DispatchMetadata));
// Generate the LoadDispatchMetadata() methods
context.RegisterSourceOutput(dispatchMetadataInfo, static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.DispatchMetadata);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchMetadata)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Transform the raw HLSL source to compile (this step aggregates the HLSL source to ensure compilation is only done for actual HLSL changes)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo =
shaderInfoWithErrors
.Select(static (item, token) => (item.Hierarchy, item.HlslShaderSource.HlslSource, item.ThreadIds));
// Compile the requested shader bytecodes
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
shaderBytecodeInfo
.Select(static (item, token) =>
{
ImmutableArray<byte> bytecode = LoadBytecode.GetBytecode(item.ThreadIds, item.Hlsl, token, out DeferredDiagnosticInfo? diagnostic);
token.ThrowIfCancellationRequested();
EmbeddedBytecodeInfo bytecodeInfo = new(
item.ThreadIds.X,
item.ThreadIds.Y,
item.ThreadIds.Z,
bytecode);
return (item.Hierarchy, bytecodeInfo, diagnostic);
});
// Gather the diagnostics
IncrementalValuesProvider<DiagnosticInfo> embeddedBytecodeDiagnostics =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic))
.Where(static item => item.Diagnostic is not null)
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!;
return DiagnosticInfo.Create(item.Left.Diagnostic!.Descriptor, typeSymbol, new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Arguments).ToArray());
});
// Output the diagnostics
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
// Get the TryGetBytecode() info (hierarchy and compiled bytecode)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode)> embeddedBytecodeInfo =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode));
// Generate the TryGetBytecode() methods
context.RegisterSourceOutput(embeddedBytecodeInfo, static (context, item) =>
{
MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.EmbeddedBytecode, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false);
SourceText text = fixup(compilationUnit);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString());
});
}
}
-16
ファイルの表示
@@ -1,16 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader dispatch data.
/// </summary>
/// <param name="Type">The shader interface type.</param>
/// <param name="FieldInfos">The description on shader instance fields.</param>
/// <param name="ResourceCount">The total number of captured resources.</param>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
internal sealed record DispatchDataInfo(
ShaderType Type,
EquatableArray<FieldInfo> FieldInfos,
int ResourceCount,
int Root32BitConstantCount);
-11
ファイルの表示
@@ -1,11 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model containing info on shader dispatch metadata.
/// </summary>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="ResourceDescriptors">The sequence of resource descriptors for the shader.</param>
internal sealed record DispatchMetadataInfo(int Root32BitConstantCount, bool IsSamplerUsed, EquatableArray<ResourceDescriptor> ResourceDescriptors);
-12
ファイルの表示
@@ -1,12 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing a compiled shader bytecode, or none.
/// </summary>
/// <param name="X">The thread ids value for the X axis.</param>
/// <param name="Y">The thread ids value for the Y axis.</param>
/// <param name="Z">The thread ids value for the Z axis.</param>
/// <param name="Bytecode">The compiled shader bytecode, if available.</param>
internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, EquatableArray<byte> Bytecode);
+10
ファイルの表示
@@ -0,0 +1,10 @@
using ComputeSharp.SourceGeneration.Models;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model with info to be a unique key for <see cref="HlslBytecodeInfo"/> instances.
/// </summary>
/// <param name="HlslSource">The input HLSL source code.</param>
/// <param name="IsCompilationEnabled">Whether compilation should be attempted for the current info.</param>
internal sealed record HlslBytecodeInfoKey(string HlslSource, bool IsCompilationEnabled);
-8
ファイルの表示
@@ -1,8 +0,0 @@
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL shader.
/// </summary>
/// <param name="HlslSource">The HLSL source for the shader.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
internal sealed record HlslShaderSourceInfo(string HlslSource, bool IsSamplerUsed);
+22 -8
ファイルの表示
@@ -7,15 +7,29 @@ namespace ComputeSharp.SourceGenerators.Models;
/// A model representing all necessary info for a full generation pass for a shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="DispatchMetadata">The gathered shader dispatch metadata.</param>
/// <param name="HlslShaderSource">The processed HLSL source for the shader.</param>
/// <param name="ThreadIds">The thread ids for the shader, if compilation is requested.</param>
/// <param name="ThreadsX">The thread ids value for the X axis.</param>
/// <param name="ThreadsY">The thread ids value for the Y axis.</param>
/// <param name="ThreadsZ">The thread ids value for the Z axis.</param>
/// <param name="IsPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="Fields">The description on shader instance fields.</param>
/// <param name="ResourceDescriptors">The sequence of resource descriptors for the shader.</param>
/// <param name="ResourceCount">The total number of captured resources in the shader.</param>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
/// <param name="HlslInfoKey">The key with processed info on the shader.</param>
/// <param name="HlslInfo">The value with processed info on the shader.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderInfo(
HierarchyInfo Hierarchy,
DispatchDataInfo DispatchData,
DispatchMetadataInfo DispatchMetadata,
HlslShaderSourceInfo HlslShaderSource,
ThreadIdsInfo ThreadIds,
int ThreadsX,
int ThreadsY,
int ThreadsZ,
bool IsPixelShaderLike,
bool IsSamplerUsed,
EquatableArray<FieldInfo> Fields,
EquatableArray<ResourceDescriptor> ResourceDescriptors,
int ResourceCount,
int Root32BitConstantCount,
HlslBytecodeInfoKey HlslInfoKey,
HlslBytecodeInfo HlslInfo,
EquatableArray<DiagnosticInfo> Diagnostcs);
-17
ファイルの表示
@@ -1,17 +0,0 @@
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// Indicates a type of shader being processed.
/// </summary>
public enum ShaderType
{
/// <summary>
/// A compute shader.
/// </summary>
ComputeShader,
/// <summary>
/// A pixel shader.
/// </summary>
PixelShader
}
-10
ファイルの表示
@@ -1,10 +0,0 @@
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a embedded thread ids.
/// </summary>
/// <param name="IsDefault">Whether the values are discarded.</param>
/// <param name="X">The thread ids value for the X axis.</param>
/// <param name="Y">The thread ids value for the Y axis.</param>
/// <param name="Z">The thread ids value for the Z axis.</param>
internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z);