Initial implementation of generator for shader methods

このコミットが含まれているのは:
Sergio Pedri committed 2022-08-18 14:26:09 +02:00
1 親 2fa5922c15
コミット 4e6f4f55d4
6ファイル変更
+351 -6

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

+1
ファイルの表示
@@ -76,6 +76,7 @@
<Compile Include="..\ComputeSharp.D2D1\Attributes\D2DInputCountAttribute.cs" Link="ComputeSharp.D2D1\Attributes\D2DInputCountAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\D2DInputSimpleAttribute.cs" Link="ComputeSharp.D2D1\Attributes\D2DInputSimpleAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\D2DRequiresScenePositionAttribute.cs" Link="ComputeSharp.D2D1\Attributes\D2DRequiresScenePositionAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\D2DPixelShaderSourceAttribute.cs" Link="ComputeSharp.D2D1\Attributes\D2DPixelShaderSourceAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1\Extensions\ComPtrExtensions.cs" Link="ComputeSharp.D2D1\Extensions\ComPtrExtensions.cs" />
<Compile Include="..\ComputeSharp.D2D1\Extensions\HResultExtensions.cs" Link="ComputeSharp.D2D1\Extensions\HResultExtensions.cs" />
<Compile Include="..\ComputeSharp.D2D1\Interfaces\ID2D1PixelShader.cs" Link="ComputeSharp.D2D1\Interfaces\ID2D1PixelShader.cs" />
@@ -0,0 +1,73 @@
using System;
using System.Text;
using ComputeSharp.D2D1.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class D2DPixelShaderSourceGenerator
{
/// <inheritdoc/>
partial class Execute
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// </summary>
/// <param name="bytecodeInfo">The input bytecode info.</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 target method.</returns>
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func<SyntaxNode, SourceText> fixup)
{
// If there is no precompiled bytecode, just emit a span with a 0 value
string bytecodeLiterals = bytecodeInfo.Bytecode.IsDefaultOrEmpty
? "0"
: ID2D1ShaderGenerator.LoadBytecode.BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan());
// Prepare the fixup function
fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8);
// This code produces a branch as follows:
//
// /// <inheritdoc/>
// [global::System.CodeDom.Compiler.GeneratedCode("...", "...")]
// [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
// <MODIFIERS> global::System.ReadOnlySpan<byte> <METHOD_NAME>()
// {
// return new byte[] { __EMBEDDED_SHADER_BYTECODE };
// }
//
// As in the ID2D1Shader generator, the __EMBEDDED_SHADER_BYTECODE identifier will be replaced with the bytecode
// after the full string for the syntax tree has been generated, to avoid every literal going through a token.
return
MethodDeclaration(
GenericName(Identifier("global::System.ReadOnlySpan"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))),
Identifier("TheMethodName")).AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode"))
.AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).Assembly.GetName().Version.ToString()))))))
.WithOpenBracketToken(Token(TriviaList(Comment(
$"/// <inheritdoc/>")),
SyntaxKind.OpenBracketToken,
TriviaList())),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))))
.WithBody(Block(
ReturnStatement(
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))));
}
}
}
+152
ファイルの表示
@@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using ComputeSharp.D2D1.Exceptions;
using ComputeSharp.D2D1.Shaders.Translation;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class D2DPixelShaderSourceGenerator
{
/// <summary>
/// A container for all the logic for <see cref="D2DPixelShaderSourceGenerator"/>.
/// </summary>
private static partial class Execute
{
/// <summary>
/// Extracts the HLSL source from a method with the <see cref="D2DPixelShaderSourceAttribute"/> annotation.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The HLSL source to compile, if present.</returns>
public static string? GetHlslSource(ImmutableArray<Diagnostic>.Builder diagnostics, IMethodSymbol methodSymbol)
{
_ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData);
if (!attributeData!.TryGetConstructorArgument(0, out string? hlslSource))
{
// TODO: no string diagnostic
}
return hlslSource;
}
/// <summary>
/// Extracts the shader profile for a target method, if present.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The shader profile to use to compile the shader, if present.</returns>
public static D2D1ShaderProfile? GetShaderProfile(ImmutableArray<Diagnostic>.Builder diagnostics, IMethodSymbol methodSymbol)
{
if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out AttributeData? attributeData))
{
return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!;
}
if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out attributeData))
{
return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!;
}
// TODO: diagnostics
return null;
}
/// <summary>
/// Extracts the compile options for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="methodSymbol">The input <see cref="IMethodSymbol"/> instance to process.</param>
/// <returns>The compile options to use to compile the shader, if present.</returns>
public static D2D1CompileOptions? GetCompileOptions(ImmutableArray<Diagnostic>.Builder diagnostics, IMethodSymbol methodSymbol)
{
if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData))
{
return (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!;
}
if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out attributeData))
{
return (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!;
}
// TODO: diagnostics
return null;
}
/// <summary>
/// Gets an <see cref="ImmutableArray{T}"/> instance with the compiled bytecode for the current shader.
/// </summary>
/// <param name="sourceInfo">The source info for the shader to compile.</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(HlslShaderSourceInfo sourceInfo, CancellationToken token, out DiagnosticInfo? diagnostic)
{
ImmutableArray<byte> bytecode = ImmutableArray<byte>.Empty;
// Skip compilation if there are any errors
if (sourceInfo is { HasErrors: true })
{
diagnostic = null;
goto End;
}
try
{
token.ThrowIfCancellationRequested();
// Compile the shader bytecode using the requested parameters
using ComPtr<ID3DBlob> dxcBlobBytecode = D3DCompiler.Compile(
sourceInfo.HlslSource.AsSpan(),
sourceInfo.ShaderProfile!.Value,
sourceInfo.CompileOptions!.Value);
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;
}
catch (Win32Exception e)
{
diagnostic = new DiagnosticInfo(
null!, // TODO
e.HResult,
ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message));
}
catch (FxcCompilationException e)
{
diagnostic = new DiagnosticInfo(
null!, // TODO
ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message));
}
End:
return bytecode;
}
}
}
+121
ファイルの表示
@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <summary>
/// A source generator compiling methods annotated with <see cref="D2DPixelShaderSourceAttribute"/>.
/// </summary>
[Generator(LanguageNames.CSharp)]
public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get all method declarations with the [D2DPixelShaderSource] attribute
IncrementalValuesProvider<IMethodSymbol> methodSymbols =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is MethodDeclarationSyntax { Parent: ClassDeclarationSyntax, AttributeLists.Count: > 0 },
static (context, _) => (IMethodSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!)
.Where(static symbol => symbol.HasAttributeWithFullyQualifiedName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute"));
// Gather info for all annotated methods
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source, ImmutableArray<Diagnostic> Diagnostics)> shaderInfoWithErrors =
methodSymbols
.Select(static (item, _) =>
{
ImmutableArray<Diagnostic>.Builder diagnostics = ImmutableArray.CreateBuilder<Diagnostic>();
// Get all necessary info for the current shader
string? hlslSource = Execute.GetHlslSource(diagnostics, item) ?? "";
D2D1ShaderProfile? shaderProfile = Execute.GetShaderProfile(diagnostics, item);
D2D1CompileOptions? compileOptions = Execute.GetCompileOptions(diagnostics, item);
HlslShaderSourceInfo sourceInfo = new(
hlslSource,
shaderProfile,
compileOptions,
IsLinkingSupported: false,
HasErrors: diagnostics.Count > 0);
HierarchyInfo hierarchy = HierarchyInfo.From(item.ContainingType!);
return (hierarchy, sourceInfo, diagnostics.ToImmutable());
});
// Output the diagnostics
context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostics));
// Filter all items to enable caching at a coarse level, and remove diagnostics
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderInfo =
shaderInfoWithErrors
.Select(static (item, token) => (item.Hierarchy, item.Source))
.WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer<HlslShaderSourceInfo>.Default);
// Compile the requested shader bytecodes
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
shaderInfo
.Select(static (item, token) =>
{
ImmutableArray<byte> bytecode = Execute.GetBytecode(
item.Source,
token,
out DiagnosticInfo? diagnostic);
token.ThrowIfCancellationRequested();
EmbeddedBytecodeInfo bytecodeInfo = new(
item.Source.HlslSource,
item.Source.ShaderProfile,
item.Source.CompileOptions,
bytecode);
return (item.Hierarchy, bytecodeInfo, diagnostic);
});
// Gather the diagnostics
IncrementalValuesProvider<Diagnostic> 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 Diagnostic.Create(
item.Left.Diagnostic!.Descriptor,
typeSymbol.Locations.FirstOrDefault(),
new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray());
});
// Output the diagnostics
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo))
.WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default);
// Generate the shader bytecode methods
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
{
MethodDeclarationSyntax loadBytecodeMethod = Execute.GetSyntax(item.BytecodeInfo, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = item.Hierarchy.GetSyntax(loadBytecodeMethod);
SourceText text = fixup(compilationUnit);
context.AddSource($"{item.Hierarchy.FilenameHint}.TESTMETHOD", text);
});
}
}
@@ -214,7 +214,7 @@ partial class ID2D1ShaderGenerator
/// </summary>
/// <param name="bytecode">The input shader bytecode to serialize.</param>
/// <returns>A formatted <see cref="string"/> with the serialized data.</returns>
private static string BuildShaderBytecodeExpressionString(ReadOnlySpan<byte> bytecode)
internal static string BuildShaderBytecodeExpressionString(ReadOnlySpan<byte> bytecode)
{
//The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
@@ -11,8 +11,6 @@ using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
@@ -25,7 +23,7 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// A helper with all logic to generate the <c>LoadBytecode</c> method.
/// </summary>
private static partial class LoadBytecode
internal static partial class LoadBytecode
{
/// <summary>
/// Extracts the shader profile for the current shader.
@@ -142,7 +140,7 @@ partial class ID2D1ShaderGenerator
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// Gets an <see cref="ImmutableArray{T}"/> instance with the compiled bytecode for the current shader.
/// </summary>
/// <param name="sourceInfo">The source info for the shader to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
@@ -212,7 +210,7 @@ partial class ID2D1ShaderGenerator
/// </summary>
/// <param name="message">The input exception message.</param>
/// <returns>The updated exception message.</returns>
private static string FixupExceptionMessage(string message)
internal static string FixupExceptionMessage(string message)
{
// Add square brackets around error headers
message = Regex.Replace(message, @"((?:error|warning) \w+):", static m => $"[{m.Groups[1].Value}]:");