diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 6d7afd0c..5ba5ade8 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -16,6 +16,7 @@ and to match members based on full name, so the types being in the generator assembly are not an issue.--> + @@ -70,6 +71,9 @@ + + + diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs b/src/ComputeSharp.SourceGenerators/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs new file mode 100644 index 00000000..8bcf0e29 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp/Graphics/Extensions/Interop/HResultExtensions.cs @@ -0,0 +1,35 @@ +using System.ComponentModel; +using System.Diagnostics; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.Core.Extensions; + +/// +/// Helper methods to efficiently throw exceptions. +/// +[DebuggerStepThrough] +internal static class HResultExtensions +{ + /// + /// Throws a if represents an error. + /// + /// The input to check. + /// Thrown if represents an error. + public static void Assert(this HRESULT result) + { + Assert((int)result); + } + + /// + /// Throws a if represents an error. + /// + /// The input to check. + /// Thrown if represents an error. + public static void Assert(this int result) + { + if (result < 0) + { + throw new Win32Exception(result); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 66b7a382..94d6bf45 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -29,7 +29,8 @@ public sealed partial class IShaderGenerator StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, - out bool isSamplerUsed) + out bool isSamplerUsed, + out string hlslSource) { // Properties are not supported DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); @@ -70,7 +71,8 @@ public sealed partial class IShaderGenerator accessesStaticSampler, sharedBuffers, processedMethods, - entryPoint); + entryPoint, + out hlslSource); implicitTextureType = pixelShaderTextureType; isSamplerUsed = accessesStaticSampler; @@ -472,6 +474,7 @@ public sealed partial class IShaderGenerator /// The sequence of shared buffers declared by the shader. /// The sequence of processed methods used by the shader. /// The body of the entry point of the shader. + /// The generated HLSL source code (ignoring captured delegates, if present). /// The series of statements to build the HLSL source to compile to execute the current shader. private static IEnumerable GenerateRenderMethodBody( IEnumerable<(string Name, string Value)> definedConstants, @@ -483,34 +486,41 @@ public sealed partial class IShaderGenerator bool isSamplerUsed, IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, IEnumerable<(string Signature, string Definition)> processedMethods, - string executeMethod) + string executeMethod, + out string hlslSource) { List statements = new(); - StringBuilder textBuilder = new(); + StringBuilder chunkedTextBuilder = new(); + StringBuilder aggregateTextBuilder = new(); int capturedDelegates = 0; int prologueStatements = 0; int sizeHint = 64; void AppendLF() { - textBuilder.Append('\n'); + chunkedTextBuilder.Append('\n'); } void AppendLine(string text) { - textBuilder.Append(text); + chunkedTextBuilder.Append(text); } void AppendLineAndLF(string text) { - textBuilder.Append(text); - textBuilder.Append('\n'); + chunkedTextBuilder.Append(text); + chunkedTextBuilder.Append('\n'); } void AppendCharacterAndLF(char c) { - textBuilder.Append(c); - textBuilder.Append('\n'); + chunkedTextBuilder.Append(c); + chunkedTextBuilder.Append('\n'); + } + + void AppendThreadNumIdentifier(string name) + { + aggregateTextBuilder.Append(name); } void AppendParsedStatement(string text) @@ -522,17 +532,21 @@ public sealed partial class IShaderGenerator void FlushText() { - if (textBuilder.Length > 0) + if (chunkedTextBuilder.Length > 0) { - sizeHint += textBuilder.Length; + string chunkedText = chunkedTextBuilder.ToString(); + + aggregateTextBuilder.Append(chunkedText); + + sizeHint += chunkedTextBuilder.Length; statements.Add( ExpressionStatement( InvocationExpression( MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(textBuilder.ToString())))))); + .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(chunkedText)))))); - textBuilder.Clear(); + chunkedTextBuilder.Clear(); } } @@ -608,12 +622,15 @@ public sealed partial class IShaderGenerator AppendLF(); AppendLine("#define __GroupSize__get_X "); AppendParsedStatement("builder.Append(threadsX);"); + AppendThreadNumIdentifier(""); AppendLF(); AppendLine("#define __GroupSize__get_Y "); AppendParsedStatement("builder.Append(threadsY);"); + AppendThreadNumIdentifier(""); AppendLF(); AppendLine("#define __GroupSize__get_Z "); AppendParsedStatement("builder.Append(threadsZ);"); + AppendThreadNumIdentifier(""); AppendLF(); // Define declarations @@ -810,6 +827,8 @@ public sealed partial class IShaderGenerator SyntaxKind.NumericLiteralExpression, Literal(sizeHint))))))); + hlslSource = aggregateTextBuilder.ToString(); + return statements; } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs index bbbf4452..1e8a3eae 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs @@ -16,7 +16,7 @@ namespace ComputeSharp.SourceGenerators; public sealed partial class IShaderGenerator { /// - private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol) + private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader) { // This code produces a method declaration as follows: // @@ -30,16 +30,17 @@ public sealed partial class IShaderGenerator Identifier("GetDispatchId")) .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .WithBody(GetShaderHashCodeBody(structDeclarationSymbol)); + .WithBody(GetShaderHashCodeBody(structDeclarationSymbol, out isDynamicShader)); } /// /// Gets a instance with the logic to compute the hashcode of a given shader type. /// /// The input instance to process. + /// Indicates whether or not the shader is dynamic (ie. captures delegates). /// The instance to hash the input shader. [Pure] - private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol) + private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader) { var delegateFields = structDeclarationSymbol .GetMembers() @@ -47,6 +48,8 @@ public sealed partial class IShaderGenerator .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) .ToImmutableArray(); + isDynamicShader = delegateFields.Length > 0; + if (delegateFields.Length == 0) { // return 0; diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index 18c3a058..604f45a5 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -1,14 +1,182 @@ using System; using System.ComponentModel; +using System.Diagnostics.Contracts; using System.IO; +using System.Linq; using System.Reflection; using System.Runtime.InteropServices; +using ComputeSharp.__Internals; +using ComputeSharp.Exceptions; +using ComputeSharp.Shaders.Translation; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; /// public sealed partial class IShaderGenerator { + /// + /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// + private static bool areDxcLibrariesLoaded; + + /// + private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + bool isDynamicShader, + string hlslSource) + { + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode) + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.BoolKeyword)), + Identifier("TryGetBytecode")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .AddParameterListParameters( + Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan"))) + .WithBody(GetShaderBytecodeBody(structDeclarationSymbol, isDynamicShader, hlslSource)); + } + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance to process. + /// Indicates whether or not the shader is dynamic (ie. captures delegates). + /// The generated HLSL source code (ignoring captured delegates, if present). + /// The instance to hash the input shader. + [Pure] + private static unsafe BlockSyntax GetShaderBytecodeBody(INamedTypeSymbol structDeclarationSymbol, bool isDynamicShader, string hlslSource) + { + AttributeData? attribute = structDeclarationSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(EmbeddedBytecodeAttribute) }); + + // No embedded shader was requested + if (attribute is null) + { + // This code produces a method declaration as follows: + // + // bytecode = default; + // + // return false; + return + Block( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement( + LiteralExpression( + SyntaxKind.FalseLiteralExpression))); + } + + // If the current shader is dynamic, emit a diagnostic error + if (isDynamicShader) + { + // TODO + return Block(); + } + + // Validate the thread number arguments + if (attribute.ConstructorArguments[0].Value is not int threadsX || + attribute.ConstructorArguments[1].Value is not int threadsY || + attribute.ConstructorArguments[2].Value is not int threadsZ || + threadsX is < 1 or > 1024 || + threadsY is < 1 or > 1024 || + threadsZ is < 1 or > 64) + { + // TODO + return Block(); + } + + LoadNativeDxcLibraries(); + + try + { + // Replace the actual thread num values + hlslSource = hlslSource.Replace("", threadsX.ToString()).Replace("", threadsY.ToString()).Replace("", threadsZ.ToString()); + + // Compile the shader bytecode + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan()); + + byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); + int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + string bytecode = string.Join(",", new Span(buffer, length).ToArray().Select(static b => $"0x{b:X2}")); + + // This code produces a method declaration as follows: + // + // if (threadsX == && threadsY == && threadsZ == ) + // { + // bytecode = new byte[] { 0x00, 0x01, ..., 0xFF }; + // + // return true; + // } + // + // bytecode = default; + // + // return false; + return + Block( + IfStatement( + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.LogicalAndExpression, + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsX"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsX))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsY"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsY)))), + BinaryExpression( + SyntaxKind.EqualsExpression, + IdentifierName("threadsZ"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsZ)))), + Block( + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + ParseExpression($"new byte[] {{ {bytecode} }}"))), + ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); + } + catch (Win32Exception) + { + // TODO + return Block(); + } + catch (HlslCompilationException) + { + // TODO + return Block(); + } + } + /// /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. /// @@ -16,18 +184,13 @@ public sealed partial class IShaderGenerator /// Thrown if a library fails to load. private static void LoadNativeDxcLibraries() { - string rid = RuntimeInformation.ProcessArchitecture switch - { - Architecture.X64 => "win-x64", - Architecture.Arm64 => "win-arm64", - _ => throw new NotSupportedException("Invalid process architecture") - }; - // Extracts a specified native library for a given runtime identifier static string ExtractLibrary(string rid, string name) { - string sourceFilename = $"ComputeSharp.SourceGenerators.Libraries.{rid}.{name}.dll"; - string targetFilename = Path.Combine("%TEMP%", "ComputeSharp.SourceGenerators", rid, $"{name}.dll"); + string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll"; + string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll"); + + Directory.CreateDirectory(Path.GetDirectoryName(targetFilename)); using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename); @@ -61,7 +224,19 @@ public sealed partial class IShaderGenerator } } - LoadLibrary(ExtractLibrary(rid, "dxil")); - LoadLibrary(ExtractLibrary(rid, "dxcompiler")); + if (!areDxcLibrariesLoaded) + { + string rid = RuntimeInformation.ProcessArchitecture switch + { + Architecture.X64 => "x64", + Architecture.Arm64 => "arm64", + _ => throw new NotSupportedException("Invalid process architecture") + }; + + LoadLibrary(ExtractLibrary(rid, "dxil")); + LoadLibrary(ExtractLibrary(rid, "dxcompiler")); + } + + areDxcLibrariesLoaded = true; } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index c89752f1..0b5b41fd 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -56,10 +56,11 @@ public sealed partial class IShaderGenerator : ISourceGenerator private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol) { // Create the required interface methods for the current shader type - MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol); + MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol, out bool isDynamicShader); MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants); - MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed); + MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out string hlslSource); MethodDeclarationSyntax loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed); + MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(context, structDeclaration, structDeclarationSymbol, isDynamicShader, hlslSource); // Reorder the method declarations to respect the order in the interface definition MethodDeclarationSyntax[] methods = @@ -67,7 +68,8 @@ public sealed partial class IShaderGenerator : ISourceGenerator getDispatchIdMethod, loadDispatchDataMethod, loadDispatchMetadataMethod, - buildHlslStringMethod + buildHlslStringMethod, + tryGetBytecodeMethod }; // Method attributes @@ -148,8 +150,9 @@ public sealed partial class IShaderGenerator : ISourceGenerator /// Creates a instance for the GetDispatchId method. /// /// The for the input struct declaration. + /// Indicates whether or not the shader is dynamic (ie. captures delegates). /// The resulting instance for the GetDispatchId method. - private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol); + private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader); /// /// Creates a instance for the LoadDispatchDataMethod method. @@ -173,13 +176,15 @@ public sealed partial class IShaderGenerator : ISourceGenerator /// The for . /// The implicit texture type, if available (if the shader is a pixel shader). /// Whether or not the current shader type requires a static sampler to be available. + /// The generated HLSL source code (ignoring captured delegates, if present). /// The resulting instance for the BuildHlslString method. private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, out string? implicitTextureType, - out bool isSamplerUsed); + out bool isSamplerUsed, + out string hlslSource); /// /// Creates a instance for the LoadDispatchMetadata method. @@ -194,4 +199,20 @@ public sealed partial class IShaderGenerator : ISourceGenerator IReadOnlyCollection discoveredResources, int root32BitConstantsCount, bool isSamplerUsed); + + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input instance to use. + /// The node to process. + /// The for . + /// Indicates whether or not the shader is dynamic (ie. captures delegates). + /// The generated HLSL source code (ignoring captured delegates, if present). + /// The resulting instance for the BuildHlslString method. + private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod( + GeneratorExecutionContext context, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + bool isDynamicShader, + string hlslSource); }