From e0b2c6a9fde77235da202e516d2c83fca56d4d75 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 17 Oct 2023 03:11:44 +0200 Subject: [PATCH] Switch to CsWin32 for DXC APIs in D3D12 generator --- ComputeSharp.sln | 2 - .../Primitives/Internals/UndefinedData.cs | 11 ++- .../ComputeSharp.SourceGenerators.csproj | 7 +- .../Dxc/DxcShaderCompiler.cs | 75 +++++++++---------- .../Dxc/Interop/ComPtr{T}.cs | 62 +++++++++++++++ .../NativeMethods.json | 10 +++ .../NativeMethods.txt | 7 ++ 7 files changed, 121 insertions(+), 53 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Dxc/Interop/ComPtr{T}.cs create mode 100644 src/ComputeSharp.SourceGenerators/NativeMethods.json create mode 100644 src/ComputeSharp.SourceGenerators/NativeMethods.txt diff --git a/ComputeSharp.sln b/ComputeSharp.sln index e3be080b..1a592848 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -495,10 +495,8 @@ Global src\ComputeSharp.Win32.D2D1\ComputeSharp.Win32.D2D1.projitems*{e44053bd-a761-47fb-aa78-087a599672ea}*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\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 - src\ComputeSharp.Win32.D3D12\ComputeSharp.Win32.D3D12.projitems*{eb52cb67-4162-4722-874b-44ea8da5450e}*SharedItemsImports = 5 samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{f8bf7666-7ccf-4fe4-b055-2eba4bcd4564}*SharedItemsImports = 13 EndGlobalSection EndGlobal diff --git a/src/ComputeSharp.Core/Primitives/Internals/UndefinedData.cs b/src/ComputeSharp.Core/Primitives/Internals/UndefinedData.cs index 6e25e4ac..1659d4db 100644 --- a/src/ComputeSharp.Core/Primitives/Internals/UndefinedData.cs +++ b/src/ComputeSharp.Core/Primitives/Internals/UndefinedData.cs @@ -1,7 +1,5 @@ -#if NET6_0_OR_GREATER +#if !SOURCE_GENERATOR using System.Runtime.CompilerServices; -#else -using RuntimeHelpers = ComputeSharp.NetStandard.RuntimeHelpers; #endif namespace ComputeSharp; @@ -15,5 +13,10 @@ internal static class UndefinedData /// /// The shared memory with undefined data (has size of , as it's the maximum needed at once). /// - public static readonly unsafe void* Memory = (void*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(UndefinedData), sizeof(Double4)); + public static readonly unsafe void* Memory = +#if SOURCE_GENERATOR + null; +#else + (void*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(UndefinedData), sizeof(Double4)); +#endif } diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 66666ac9..63332f06 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -70,6 +70,7 @@ + @@ -88,12 +89,6 @@ - - - - - - diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs index 9360ef72..d3980d85 100644 --- a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs +++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs @@ -1,10 +1,11 @@ using System; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Threading; -using TerraFX.Interop.DirectX; -using TerraFX.Interop.Windows; +using ComputeSharp.SourceGenerators.Dxc.Interop; +using Windows.Win32; +using Windows.Win32.Foundation; +using Windows.Win32.Graphics.Direct3D.Dxc; namespace ComputeSharp.SourceGenerators.Dxc; @@ -42,19 +43,20 @@ internal sealed unsafe class DxcShaderCompiler { using ComPtr dxcCompiler = default; using ComPtr dxcLibrary = default; + + _ = PInvoke.DxcCreateInstance( + PInvoke.CLSID_DxcCompiler, + IDxcCompiler.IID_Guid, + out *(void**)dxcCompiler.GetAddressOf()).ThrowOnFailure(); + + _ = PInvoke.DxcCreateInstance( + PInvoke.CLSID_DxcLibrary, + IDxcLibrary.IID_Guid, + out *(void**)dxcLibrary.GetAddressOf()).ThrowOnFailure(); + using ComPtr dxcIncludeHandler = default; - Marshal.ThrowExceptionForHR(DirectX.DxcCreateInstance( - (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcCompiler)), - Windows.__uuidof(), - (void**)dxcCompiler.GetAddressOf())); - - Marshal.ThrowExceptionForHR(DirectX.DxcCreateInstance( - (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_DxcLibrary)), - Windows.__uuidof(), - (void**)dxcLibrary.GetAddressOf())); - - Marshal.ThrowExceptionForHR(dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf())); + _ = dxcLibrary.Get()->CreateIncludeHandler(dxcIncludeHandler.GetAddressOf()).ThrowOnFailure(); this.dxcCompiler = new ComPtr(dxcCompiler.Get()); this.dxcLibrary = new ComPtr(dxcLibrary.Get()); @@ -90,54 +92,45 @@ internal sealed unsafe class DxcShaderCompiler // Get the encoded blob from the source code fixed (char* p = source) { - int hresult = this.dxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy( - p, - (uint)source.Length * 2, - 1200, - dxcBlobEncoding.GetAddressOf()); - - Marshal.ThrowExceptionForHR(hresult); + _ = this.dxcLibrary.Get()->CreateBlobWithEncodingOnHeapCopy( + pText: p, + size: (uint)source.Length * 2, + codePage: DXC_CP.DXC_CP_UTF16, + pBlobEncoding: dxcBlobEncoding.GetAddressOf()).ThrowOnFailure(); } token.ThrowIfCancellationRequested(); // Try to compile the new compute shader - fixed (char* shaderName = "") - fixed (char* entryPoint = nameof(IComputeShader.Execute)) - fixed (char* shaderProfile = "cs_6_0") fixed (char* optimization = "-O3") fixed (char* rowMajor = "-Zpr") fixed (char* warningsAsErrors = "-Werror") { - char** arguments = stackalloc char*[3] { optimization, rowMajor, warningsAsErrors }; + Span arguments = stackalloc PCWSTR[] { optimization, rowMajor, warningsAsErrors }; - int hresult = this.dxcCompiler.Get()->Compile( - (IDxcBlob*)dxcBlobEncoding.Get(), - (ushort*)shaderName, - (ushort*)entryPoint, - (ushort*)shaderProfile, - (ushort**)arguments, - 3, - null, - 0, - this.dxcIncludeHandler.Get(), - dxcOperationResult.GetAddressOf()); - - Marshal.ThrowExceptionForHR(hresult); + _ = this.dxcCompiler.Get()->Compile( + pSource: (IDxcBlob*)dxcBlobEncoding.Get(), + pSourceName: "", + pEntryPoint: "Execute", + pTargetProfile: "cs_6_0", + pArguments: arguments, + pDefines: ReadOnlySpan.Empty, + pIncludeHandler: this.dxcIncludeHandler.Get(), + ppResult: dxcOperationResult.GetAddressOf()).ThrowOnFailure(); } token.ThrowIfCancellationRequested(); HRESULT status; - Marshal.ThrowExceptionForHR(dxcOperationResult.Get()->GetStatus(&status)); + _ = dxcOperationResult.Get()->GetStatus(&status).ThrowOnFailure(); // The compilation was successful, so we can extract the shader bytecode if (status == 0) { using ComPtr dxcBlobBytecode = default; - Marshal.ThrowExceptionForHR(dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf())); + _ = dxcOperationResult.Get()->GetResult(dxcBlobBytecode.GetAddressOf()).ThrowOnFailure(); byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); @@ -158,7 +151,7 @@ internal sealed unsafe class DxcShaderCompiler { using ComPtr dxcBlobEncodingError = default; - Marshal.ThrowExceptionForHR(dxcOperationResult->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf())); + _ = dxcOperationResult->GetErrorBuffer(dxcBlobEncodingError.GetAddressOf()).ThrowOnFailure(); string message = new((sbyte*)dxcBlobEncodingError.Get()->GetBufferPointer()); diff --git a/src/ComputeSharp.SourceGenerators/Dxc/Interop/ComPtr{T}.cs b/src/ComputeSharp.SourceGenerators/Dxc/Interop/ComPtr{T}.cs new file mode 100644 index 00000000..c4789ba6 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Dxc/Interop/ComPtr{T}.cs @@ -0,0 +1,62 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from winrt/wrl/client.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using Windows.Win32.System.Com; + +namespace ComputeSharp.SourceGenerators.Dxc.Interop; + +/// A type that allows working with pointers to COM objects more securely. +/// The type to wrap in the current instance. +internal unsafe struct ComPtr : IDisposable + where T : unmanaged +{ + /// The raw pointer to a COM object, if existing. + private T* ptr; + + /// Creates a new instance from a raw pointer and increments the ref count. + /// The raw pointer to wrap. + public ComPtr(T* other) + { + this.ptr = other; + + if (other is not null) + { + _ = ((IUnknown*)other)->AddRef(); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() + { + T* pointer = this.ptr; + + if (pointer is not null) + { + this.ptr = null; + + _ = ((IUnknown*)pointer)->Release(); + } + } + + /// Gets the currently wrapped raw pointer to a COM object. + /// The raw pointer wrapped by the current instance. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly T* Get() + { + return this.ptr; + } + + /// Gets the address of the current instance as a raw double pointer. This method is only valid when the current instance is on the stack or pinned. + /// + /// The raw pointer to the current instance. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public readonly T** GetAddressOf() + { + return (T**)Unsafe.AsPointer(ref Unsafe.AsRef(in this)); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/NativeMethods.json b/src/ComputeSharp.SourceGenerators/NativeMethods.json new file mode 100644 index 00000000..f491f43c --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/NativeMethods.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://aka.ms/CsWin32.schema.json", + "allowMarshaling": false, + "useSafeHandles": false, + "comInterop": { + "preserveSigMethods": [ + "*" + ] + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/NativeMethods.txt b/src/ComputeSharp.SourceGenerators/NativeMethods.txt new file mode 100644 index 00000000..396fba96 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/NativeMethods.txt @@ -0,0 +1,7 @@ +CLSID_DxcCompiler +CLSID_DxcLibrary +DxcCreateInstance +IDxcCompiler +IDxcLibrary +IDxcIncludeHandler +IUnknown \ No newline at end of file