diff --git a/samples/ComputeSharp.Sample.Shared/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs index 78b04240..b56d467d 100644 --- a/samples/ComputeSharp.Sample.Shared/Program.cs +++ b/samples/ComputeSharp.Sample.Shared/Program.cs @@ -44,7 +44,7 @@ namespace ComputeSharp.Sample [AutoConstructor] internal readonly partial struct MainKernel : IComputeShader { - private readonly ReadWriteBuffer buffer; + public readonly ReadWriteBuffer buffer; /// public void Execute(ThreadIds ids) diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs index 4f1eb61f..ca016a1c 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -12,9 +12,9 @@ namespace ComputeSharp.Shaders.Translation.Models internal readonly ref struct DispatchData { /// - /// The array with the captured buffers. + /// The array (actually values) with the captured buffers. /// - private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray; + private readonly ulong[] resourcesArray; /// /// The number of values in . @@ -34,11 +34,11 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// Creates a new instance with the specified parameters. /// - /// The array with the captured buffers. + /// The array with the captured buffers. /// The number of instances in . /// The array with all the captured variables, with proper padding. /// The actual size in bytes to use from . - public DispatchData(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) + public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) { this.resourcesArray = resourcesArray; this.variablesArray = variablesArray; @@ -54,9 +54,10 @@ namespace ComputeSharp.Shaders.Translation.Models [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); + ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); + ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); - return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount); + return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); } } @@ -79,7 +80,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// public void Dispose() { - ArrayPool.Shared.Return(this.resourcesArray); + ArrayPool.Shared.Return(this.resourcesArray); ArrayPool.Shared.Return(this.variablesArray); } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 40ff7baa..270c40e1 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -1,20 +1,13 @@ -using System.Buffers; +using System; +using System.Buffers; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; -using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Graphics.Interop; -using ComputeSharp.Shaders.Extensions; -using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; -using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; -using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Shaders.Translation { @@ -26,21 +19,19 @@ namespace ComputeSharp.Shaders.Translation /// /// The to use to run the shader. /// The shader instance to load the data from. - /// A reference to the buffer with all the captured instances. + /// + /// A reference to the buffer with all the captured instances. + /// This is just represented as a reference, to avoid exposing the type publicly. + /// /// A reference to the buffer to use to store all the captured value types. - private delegate void DispatchDataLoader(GraphicsDevice device, in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1); + /// The returned value indicates the total number of written bytes into . + private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1); /// /// The number of captured graphics resources (buffers). /// private int totalResourceCount; - /// - /// The size in bytes of the buffer with the captured variables. - /// - /// Initially set to 3 values for X, Y and Z threads counts. - private int totalVariablesByteSize = 3 * sizeof(int); - /// /// The cached instance to load dispatch data before execution. /// @@ -63,10 +54,10 @@ namespace ComputeSharp.Shaders.Translation public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z) { // Resources and variables buffers - D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(this.totalVariablesByteSize); + ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); + byte[] variables = ArrayPool.Shared.Rent(4096); - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources); + ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); // Set the x, y and z counters @@ -75,96 +66,22 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - this.dispatchDataLoader!(device, in shader, ref r0, ref r1); + int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1); - return new(resources, this.totalResourceCount, variables, this.totalVariablesByteSize); + return new(resources, this.totalResourceCount, variables, totalVariablesByteSize); } /// - /// Builds a new instance that loads the dispatch data for the current shader type. + /// Initializes the instance that loads the dispatch data for the current shader type. /// - private void BuildDispatchDataLoader() + private void InitializeDispatchDataLoader() { - // The delegate signature is . - // Due to how DynamicMethod is implemented (see notes in the XML docs for DynamicMethod.New), - // all offsets for the input arguments are shifted by one. Because of this, we have the following: - // - // ldarg.1 = GraphicsDevice - // ldarg.2 = in T shader - // ldarg.3 = ref D3D12_GPU_DESCRIPTOR_HANDLE r0 - // ldarg.4 = ref byte r1 - this.dispatchDataLoader = DynamicMethod.New(il => - { - foreach (FieldInfo fieldInfo in this.capturedFields) - { - if (HlslKnownTypes.IsKnownBufferType(fieldInfo.FieldType)) - { - // Load the offset address into the resource buffers - il.Emit(OpCodes.Ldarg_3); + // Get the generated data loader + Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() }; + Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!; + MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!; - if (totalResourceCount > 0) - { - il.EmitAddOffset(this.totalResourceCount); - } - - il.Emit(OpCodes.Ldarg_2); - il.EmitReadMember(fieldInfo); - - // Call NativeObject.ThrowIfDisposed() - il.Emit(OpCodes.Dup); - il.EmitCall(OpCodes.Callvirt, typeof(NativeObject).GetMethod( - nameof(NativeObject.ThrowIfDisposed), - BindingFlags.Instance | BindingFlags.NonPublic)!, null); - - // Call ThrowIfDeviceMismatch(GraphicsDevice) - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Ldarg_1); - il.EmitCall(OpCodes.Callvirt, fieldInfo.FieldType.GetMethod( - nameof(Buffer.ThrowIfDeviceMismatch), - BindingFlags.Instance | BindingFlags.NonPublic)!, null); - - // Access D3D12GpuDescriptorHandle - il.EmitReadMember(fieldInfo.FieldType.GetField( - nameof(Buffer.D3D12GpuDescriptorHandle), - BindingFlags.Instance | BindingFlags.NonPublic)!); - il.EmitStoreToAddress(typeof(D3D12_GPU_DESCRIPTOR_HANDLE)); - - this.totalResourceCount++; - } - else if (HlslKnownTypes.IsKnownScalarType(fieldInfo.FieldType) || - HlslKnownTypes.IsKnownVectorType(fieldInfo.FieldType)) - { - // Calculate the right offset with 16-bytes padding (HLSL constant buffer) - int elementSizeInBytes = Marshal.SizeOf(fieldInfo.FieldType); - - this.totalVariablesByteSize = AlignmentHelper.AlignToBoundary( - this.totalVariablesByteSize, - elementSizeInBytes, - FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT); - - // Load the target address into the variables buffer - il.Emit(OpCodes.Ldarg_S, (byte)4); - il.EmitAddOffset(totalVariablesByteSize); - - il.Emit(OpCodes.Ldarg_2); - il.EmitReadMember(fieldInfo); - il.EmitStoreToAddress(fieldInfo.FieldType); - - this.totalVariablesByteSize += elementSizeInBytes; - } - else ThrowHelper.ThrowArgumentException("Invalid captured member type"); - } - - il.Emit(OpCodes.Ret); - }); - - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to the standard alignment for constant buffers. This is - // necessary to enable loading all the dispatch data after reinterpreting it to a sequence - // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. - this.totalVariablesByteSize = AlignmentHelper.Pad( - this.totalVariablesByteSize, - FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT); + this.dispatchDataLoader = method.CreateDelegate(); } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index de25b813..92ee855b 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -114,7 +114,7 @@ namespace ComputeSharp.Shaders.Translation @this.LoadFieldsInfo(box); @this.LoadMethodMetadata(); - @this.BuildDispatchDataLoader(); + @this.InitializeDispatchDataLoader(); return @this; } @@ -164,6 +164,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { @@ -172,6 +173,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { @@ -180,6 +182,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index c911e3f7..453a5b40 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -2,7 +2,6 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; -using System.Runtime.CompilerServices; using System.Text; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; @@ -69,6 +68,8 @@ namespace ComputeSharp.SourceGenerators } } + block = block.AddStatements(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1024)))); + // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: // @@ -81,7 +82,7 @@ namespace ComputeSharp.SourceGenerators // { // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] // [System.Obsolete("This method is intended for internal usage only")] - // public static void LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) + // public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) // { // ... // } @@ -98,7 +99,7 @@ namespace ComputeSharp.SourceGenerators Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.PartialKeyword)).AddMembers( MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), + PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier("LoadDispatchData")).AddAttributeLists( AttributeList(SingletonSeparatedList( Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(