diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index 7bc4b50e..73a2a5a9 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -44,10 +44,30 @@ jobs:
run: msbuild -t:restore,build /p:Configuration=Release /p:Platform=x64
shell: cmd
+ # Build the whole ComputeSharp solution with /p:DisableShaderCompilationSupport=True
+ build-solution-release-no-dynamic:
+ runs-on: windows-2022
+ steps:
+ - name: Git checkout
+ uses: actions/checkout@v2
+ - name: Add msbuild to PATH
+ uses: microsoft/setup-msbuild@v1.0.3
+ - name: Setup .NET Core 3.1 SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 3.1.x
+ - name: Setup .NET 6 SDK
+ uses: actions/setup-dotnet@v1
+ with:
+ dotnet-version: 6.0.x
+ - name: Build
+ run: msbuild -t:restore,build /p:Configuration=Release /p:Platform=x64 /p:DisableShaderCompilationSupport=True
+ shell: cmd
+
# Run all the unit tests referencing the ComputeSharp project directly
run-tests:
if: success()
- needs: [build-solution-debug, build-solution-release]
+ needs: [build-solution-debug, build-solution-release, build-solution-release-no-dynamic]
runs-on: windows-2022
steps:
- name: Git checkout
@@ -151,7 +171,7 @@ jobs:
# This workflow also uploads the resulting package as an artifact.
build-package:
if: success()
- needs: [build-solution-debug, build-solution-release]
+ needs: [build-solution-debug, build-solution-release, build-solution-release-no-dynamic]
runs-on: windows-2022
steps:
- name: Git checkout
diff --git a/ComputeSharp.sln b/ComputeSharp.sln
index d4c0b7a6..0327debd 100644
--- a/ComputeSharp.sln
+++ b/ComputeSharp.sln
@@ -84,6 +84,8 @@ Global
src\ComputeSharp.UI\ComputeSharp.UI.projitems*{afaafdc9-be42-45d4-8c79-0ee8c8edbf52}*SharedItemsImports = 5
samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{e7c9247d-016b-4819-af9f-0e9b3591e04b}*SharedItemsImports = 5
samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{e91f4d24-922a-4921-a8d7-9c45a143c45d}*SharedItemsImports = 5
+ src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
+ src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5
src\ComputeSharp.UI\ComputeSharp.UI.projitems*{fa18ba9f-76bf-4de0-8d24-02fc7657e6cb}*SharedItemsImports = 5
samples\ComputeSharp.SwapChain.Core.Shared\ComputeSharp.SwapChain.Core.Shared.projitems*{fbd388a5-7855-4408-98ff-e689f509db5a}*SharedItemsImports = 4
samples\ComputeSharp.SwapChain.Shaders.Shared\ComputeSharp.SwapChain.Shaders.Shared.projitems*{fbd388a5-7855-4408-98ff-e689f509db5a}*SharedItemsImports = 4
diff --git a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj
index 62ed2535..0c8a51df 100644
--- a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj
+++ b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj
@@ -142,7 +142,6 @@
Assets\Textures\RustyMetal.png
PreserveNewest
-
diff --git a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems
index 7c78a112..5e1d264c 100644
--- a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems
+++ b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems
@@ -18,6 +18,7 @@
+
diff --git a/src/ComputeSharp.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs b/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/IsExternalInit.cs
similarity index 54%
rename from src/ComputeSharp.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs
rename to src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/IsExternalInit.cs
index 8c84cb00..a914bf06 100644
--- a/src/ComputeSharp.SourceGenerators/System.Runtime.CompilerServices/IsExternalInit.cs
+++ b/src/ComputeSharp.NetStandard/System/Runtime/CompilerServices/IsExternalInit.cs
@@ -1,8 +1,4 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.ComponentModel;
+using System.ComponentModel;
namespace System.Runtime.CompilerServices;
diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
index 02fa72d6..9507ad4e 100644
--- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
+++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md
@@ -52,3 +52,7 @@ CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentatio
CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0048 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0049 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0050 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
+CMPS0051 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
index c6b670e3..2814dcd1 100644
--- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
+++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj
@@ -4,73 +4,77 @@
netstandard2.0
false
ComputeSharp.SourceGenerators
+ $(NoWarn);CS1591;CS0649
- SOURCE_GENERATOR
+ $(DefineConstants);SOURCE_GENERATOR
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -82,12 +86,23 @@
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/ComputeSharp.SourceGenerators/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp.SourceGenerators/ComputeSharp/Core/Interfaces/__Internals/IShader.cs
similarity index 100%
rename from src/ComputeSharp.SourceGenerators/Core/Interfaces/__Internals/IShader.cs
rename to src/ComputeSharp.SourceGenerators/ComputeSharp/Core/Interfaces/__Internals/IShader.cs
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/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
index c46faa7f..1e5cf347 100644
--- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
+++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs
@@ -630,4 +630,68 @@ internal static class DiagnosticDescriptors
isEnabledByDefault: true,
description: "A shader type cannot implement more than one shader interface.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for a dynamic shader annotated as an embedded bytecode.
+ ///
+ /// Format: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new(
+ id: "CMPS0048",
+ title: "Embedded bytecode for dynamic shader",
+ messageFormat: $"The shader of type {{0}} cannot be precompiled, as it is dynamic (it captures delegate fields)",
+ category: typeof(IShaderGenerator).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "A shader type cannot be precompiled if it captures one or more delegate values.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an embedded bytecode shader with invalid thread ids values.
+ ///
+ /// Format: "The shader of type {0} is annotated with invalid thread ids values ({1}, {2}, {3})".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor InvalidEmbeddedBytecodeThreadIds = new(
+ id: "CMPS0049",
+ title: "Invalid thread ids for shader with embedded bytecode",
+ messageFormat: $"The shader of type {{0}} is annotated with invalid thread ids values ({{1}}, {{2}}, {{3}})",
+ category: typeof(IShaderGenerator).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The thread ids values for a shader marked as embedded bytecode have to be in the valid range.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an embedded bytecode shader failed due to a Win32 exception.
+ ///
+ /// Format: "The shader of type {{0}} failed to compile due to a Win32 exception (HRESULT: {1:X8}, Message: "{2}")".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithWin32Exception = new(
+ id: "CMPS0050",
+ title: "Embedded bytecode compilation failed due to Win32 exception",
+ messageFormat: $"The shader of type {{0}} failed to compile due to a Win32 exception (HRESULT: {{1:X8}}, Message: \"{{2}}\")",
+ category: typeof(IShaderGenerator).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The embedded bytecode for a shader failed to be compiled due to a Win32 exception.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
+
+ ///
+ /// Gets a for an embedded bytecode shader failed due to an HLSL compilation exception.
+ ///
+ /// Format: "The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: "{1}")".
+ ///
+ ///
+ public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithHlslCompilationException = new(
+ id: "CMPS0051",
+ title: "Embedded bytecode compilation failed due to an HLSL compiler error",
+ messageFormat: $"The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: \"{{1}}\")",
+ category: typeof(IShaderGenerator).FullName,
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true,
+ description: "The embedded bytecode for a shader failed to be compiled due to an HLSL compiler error.",
+ helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
}
diff --git a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs
new file mode 100644
index 00000000..1861ee67
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs
@@ -0,0 +1,47 @@
+namespace System;
+
+///
+/// A polyfill type that mirrors some methods from on .NET 6.
+///
+internal struct HashCode
+{
+ ///
+ /// Combines six values into a hash code.
+ ///
+ /// The type of the first value to combine into the hash code.
+ /// The type of the second value to combine into the hash code.
+ /// The type of the third value to combine into the hash code.
+ /// The type of the fourth value to combine into the hash code.
+ /// The type of the fifth value to combine into the hash code.
+ /// The type of the sixth value to combine into the hash code.
+ /// The first value to combine into the hash code.
+ /// The second value to combine into the hash code.
+ /// The third value to combine into the hash code.
+ /// The fourth value to combine into the hash code.
+ /// The fifth value to combine into the hash code.
+ /// The sixth value to combine into the hash code.
+ /// The hash code that represents the six values.
+ public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6)
+ {
+ throw new NotSupportedException();
+ }
+
+ ///
+ /// Adds a single value to the hash code.
+ ///
+ /// The type of the value to add to the hash code.
+ /// The value to add to the hash code.
+ public void Add(T value)
+ {
+ throw new NotSupportedException();
+ }
+
+ ///
+ /// Calculates the final hash code after consecutive invocations.
+ ///
+ /// The calculated hash code.
+ public int ToHashCode()
+ {
+ throw new NotSupportedException();
+ }
+}
\ No newline at end of file
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
new file mode 100644
index 00000000..78e78d53
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs
@@ -0,0 +1,322 @@
+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 ComputeSharp.SourceGenerators.Diagnostics;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
+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,
+ INamedTypeSymbol structDeclarationSymbol,
+ bool isDynamicShader,
+ string hlslSource,
+ out string? bytecodeLiterals)
+ {
+ // 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(context, structDeclarationSymbol, isDynamicShader, hlslSource, out bytecodeLiterals));
+ }
+
+ ///
+ /// Gets a instance with the logic to try to get a compiled shader bytecode.
+ ///
+ /// The current generator context in use.
+ /// 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 resulting bytecode literals to insert into the final source code.
+ /// The instance to hash the input shader.
+ [Pure]
+ private static unsafe BlockSyntax GetShaderBytecodeBody(
+ GeneratorExecutionContext context,
+ INamedTypeSymbol structDeclarationSymbol,
+ bool isDynamicShader,
+ string hlslSource,
+ out string? bytecodeLiterals)
+ {
+ AttributeData? attribute = structDeclarationSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(EmbeddedBytecodeAttribute) });
+
+ // No embedded shader was requested
+ if (attribute is null)
+ {
+ goto Failure;
+ }
+
+ // If the current shader is dynamic, emit a diagnostic error
+ if (isDynamicShader)
+ {
+ context.ReportDiagnostic(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
+
+ goto Failure;
+ }
+
+ // 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)
+ {
+ context.ReportDiagnostic(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol);
+
+ goto Failure;
+ }
+
+ try
+ {
+ // Try to load dxcompiler.dll and dxil.dll
+ LoadNativeDxcLibraries();
+
+ // 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());
+
+ // Build and set the text with the literal expressions
+ bytecodeLiterals = BuildShaderBytecodeExpressionString(new ReadOnlySpan(buffer, length));
+
+ // This code produces a method declaration as follows:
+ //
+ // if (threadsX == && threadsY == && threadsZ == )
+ // {
+ // bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
+ //
+ // return true;
+ // }
+ //
+ // bytecode = default;
+ //
+ // return false;
+ //
+ // 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.
+ 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"),
+ ArrayCreationExpression(
+ ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
+ .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression()))))
+ .WithInitializer(
+ InitializerExpression(
+ SyntaxKind.ArrayInitializerExpression,
+ SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))),
+ ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
+ ExpressionStatement(
+ AssignmentExpression(
+ SyntaxKind.SimpleAssignmentExpression,
+ IdentifierName("bytecode"),
+ LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
+ ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
+ }
+ catch (Win32Exception e)
+ {
+ context.ReportDiagnostic(
+ EmbeddedBytecodeFailedWithWin32Exception,
+ structDeclarationSymbol,
+ structDeclarationSymbol,
+ e.HResult,
+ e.Message);
+ }
+ catch (HlslCompilationException e)
+ {
+ context.ReportDiagnostic(
+ EmbeddedBytecodeFailedWithHlslCompilationException,
+ structDeclarationSymbol,
+ structDeclarationSymbol,
+ e.Message);
+ }
+
+ Failure:
+ bytecodeLiterals = 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)));
+ }
+
+ ///
+ /// Extracts and loads the dxcompiler.dll and dxil.dll libraries.
+ ///
+ /// Thrown if the CPU architecture is not supported.
+ /// Thrown if a library fails to load.
+ private static void LoadNativeDxcLibraries()
+ {
+ // Extracts a specified native library for a given runtime identifier
+ static string ExtractLibrary(string rid, string name)
+ {
+ 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);
+
+ try
+ {
+ using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write);
+
+ sourceStream.CopyTo(destinationStream);
+ }
+ catch (IOException)
+ {
+ }
+
+ return targetFilename;
+ }
+
+ // Loads a target native library
+ static unsafe void LoadLibrary(string filename)
+ {
+ [DllImport("kernel32", ExactSpelling = true, SetLastError = true)]
+ static extern void* LoadLibraryW(ushort* lpLibFileName);
+
+ fixed (char* p = filename)
+ {
+ if (LoadLibraryW((ushort*)p) is null)
+ {
+ int hresult = Marshal.GetLastWin32Error();
+
+ throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}.");
+ }
+ }
+ }
+
+ 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;
+ }
+
+ ///
+ /// A mapping of precomputed literals for all values.
+ ///
+ private static readonly string[] formattedBytes =
+ {
+ "0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
+ "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
+ "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
+ "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
+ "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
+ "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
+ "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
+ "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
+ "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
+ "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
+ "0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
+ "0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
+ "0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
+ "0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
+ "0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
+ "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
+ };
+
+ ///
+ /// Creates a formatted expression to initialize a with a given shader data.
+ ///
+ /// The input shader bytecode to serialize.
+ /// A formatted with the serialized data.
+ private static string BuildShaderBytecodeExpressionString(ReadOnlySpan 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);
+
+ builder.Append(formattedBytes[bytecode[0]]);
+
+ foreach (byte b in bytecode.Slice(1))
+ {
+ builder.Append(", ");
+ builder.Append(formattedBytes[b]);
+ }
+
+ return builder.WrittenSpan.ToString();
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
index c89752f1..cf231bf6 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, structDeclarationSymbol, isDynamicShader, hlslSource, out string? bytecodeLiterals);
// 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
@@ -140,6 +142,12 @@ public sealed partial class IShaderGenerator : ISourceGenerator
.NormalizeWhitespace(eol: "\n")
.ToFullString();
+ // Insert the bytecode literals, if needed
+ if (bytecodeLiterals is not null)
+ {
+ source = source.Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
+ }
+
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
@@ -148,8 +156,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 +182,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 +205,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 for the shader type.
+ /// Indicates whether or not the shader is dynamic (ie. captures delegates).
+ /// The generated HLSL source code (ignoring captured delegates, if present).
+ /// The resulting bytecode literals to insert into the final source code.
+ /// The resulting instance for the BuildHlslString method.
+ private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod(
+ GeneratorExecutionContext context,
+ INamedTypeSymbol structDeclarationSymbol,
+ bool isDynamicShader,
+ string hlslSource,
+ out string? bytecodeLiterals);
}
diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj
index 4c8128dc..e97405a8 100644
--- a/src/ComputeSharp/ComputeSharp.csproj
+++ b/src/ComputeSharp/ComputeSharp.csproj
@@ -5,6 +5,7 @@
ComputeSharp.xml
ComputeSharp
AnyCPU;x64;ARM64
+ false
@@ -37,8 +38,16 @@
$(NoWarn);CS1591
+
+
+ $(DefineConstants);DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
+
+
+
+
+
diff --git a/src/ComputeSharp/Core/Attributes/EmbeddedBytecodeAttribute.cs b/src/ComputeSharp/Core/Attributes/EmbeddedBytecodeAttribute.cs
new file mode 100644
index 00000000..8dbbf759
--- /dev/null
+++ b/src/ComputeSharp/Core/Attributes/EmbeddedBytecodeAttribute.cs
@@ -0,0 +1,58 @@
+using System;
+
+namespace ComputeSharp;
+
+///
+/// An attribute that indicates that a given shader should be precompiled at build time and embedded
+/// directly into the containing assembly as static bytecode, to avoid compiling it at runtime.
+///
+/// This attribute can be used to annotate shader types as follows:
+///
+/// [EmbeddedBytecode(8, 8, 1)]
+/// struct MyShader : IComputeShader
+/// {
+/// }
+///
+///
+///
+/// This attribute can only be used when the shader type being annotated does not require dynamic
+/// features. Specifically, this attribute is not supported if the shader captures any delegates.
+///
+/// The runtime compilation will automatically be skipped if the shader is invoked using matching
+/// thread count values, otherwise the usual runtime compilation will be used as fallback. In case
+/// the fallback support is not needed and all shaders in use are being precompiled, it is possible
+/// to skip bundling the native dxcompiler.dll and dxil.dll libraries included with
+/// ComputeSharp entirely, resulting in a smaller binary size in consuming applications. To do this,
+/// the PackageReference item for the library should be annotated with ExcludeAssets="native".
+///
+[AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)]
+public sealed class EmbeddedBytecodeAttribute : Attribute
+{
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The number of threads in each thread group for the X axis.
+ /// The number of threads in each thread group for the Y axis.
+ /// The number of threads in each thread group for the Z axis.
+ public EmbeddedBytecodeAttribute(int threadsX, int threadsY, int threadsZ)
+ {
+ ThreadsX = threadsX;
+ ThreadsY = threadsY;
+ ThreadsZ = threadsZ;
+ }
+
+ ///
+ /// Gets the number of threads in each thread group for the X axis
+ ///
+ public int ThreadsX { get; init; }
+
+ ///
+ /// Gets the number of threads in each thread group for the Y axis
+ ///
+ public int ThreadsY { get; init; }
+
+ ///
+ /// Gets the number of threads in each thread group for the Z axis
+ ///
+ public int ThreadsZ { get; init; }
+}
diff --git a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs
index 5534928a..8193efc6 100644
--- a/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs
+++ b/src/ComputeSharp/Core/Interfaces/__Internals/IShader.cs
@@ -81,4 +81,24 @@ public interface IShader
#else
;
#endif
+
+ ///
+ /// Tries to retrieve the precompiled bytecode for the current shader.
+ ///
+ /// The number of threads in each thread group for the X axis.
+ /// The number of threads in each thread group for the Y axis.
+ /// The number of threads in each thread group for the Z axis.
+ /// The resulting bytecode, if found.
+ /// Whether or not a precompiled bytecode was found.
+ /// The underlying buffer for , if found, can be assumed to always be pinned.
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [Obsolete("This method is not intended to be used directly by user code")]
+ bool TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan bytecode)
+#if NET6_0_OR_GREATER
+ {
+ throw new NotImplementedException();
+ }
+#else
+ ;
+#endif
}
diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs
index 2d9467c4..c54769da 100644
--- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs
+++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs
@@ -1,10 +1,18 @@
using System;
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
using System.Runtime.CompilerServices;
+#endif
using ComputeSharp.__Internals;
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
using ComputeSharp.Core.Extensions;
using ComputeSharp.Shaders.Translation;
+#else
+using Microsoft.Toolkit.Diagnostics;
+#endif
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
+#endif
#pragma warning disable CS0618
@@ -102,6 +110,11 @@ public static class ReflectionServices
private static unsafe void GetNonGenericShaderInfo(in T shader, out ShaderInfo shaderInfo)
where T : struct, IShader
{
+#if DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
+ ThrowHelper.ThrowNotSupportedException("Runtime shader compilation is not supported by the current configuration.");
+
+ shaderInfo = default;
+#else
Unsafe.AsRef(in shader).BuildHlslString(out ArrayPoolStringBuilder shaderSource, 1, 1, 1);
using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(shaderSource.WrittenSpan);
@@ -155,5 +168,6 @@ public static class ReflectionServices
Unsafe.AsRef(shaderInfo.MovcInstructionCount) = d3D12ShaderReflection.Get()->GetMovcInstructionCount();
Unsafe.AsRef(shaderInfo.MovInstructionCount) = d3D12ShaderReflection.Get()->GetMovInstructionCount();
Unsafe.AsRef(shaderInfo.InterfaceSlotCount) = d3D12ShaderReflection.Get()->GetNumInterfaceSlots();
+#endif
}
}
diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs
index a86d812e..3f9d462a 100644
--- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs
+++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs
@@ -4,7 +4,9 @@ using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Commands;
using ComputeSharp.Shaders.Dispatching;
using ComputeSharp.Shaders.Extensions;
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
using ComputeSharp.Shaders.Translation;
+#endif
using ComputeSharp.Shaders.Translation.Models;
using ComputeSharp.__Internals;
using Microsoft.Toolkit.Diagnostics;
@@ -25,7 +27,7 @@ internal static class ShaderRunner
///
/// The mapping used to cache and reuse compiled shaders.
///
- private static readonly Dictionary ShadersCache = new();
+ private static readonly Dictionary ShadersCache = new();
///
/// Compiles and runs the input shader on a target instance, with the specified parameters.
@@ -129,7 +131,7 @@ internal static class ShaderRunner
lock (ShadersCache)
{
// Get or preload the shader
- if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData))
+ if (!ShadersCache.TryGetValue(key, out ICachedShader? shaderData))
{
LoadShader(threadsX, threadsY, threadsZ, ref shader, out shaderData);
@@ -183,7 +185,7 @@ internal static class ShaderRunner
lock (ShadersCache)
{
// Get or preload the shader
- if (!ShadersCache.TryGetValue(key, out CachedShader? shaderData))
+ if (!ShadersCache.TryGetValue(key, out ICachedShader? shaderData))
{
LoadShader(threadsX, threadsY, 1, ref shader, out shaderData);
@@ -222,27 +224,40 @@ internal static class ShaderRunner
/// The number of threads in each thread group for the Y axis.
/// The number of threads in each thread group for the Z axis.
/// The input instance representing the compute shader to run.
- /// The instance to return with the cached shader data.
+ /// The instance to return with the cached shader data.
[MethodImpl(MethodImplOptions.NoInlining)]
- private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, ref T shader, out CachedShader shaderData)
+ private static unsafe void LoadShader(int threadsX, int threadsY, int threadsZ, ref T shader, out ICachedShader shaderData)
{
- shader.BuildHlslString(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ);
+ if (shader.TryGetBytecode(threadsX, threadsY, threadsZ, out ReadOnlySpan bytecode))
+ {
+ shaderData = new ICachedShader.Embedded(bytecode);
+ }
+ else
+ {
+#if DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
+ ThrowHelper.ThrowNotSupportedException("Runtime shader compilation is not supported by the current configuration.");
- using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan);
+ shaderData = null!;
+#else
+ shader.BuildHlslString(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ);
- builder.Dispose();
+ using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(builder.WrittenSpan);
- shaderData = new CachedShader(dxcBlobBytecode.Get());
+ builder.Dispose();
+
+ shaderData = new ICachedShader.Dynamic(dxcBlobBytecode.Get());
+#endif
+ }
}
///
/// Creates and caches a instance for a given shader.
///
/// The to use to run the shader.
- /// The instance with the data on the loaded shader.
+ /// The instance with the data on the loaded shader.
/// The resulting instance to use to run the shader.
[MethodImpl(MethodImplOptions.NoInlining)]
- private static unsafe void CreatePipelineData(GraphicsDevice device, CachedShader shaderData, out PipelineData pipelineData)
+ private static unsafe void CreatePipelineData(GraphicsDevice device, ICachedShader shaderData, out PipelineData pipelineData)
{
using ComPtr d3D12RootSignature = default;
diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs
deleted file mode 100644
index 2afec884..00000000
--- a/src/ComputeSharp/Shaders/Translation/Models/CachedShader.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System.Runtime.CompilerServices;
-using ComputeSharp.Graphics.Commands;
-using ComputeSharp.Interop;
-using TerraFX.Interop.DirectX;
-using TerraFX.Interop.Windows;
-
-namespace ComputeSharp.Shaders.Translation.Models;
-
-///
-/// A class that contains info on a cached shader.
-///
-internal sealed unsafe class CachedShader : NativeObject
-{
- ///
- /// The instance currently in use.
- ///
- private ComPtr dxcBlobBytecode;
-
- ///
- /// Creates a new instance with the specified parameters.
- ///
- /// The bytecode instance to wrap.
- public CachedShader(IDxcBlob* dxcBlobBytecode)
- {
- this.dxcBlobBytecode = new ComPtr(dxcBlobBytecode);
- }
-
- ///
- /// Gets the map of cached instances for each GPU in use.
- ///
- public ConditionalWeakTable CachedPipelines { get; } = new();
-
- ///
- /// Gets a raw pointer to the instance in use.
- ///
- public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new((ID3DBlob*)this.dxcBlobBytecode.Get());
-
- ///
- protected override void OnDispose()
- {
- this.dxcBlobBytecode.Dispose();
- }
-}
diff --git a/src/ComputeSharp/Shaders/Translation/Models/ICachedShader.cs b/src/ComputeSharp/Shaders/Translation/Models/ICachedShader.cs
new file mode 100644
index 00000000..309f0de2
--- /dev/null
+++ b/src/ComputeSharp/Shaders/Translation/Models/ICachedShader.cs
@@ -0,0 +1,95 @@
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using ComputeSharp.Graphics.Commands;
+using ComputeSharp.Interop;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+
+namespace ComputeSharp.Shaders.Translation.Models;
+
+///
+/// An interface that contains info on a cached shader.
+///
+internal interface ICachedShader
+{
+ ///
+ /// Gets the map of cached instances for each GPU in use.
+ ///
+ ConditionalWeakTable CachedPipelines { get; }
+
+ ///
+ /// Gets a value pointing shader bytecode to use.
+ ///
+ D3D12_SHADER_BYTECODE D3D12ShaderBytecode { get; }
+
+ ///
+ /// An implementation for an embedded shader.
+ ///
+ public sealed unsafe class Embedded : ICachedShader
+ {
+ ///
+ /// The bytecode buffer, if a precompiled shader is used.
+ ///
+ private readonly byte* precompiledBytecodeBuffer;
+
+ ///
+ /// The buffer size for , if present.
+ ///
+ private readonly uint precompiledBytecodeSize;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The shader bytecode buffer to wrap.
+ ///
+ /// It is assumed that is a static binary block in the .text segment of the
+ /// PE file, which is what Roslyn generates when directly assigning a new array to a . As such,
+ /// the underlying buffer is assumed to be pinned, and it will not be properly tracked for GC compactions. If an invalid
+ /// buffer is passed and its contents are moved, the behavior is undefined (access violations will most definitely occurr).
+ ///
+ public Embedded(ReadOnlySpan precompiledBytecode)
+ {
+ this.precompiledBytecodeBuffer = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(precompiledBytecode));
+ this.precompiledBytecodeSize = (uint)precompiledBytecode.Length;
+ }
+
+ ///
+ public ConditionalWeakTable CachedPipelines { get; } = new();
+
+ ///
+ public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new(this.precompiledBytecodeBuffer, this.precompiledBytecodeSize);
+ }
+
+ ///
+ /// An implementation for a dynamically compiled shader.
+ ///
+ public sealed unsafe class Dynamic : NativeObject, ICachedShader
+ {
+ ///
+ /// The instance currently in use.
+ ///
+ private ComPtr dxcBlobBytecode;
+
+ ///
+ /// Creates a new instance with the specified parameters.
+ ///
+ /// The bytecode instance to wrap.
+ public Dynamic(IDxcBlob* dxcBlobBytecode)
+ {
+ this.dxcBlobBytecode = new ComPtr(dxcBlobBytecode);
+ }
+
+ ///
+ public ConditionalWeakTable CachedPipelines { get; } = new();
+
+ ///
+ public D3D12_SHADER_BYTECODE D3D12ShaderBytecode => new ((ID3DBlob*)this.dxcBlobBytecode.Get());
+
+ ///
+ protected override void OnDispose()
+ {
+ this.dxcBlobBytecode.Dispose();
+ }
+ }
+}
diff --git a/src/ComputeSharp/Shaders/Translation/ShaderCompiler.LibraryLoading.cs b/src/ComputeSharp/Shaders/Translation/ShaderCompiler.LibraryLoading.cs
index 52bf32ff..efd62ed7 100644
--- a/src/ComputeSharp/Shaders/Translation/ShaderCompiler.LibraryLoading.cs
+++ b/src/ComputeSharp/Shaders/Translation/ShaderCompiler.LibraryLoading.cs
@@ -1,4 +1,4 @@
-#if NET6_0_OR_GREATER
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT && NET6_0_OR_GREATER
using System;
using System.IO;
diff --git a/src/ComputeSharp/Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp/Shaders/Translation/ShaderCompiler.cs
index 21da886d..63de1f27 100644
--- a/src/ComputeSharp/Shaders/Translation/ShaderCompiler.cs
+++ b/src/ComputeSharp/Shaders/Translation/ShaderCompiler.cs
@@ -1,4 +1,6 @@
-using System;
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
+
+using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Core.Extensions;
@@ -153,3 +155,5 @@ internal sealed unsafe partial class ShaderCompiler
throw new HlslCompilationException(message);
}
}
+
+#endif
diff --git a/src/TerraFX.Interop.Windows/DirectX/um/dxcapi/DirectX.cs b/src/TerraFX.Interop.Windows/DirectX/um/dxcapi/DirectX.cs
index 0963b55b..0448fa06 100644
--- a/src/TerraFX.Interop.Windows/DirectX/um/dxcapi/DirectX.cs
+++ b/src/TerraFX.Interop.Windows/DirectX/um/dxcapi/DirectX.cs
@@ -3,6 +3,8 @@
// Ported from um/dxcapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved. Licensed under the University of Illinois Open Source License.
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
+
using System;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
@@ -15,3 +17,5 @@ namespace TerraFX.Interop.DirectX
public static extern HRESULT DxcCreateInstance([NativeTypeName("const IID &")] Guid* rclsid, [NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("LPVOID *")] void** ppv);
}
}
+
+#endif
diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj
index bb8d58fb..190815c1 100644
--- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj
+++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj
@@ -4,6 +4,12 @@
net472;netcoreapp3.1;net6.0
false
AnyCPU;x64;ARM64
+ false
+
+
+
+
+ $(DefineConstants);DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
diff --git a/tests/ComputeSharp.Tests.Internals/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderCompilerTests.cs
index e563da4a..0c10427f 100644
--- a/tests/ComputeSharp.Tests.Internals/ShaderCompilerTests.cs
+++ b/tests/ComputeSharp.Tests.Internals/ShaderCompilerTests.cs
@@ -1,4 +1,6 @@
-using System;
+#if !DISABLE_RUNTIME_SHADER_COMPILATION_SUPPORT
+
+using System;
using ComputeSharp.Exceptions;
using ComputeSharp.Shaders.Translation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -45,3 +47,5 @@ public class ShaderCompilerTests
using ComPtr dxcBlob = ShaderCompiler.Instance.CompileShader(faultyShader.AsSpan());
}
}
+
+#endif
diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs
index f956aeea..0092a1ae 100644
--- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs
+++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs
@@ -1399,6 +1399,76 @@ public class DiagnosticsTests
VerifyGeneratedDiagnostics(source, "CMPS0047");
}
+ [TestMethod]
+ public void EmbeddedBytecodeWithDynamicShader()
+ {
+ string source = @"
+ using System;
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {
+ public interface IComputeShader { }
+ public class ReadWriteBuffer { }
+ public class EmbeddedBytecodeAttribute : Attribute { }
+ }
+
+ namespace MyFancyApp.Sample
+ {
+ [EmbeddedBytecode]
+ public struct MyShader : IComputeShader
+ {
+ public ReadWriteBuffer buffer;
+ public Action action;
+
+ public void Execute()
+ {
+ }
+ }
+ }";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0048");
+ }
+
+ [TestMethod]
+ [DataRow(-1, 1, 1)]
+ [DataRow(1, -1, 1)]
+ [DataRow(1, 1, -1)]
+ [DataRow(1050, 1, 1)]
+ [DataRow(1, 1050, 1)]
+ [DataRow(1, 1, 70)]
+ public void InvalidEmbeddedBytecodeThreadIds(int threadsX, int threadsY, int threadsZ)
+ {
+ string source = $@"
+ using System;
+ using ComputeSharp;
+
+ namespace ComputeSharp
+ {{
+ public interface IComputeShader {{ }}
+ public class ReadWriteBuffer {{ }}
+ public class EmbeddedBytecodeAttribute : Attribute
+ {{
+ public EmbeddedBytecodeAttribute(int threadsX, int threadsY, int threadsZ) {{ }}
+ }}
+ }}
+
+ namespace MyFancyApp.Sample
+ {{
+ [EmbeddedBytecode({threadsX}, {threadsY}, {threadsZ})]
+ public struct MyShader : IComputeShader
+ {{
+ public ReadWriteBuffer buffer;
+
+ public void Execute()
+ {{
+ }}
+ }}
+ }}";
+
+ VerifyGeneratedDiagnostics(source, "CMPS0049");
+ }
+
///
/// Verifies the output of a source generator.
///