Merge pull request #81 from Sergio0694/feature/dynamic-IL-to-source-generator

Dynamic IL to source generator
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2020-12-29 23:58:12 +01:00
コミット 918926f8e0
28ファイル変更
+716 -644

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

+8 -8
ファイルの表示
@@ -73,15 +73,15 @@ namespace ComputeSharp.Benchmark
/// Kernel for <see cref="FullyConnectedForwardGpu"/>.
/// </summary>
[AutoConstructor]
private readonly partial struct FullyConnectedForwardKernel : IComputeShader
public readonly partial struct FullyConnectedForwardKernel : IComputeShader
{
private readonly int n;
private readonly int m;
private readonly int p;
private readonly ReadOnlyBuffer<float> x;
private readonly ReadOnlyBuffer<float> w;
private readonly ReadOnlyBuffer<float> b;
private readonly ReadWriteBuffer<float> y;
public readonly int n;
public readonly int m;
public readonly int p;
public readonly ReadOnlyBuffer<float> x;
public readonly ReadOnlyBuffer<float> w;
public readonly ReadOnlyBuffer<float> b;
public readonly ReadWriteBuffer<float> y;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
+85 -2
ファイルの表示
@@ -1,4 +1,5 @@
using SixLabors.ImageSharp;
using System.Numerics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
@@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors
/// <summary>
/// Applies bokeh blur processing to the image.
/// </summary>
public sealed class HlslBokehBlurProcessor : IImageProcessor
public sealed partial class HlslBokehBlurProcessor : IImageProcessor
{
/// <summary>
/// The default radius used by the parameterless constructor.
@@ -63,5 +64,87 @@ namespace ComputeSharp.BokehBlur.Processors
{
return new HlslBokehBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct VerticalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadOnlyBuffer<Vector4> source;
public ReadWriteBuffer<ComplexVector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
Complex64 factors = kernel[i];
real += factors.Real * color;
imaginary += factors.Imaginary * color;
}
int offsetXY = ids.Y * width + ids.X;
target[offsetXY].Real = real;
target[offsetXY].Imaginary = imaginary;
}
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public float z;
public float w;
public ReadWriteBuffer<ComplexVector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
var offsetXY = offsetY * width + offsetX;
ComplexVector4 source4 = source[offsetXY];
Complex64 factors = kernel[i];
real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary;
imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real;
}
target[ids.Y * width + ids.X] += real * z + imaginary * w;
}
}
}
}
+2 -84
ファイルの表示
@@ -301,7 +301,7 @@ namespace ComputeSharp.BokehBlur.Processors
int height = Source.Height;
int width = Source.Width;
VerticalConvolutionProcessor shader = new(
HlslBokehBlurProcessor.VerticalConvolutionProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
@@ -313,47 +313,6 @@ namespace ComputeSharp.BokehBlur.Processors
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Kernel for <see cref="ApplyVerticalConvolution"/>.
/// </summary>
[AutoConstructor]
private partial struct VerticalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadOnlyBuffer<Vector4> source;
public ReadWriteBuffer<ComplexVector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
Complex64 factors = kernel[i];
real += factors.Real * color;
imaginary += factors.Imaginary * color;
}
int offsetXY = ids.Y * width + ids.X;
target[offsetXY].Real = real;
target[offsetXY].Imaginary = imaginary;
}
}
/// <summary>
/// Performs an horizontal 1D complex convolution with the specified parameters.
/// </summary>
@@ -373,7 +332,7 @@ namespace ComputeSharp.BokehBlur.Processors
int height = Source.Height;
int width = Source.Width;
HorizontalConvolutionAndAccumulatePartialsProcessor shader = new(
HlslBokehBlurProcessor.HorizontalConvolutionAndAccumulatePartialsProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
@@ -387,47 +346,6 @@ namespace ComputeSharp.BokehBlur.Processors
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Kernel for <see cref="ApplyHorizontalConvolutionAndAccumulatePartials"/>.
/// </summary>
[AutoConstructor]
private partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public float z;
public float w;
public ReadWriteBuffer<ComplexVector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
var offsetXY = offsetY * width + offsetX;
ComplexVector4 source4 = source[offsetXY];
Complex64 factors = kernel[i];
real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary;
imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real;
}
target[ids.Y * width + ids.X] += real * z + imaginary * w;
}
}
/// <summary>
/// Applies the gamma correction/highlight to the input pixel buffer and returns an <see cref="IMemoryOwner{T}"/> instance with <see cref="Vector4"/> values.
/// </summary>
+77 -2
ファイルの表示
@@ -1,4 +1,5 @@
using SixLabors.ImageSharp;
using System.Numerics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
@@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors
/// <summary>
/// Defines Gaussian blur by a (Sigma, Radius) pair.
/// </summary>
public sealed class HlslGaussianBlurProcessor : IImageProcessor
public sealed partial class HlslGaussianBlurProcessor : IImageProcessor
{
/// <summary>
/// The default value for <see cref="Sigma"/>.
@@ -52,5 +53,79 @@ namespace ComputeSharp.BokehBlur.Processors
{
return new HlslGaussianBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
public readonly int width;
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
public readonly ReadWriteBuffer<Vector4> source;
public readonly ReadWriteBuffer<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
result += kernel[i] * color;
}
int offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
}
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
public readonly int width;
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
public readonly ReadWriteBuffer<Vector4> source;
public readonly ReadWriteBuffer<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
int offsetXY;
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
offsetXY = offsetY * width + offsetX;
Vector4 color = source[offsetXY];
result += kernel[i] * color;
}
offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
}
}
}
}
+19 -91
ファイルの表示
@@ -13,7 +13,7 @@ namespace ComputeSharp.BokehBlur.Processors
/// Applies Gaussian blur processing to an image.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
internal class HlslGaussianBlurProcessor<TPixel> : ImageProcessor<TPixel>
internal sealed class HlslGaussianBlurProcessor<TPixel> : ImageProcessor<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
{
/// <summary>
@@ -124,51 +124,16 @@ namespace ComputeSharp.BokehBlur.Processors
int height = Source.Height;
int width = Source.Width;
Gpu.Default.For(width, height, new VerticalConvolutionProcessor
{
width = width,
maxY = height - 1,
maxX = width - 1,
kernelLength = kernel.Length,
source = source,
target = target,
kernel = kernel
});
}
HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
/// <summary>
/// Kernel for <see cref="ApplyVerticalConvolution"/>.
/// </summary>
private struct VerticalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadWriteBuffer<Vector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
result += kernel[i] * color;
}
int offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
}
Gpu.Default.For(width, height, in shader);
}
/// <summary>
@@ -186,53 +151,16 @@ namespace ComputeSharp.BokehBlur.Processors
int height = Source.Height;
int width = Source.Width;
Gpu.Default.For(width, height, new HorizontalConvolutionProcessor
{
width = width,
maxY = height - 1,
maxX = width - 1,
kernelLength = kernel.Length,
source = source,
target = target,
kernel = kernel
});
}
HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
/// <summary>
/// Kernel for <see cref="ApplyHorizontalConvolution"/>.
/// </summary>
private struct HorizontalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadWriteBuffer<Vector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
int offsetXY;
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
offsetXY = offsetY * width + offsetX;
Vector4 color = source[offsetXY];
result += kernel[i] * color;
}
offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
}
Gpu.Default.For(width, height, in shader);
}
}
}
+2 -2
ファイルの表示
@@ -42,9 +42,9 @@ namespace ComputeSharp.Sample
/// Kernel for <see cref="Main"/>.
/// </summary>
[AutoConstructor]
private readonly partial struct MainKernel : IComputeShader
internal readonly partial struct MainKernel : IComputeShader
{
private readonly ReadWriteBuffer<float> buffer;
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
@@ -5,7 +5,7 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
namespace ComputeSharp
namespace ComputeSharp.__Internals
{
/// <summary>
/// An attribute that contains info on a processed compute shader that can be executed.
@@ -13,7 +13,7 @@ namespace ComputeSharp
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is meant to be used from the source generator only")]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed class IComputeShaderSourceAttribute : Attribute
{
/// <summary>
@@ -6,7 +6,7 @@ using System.Reflection;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Exceptions;
namespace ComputeSharp
namespace ComputeSharp.__Internals
{
/// <summary>
/// An attribute that contains info on a processed shader method that can be executed within a shader.
@@ -15,7 +15,7 @@ namespace ComputeSharp
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is meant to be used from the source generator only")]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed class ShaderMethodSourceAttribute : Attribute
{
/// <summary>
+1
ファイルの表示
@@ -1,6 +1,7 @@
using System;
using System.Diagnostics.Contracts;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Extensions;
#pragma warning disable CS0618
@@ -1,7 +1,7 @@
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace ComputeSharp.Graphics.Helpers
namespace ComputeSharp.Core.Helpers
{
/// <summary>
/// A <see langword="class"/> with helper methods to work with alignment and padding.
+1
ファイルの表示
@@ -1,6 +1,7 @@
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Core.Helpers;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
+68
ファイルの表示
@@ -0,0 +1,68 @@
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using TerraFX.Interop;
namespace ComputeSharp.__Internals
{
/// <summary>
/// A helper class with some proxy methods to expose to generated code in external projects.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This type is not intended to be used directly by user code")]
public static class GraphicsResourceHelper
{
/// <summary>
/// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle.
/// </summary>
/// <param name="buffer">The input <see cref="Buffer{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(Buffer<T> buffer, GraphicsDevice device)
where T : unmanaged
{
buffer.ThrowIfDisposed();
buffer.ThrowIfDeviceMismatch(device);
return Unsafe.As<D3D12_GPU_DESCRIPTOR_HANDLE, ulong>(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle));
}
/// <summary>
/// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle.
/// </summary>
/// <param name="buffer">The input <see cref="Texture2D{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(Texture2D<T> buffer, GraphicsDevice device)
where T : unmanaged
{
buffer.ThrowIfDisposed();
buffer.ThrowIfDeviceMismatch(device);
return Unsafe.As<D3D12_GPU_DESCRIPTOR_HANDLE, ulong>(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle));
}
/// <summary>
/// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle.
/// </summary>
/// <param name="buffer">The input <see cref="Texture3D{T}"/> instance to check.</param>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance in use.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ValidateAndGetGpuDescriptorHandle<T>(Texture3D<T> buffer, GraphicsDevice device)
where T : unmanaged
{
buffer.ThrowIfDisposed();
buffer.ThrowIfDeviceMismatch(device);
return Unsafe.As<D3D12_GPU_DESCRIPTOR_HANDLE, ulong>(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle));
}
}
}
-107
ファイルの表示
@@ -1,107 +0,0 @@
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.Diagnostics;
namespace ComputeSharp.Shaders.Extensions
{
/// <summary>
/// A <see langword="class"/> that provides extension methods for the <see langword="ILGenerator"/> type.
/// </summary>
internal static class ILGeneratorExtensions
{
/// <summary>
/// Puts the appropriate <see langword="ldsfld"/>, <see langword="ldfld"/>, <see langword="call"/> or <see langword="callvirt"/> instruction to read a member onte the stream of instructions.
/// </summary>
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
/// <param name="member">The member to read.</param>
public static void EmitReadMember(this ILGenerator il, MemberInfo member)
{
switch (member)
{
case FieldInfo field:
il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field);
break;
case PropertyInfo property when property.CanRead:
il.EmitCall(property.GetMethod!.IsStatic ? OpCodes.Call : OpCodes.Callvirt, property.GetMethod, null);
break;
default: ThrowHelper.ThrowArgumentException("The input MemberInfo instance can't be read"); return;
}
}
/// <summary>
/// Puts the appropriate <see langword="ldc.i4"/>, <see langword="conv.i"/> and <see langword="add"/> instructions to advance a reference onto the stream of instructions.
/// </summary>
/// <typeparam name="T">The type of reference at the top of the stack.</typeparam>
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
/// <param name="offset">The offset to use to advance the current reference on top of the execution stack.</param>
public static void EmitAddOffset<T>(this ILGenerator il, int offset) => il.EmitAddOffset(Unsafe.SizeOf<T>() * offset);
/// <summary>
/// Puts the appropriate <see langword="ldc.i4"/>, <see langword="conv.i"/> and <see langword="add"/> instructions to advance a reference onto the stream of instructions.
/// </summary>
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
/// <param name="offset">The offset in bytes to use to advance the current reference on top of the execution stack.</param>
public static void EmitAddOffset(this ILGenerator il, int offset)
{
// Push the offset to the stack
if (offset < -128) il.Emit(OpCodes.Ldc_I4, offset);
else if (offset < 0) il.Emit(OpCodes.Ldc_I4_S, (sbyte)offset);
else if (offset <= 8)
{
il.Emit(offset switch
{
0 => OpCodes.Ldc_I4_0,
1 => OpCodes.Ldc_I4_1,
2 => OpCodes.Ldc_I4_2,
3 => OpCodes.Ldc_I4_3,
4 => OpCodes.Ldc_I4_4,
5 => OpCodes.Ldc_I4_5,
6 => OpCodes.Ldc_I4_6,
7 => OpCodes.Ldc_I4_7,
8 => OpCodes.Ldc_I4_8,
_ => ThrowHelper.ThrowArgumentException<OpCode>("Invalid offset value")
});
}
else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset);
else il.Emit(OpCodes.Ldc_I4, offset);
// Converts the offset to native int and adds to the address
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Add);
}
/// <summary>
/// Puts the appropriate <see langword="stind"/> or <see langword="stobj"/> instruction to write to a reference onto the stream of instructions.
/// </summary>
/// <param name="il">The input <see cref="ILGenerator"/> instance to use to emit instructions.</param>
/// <param name="type">The type of value being written to the current reference on top of the execution stack.</param>
public static void EmitStoreToAddress(this ILGenerator il, Type type)
{
if (type.IsValueType)
{
// Pick the optimal opcode to set a value type
OpCode opcode = Marshal.SizeOf(type) switch
{
// Use the faster op codes for sizes <= 8
1 when type == typeof(byte) || type == typeof(sbyte) => OpCodes.Stind_I1,
2 when type == typeof(short) || type == typeof(ushort) => OpCodes.Stind_I2,
4 when type == typeof(float) => OpCodes.Stind_R4,
4 when type == typeof(int) || type == typeof(uint) => OpCodes.Stind_I4,
8 when type == typeof(double) => OpCodes.Stind_R8,
8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8,
// Default to stobj for all other value types
_ => OpCodes.Stobj
};
// Also pass the type token if stobj is used
if (opcode == OpCodes.Stobj) il.Emit(opcode, type);
else il.Emit(opcode);
}
else il.Emit(OpCodes.Stind_Ref);
}
}
}
-21
ファイルの表示
@@ -1,21 +0,0 @@
using System;
using System.Diagnostics.Contracts;
namespace ComputeSharp.Shaders.Extensions
{
/// <summary>
/// A <see langword="class"/> that provides extension methods for the <see cref="Type"/> type.
/// </summary>
internal static class TypeExtensions
{
/// <summary>
/// Gets whether or not the input <see cref="Type"/> represents a <see cref="Delegate"/>.
/// </summary>
/// <param name="type">The input type to analyze.</param>
[Pure]
public static bool IsDelegate(this Type type)
{
return type.IsSubclassOf(typeof(Delegate));
}
}
}
-58
ファイルの表示
@@ -1,58 +0,0 @@
using System.Diagnostics.Contracts;
using System.Linq;
namespace System.Reflection.Emit
{
/// <summary>
/// A <see langword="class"/> that can be used to easily create dynamic methods.
/// </summary>
/// <typeparam name="T">The type of <see cref="Delegate"/> that will be used to wrap the new methods.</typeparam>
internal static class DynamicMethod<T>
where T : Delegate
{
/// <summary>
/// The return type of the <typeparamref name="T"/> <see langword="delegate"/>.
/// </summary>
private static readonly Type ReturnType;
/// <summary>
/// The types of the arguments of the <typeparamref name="T"/> <see langword="delegate"/>.
/// </summary>
private static readonly Type[] ParameterTypes;
/// <summary>
/// Loads all the necessary <see cref="Type"/> info for the current <typeparamref name="T"/> parameter.
/// </summary>
static DynamicMethod()
{
MethodInfo method = typeof(T).GetMethod("Invoke")!;
ReturnType = method.ReturnType;
ParameterTypes = new[] { typeof(object) }.Concat(method.GetParameters().Select(static p => p.ParameterType)).ToArray();
}
/// <summary>
/// Creates a new <typeparamref name="T"/> <see langword="delegate"/> for the target owner. For performance reasons,
/// the underlying dynamic method will be created with an extra <see cref="object"/> parameter, and then bound to
/// a <see langword="null"/> instance. This is to emulate the behavior of instance methods, which unlike static ones
/// don't need to go through the shuffle thunk when the delegate is invoked. This would be needed to redirect the
/// invocation to a stub that performs parameters swapping, as the Invoke method is an instance one with the parameters
/// starting from offset 1, while the target static method would expect them to start from offset 0. This solution
/// allows the delegate created for the dynamic method to avoid having a shuffle thunk at all, and with it only having
/// to replace the hidden instance argument when being invoked, resulting in much better performance. Because of this,
/// it is expected that <paramref name="builder"/> will emit the bytecode assuming that there is an extra unused argument
/// at offset 0. As a result of this, all argument load and store opcodes will need to be shifted by one position forwards.
/// </summary>
/// <param name="builder">An <see cref="Action"/> that builds the IL bytecode for the new method.</param>
/// <returns>A new dynamic method wrapped as a <typeparamref name="T"/> <see langword="delegate"/>.</returns>
[Pure]
public static T New(Action<ILGenerator> builder)
{
DynamicMethod method = new(string.Empty, ReturnType, ParameterTypes, true);
builder(method.GetILGenerator());
return method.CreateDelegate<T>(null);
}
}
}
+8 -7
ファイルの表示
@@ -12,9 +12,9 @@ namespace ComputeSharp.Shaders.Translation.Models
internal readonly ref struct DispatchData
{
/// <summary>
/// The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.
/// The <see cref="ulong"/> array (actually <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values) with the captured buffers.
/// </summary>
private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray;
private readonly ulong[] resourcesArray;
/// <summary>
/// The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> values in <see cref="resourcesArray"/>.
@@ -34,11 +34,11 @@ namespace ComputeSharp.Shaders.Translation.Models
/// <summary>
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
/// </summary>
/// <param name="resourcesArray">The <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> array with the captured buffers.</param>
/// <param name="resourcesArray">The <see cref="ulong"/> array with the captured buffers.</param>
/// <param name="resourcesCount">The number of <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances in <see cref="resourcesArray"/>.</param>
/// <param name="variablesArray">The <see cref="byte"/> array with all the captured variables, with proper padding.</param>
/// <param name="variablesByteSize">The actual size in bytes to use from <see cref="variablesArray"/>.</param>
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<ulong, D3D12_GPU_DESCRIPTOR_HANDLE>(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
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Return(this.resourcesArray);
ArrayPool<ulong>.Shared.Return(this.resourcesArray);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
+4 -51
ファイルの表示
@@ -1,11 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using ComputeSharp.Shaders.Extensions;
namespace ComputeSharp.Shaders.Translation
{
@@ -38,16 +34,11 @@ namespace ComputeSharp.Shaders.Translation
{
Id = HashCode.Combine(typeof(T));
// Get the valid delegates for delegate checking
FieldInfo[] delegateFieldInfos = (
from fieldInfo in typeof(T).GetFields()
where fieldInfo.FieldType.IsDelegate()
select fieldInfo).ToArray();
// If at least one delegate is present, build the hasher method
if (delegateFieldInfos.Length > 0)
// Get the generated hasher, if one if present
if (typeof(T).Assembly.GetType("ComputeSharp.__Internals.HashCodeProvider") is Type type &&
type.GetMethod("CombineHash", new[] { typeof(int), typeof(T).MakeByRefType() }) is MethodInfo method)
{
Hasher = BuildDynamicHasher<T>(delegateFieldInfos);
Hasher = method.CreateDelegate<Hasher<T>>();
}
}
}
@@ -80,43 +71,5 @@ namespace ComputeSharp.Shaders.Translation
/// <returns>The final hash value for the input closure.</returns>
private delegate int Hasher<T>(int hash, in T shader)
where T : struct, IComputeShader;
/// <summary>
/// Builds a new <see cref="Hasher{T}"/> instance for the target <see cref="Type"/> and sequence of <see cref="FieldInfo"/> values.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
/// <param name="fieldInfos">The list of captured fields to inspect.</param>
[Pure]
private static Hasher<T> BuildDynamicHasher<T>(IReadOnlyCollection<FieldInfo> fieldInfos)
where T : struct, IComputeShader
{
return DynamicMethod<Hasher<T>>.New(il =>
{
MethodInfo
getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method))!.GetMethod!,
getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode))!;
foreach (FieldInfo fieldInfo in fieldInfos)
{
// (hashcode << 5) + hashcode
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldc_I4_5);
il.Emit(OpCodes.Shl);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Add);
// hashcode += shader.Function[#].Method.GetHashCode();
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.EmitCall(OpCodes.Callvirt, getMethodInfo, null);
il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Starg_S, (byte)1);
}
// Return the computed hash
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ret);
});
}
}
}
+87
ファイルの表示
@@ -0,0 +1,87 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics;
using ComputeSharp.Shaders.Translation.Models;
using TerraFX.Interop;
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader{T}"/>
internal sealed partial class ShaderLoader<T>
{
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The shader instance to load the data from.</param>
/// <param name="r0">
/// A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.
/// This is just represented as a <see cref="ulong"/> reference, to avoid exposing the type publicly.
/// </param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
/// <returns>The returned value indicates the total number of written bytes into <paramref name="r1"/>.</returns>
private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1);
/// <summary>
/// The number of captured graphics resources (buffers).
/// </summary>
private int totalResourceCount;
/// <summary>
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
/// </summary>
private DispatchDataLoader? dispatchDataLoader;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<FieldInfo> capturedFields = new();
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
[Pure]
public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z)
{
// Resources and variables buffers
ulong[] resources = ArrayPool<ulong>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(4096);
ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and z counters
Unsafe.As<byte, int>(ref r1) = x;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
return new(resources, this.totalResourceCount, variables, totalVariablesByteSize);
}
/// <summary>
/// Initializes the <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void InitializeDispatchDataLoader()
{
// 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)!;
this.dispatchDataLoader = method.CreateDelegate<DispatchDataLoader>();
}
}
}
-170
ファイルの表示
@@ -1,170 +0,0 @@
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
{
/// <inheritdoc cref="ShaderLoader{T}"/>
internal sealed partial class ShaderLoader<T>
{
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The shader instance to load the data from.</param>
/// <param name="r0">A reference to the buffer with all the captured <see cref="D3D12_GPU_DESCRIPTOR_HANDLE"/> instances.</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
private delegate void DispatchDataLoader(GraphicsDevice device, in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1);
/// <summary>
/// The number of captured graphics resources (buffers).
/// </summary>
private int totalResourceCount;
/// <summary>
/// The size in bytes of the buffer with the captured variables.
/// </summary>
/// <remarks>Initially set to 3 <see cref="int"/> values for X, Y and Z threads counts.</remarks>
private int totalVariablesByteSize = 3 * sizeof(int);
/// <summary>
/// The cached <see cref="DispatchDataLoader"/> instance to load dispatch data before execution.
/// </summary>
private DispatchDataLoader? dispatchDataLoader;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="FieldInfo"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<FieldInfo> capturedFields = new();
/// <summary>
/// Gets a new <see cref="DispatchData"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
/// <param name="x">The number of iterations to run on the X axis.</param>
/// <param name="y">The number of iterations to run on the Y axis.</param>
/// <param name="z">The number of iterations to run on the Z axis.</param>
[Pure]
public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z)
{
// Resources and variables buffers
D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool<D3D12_GPU_DESCRIPTOR_HANDLE>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(this.totalVariablesByteSize);
ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables);
// Set the x, y and z counters
Unsafe.As<byte, int>(ref r1) = x;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
// Invoke the dynamic method to extract the captured data
this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
return new(resources, this.totalResourceCount, variables, this.totalVariablesByteSize);
}
/// <summary>
/// Builds a new <see cref="DispatchDataLoader"/> instance that loads the dispatch data for the current shader type.
/// </summary>
private void BuildDispatchDataLoader()
{
// The delegate signature is <GraphicsDevice, in T, ref D3D12_GPU_DESCRIPTOR_HANDLE, ref byte, void>.
// Due to how DynamicMethod<T> is implemented (see notes in the XML docs for DynamicMethod<T>.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<DispatchDataLoader>.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);
if (totalResourceCount > 0)
{
il.EmitAddOffset<D3D12_GPU_DESCRIPTOR_HANDLE>(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<byte>.ThrowIfDeviceMismatch),
BindingFlags.Instance | BindingFlags.NonPublic)!, null);
// Access D3D12GpuDescriptorHandle
il.EmitReadMember(fieldInfo.FieldType.GetField(
nameof(Buffer<byte>.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);
}
}
}
+5 -1
ファイルの表示
@@ -4,6 +4,7 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models;
using Microsoft.Toolkit.Diagnostics;
@@ -113,7 +114,7 @@ namespace ComputeSharp.Shaders.Translation
@this.LoadFieldsInfo(box);
@this.LoadMethodMetadata();
@this.BuildDispatchDataLoader();
@this.InitializeDispatchDataLoader();
return @this;
}
@@ -163,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))
{
@@ -171,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))
{
@@ -179,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))
{
+4 -3
ファイルの表示
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
@@ -15,12 +15,13 @@
and to match members based on full name, so the types being in the generator assembly are not an issue.-->
<ItemGroup>
<Compile Include="..\ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" Link="Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\IComputeShaderSourceAttribute.cs" Link="Core\Attributes\IComputeShaderSourceAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\ShaderMethodAttribute.cs" Link="Core\Attributes\ShaderMethodAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\ShaderMethodSourceAttribute.cs" Link="Core\Attributes\ShaderMethodSourceAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" Link="Core\Attributes\__Internals\IComputeShaderSourceAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Exceptions\InvalidExecutionContextException.cs" Link="Core\Exceptions\InvalidExecutionContextException.cs" />
<Compile Include="..\ComputeSharp.Core\Exceptions\MissingMethodSourceException.cs" Link="Core\Exceptions\MissingMethodSourceException.cs" />
<Compile Include="..\ComputeSharp.Core\Extensions\MethodInfoExtensions.cs" Link="Core\Extensions\MethodInfoExtensions.cs" />
<Compile Include="..\ComputeSharp.Core\Helpers\AlignmentHelper.cs" Link="Core\Helpers\AlignmentHelper.cs" />
<Compile Include="..\ComputeSharp.Core\Interfaces\IComputeShader.cs" Link="Core\Interfaces\IComputeShader.cs" />
<Compile Include="..\ComputeSharp.Core\Intrinsics\Attributes\PreserveMemberNameAttribute.cs" Link="Core\Intrinsics\Attributes\PreserveMemberNameAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Intrinsics\Hlsl.cs" Link="Core\Intrinsics\Hlsl.cs" />
+172
ファイルの表示
@@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators
{
[Generator]
public class IComputeShaderDataLoaderGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Find all the struct declarations
ImmutableArray<StructDeclarationSyntax> structDeclarations = (
from tree in context.Compilation.SyntaxTrees
from structDeclaration in tree.GetRoot().DescendantNodes().OfType<StructDeclarationSyntax>()
select structDeclaration).ToImmutableArray();
// Type attributes
AttributeListSyntax[] attributes = new[]
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This type is not intended to be used directly by user code"))))))
};
foreach (StructDeclarationSyntax structDeclaration in structDeclarations)
{
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
// Only process compute shader types
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol));
// 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:
//
// using System;
// using System.ComponentModel;
//
// namespace ComputeSharp.__Internals
// {
// internal static partial class DispatchDataLoader
// {
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
// [System.Obsolete("This method is not intended to be called directly by user code")]
// public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1)
// {
// ...
// }
// }
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.ComponentModel")),
UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers(
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
ClassDeclaration("DispatchDataLoader").AddModifiers(
Token(SyntaxKind.InternalKeyword),
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("LoadDispatchData")).AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be called directly by user code"))))))).AddModifiers(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.Graphics.GraphicsDevice")),
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType),
Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))),
Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.WithBody(block)))
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace()
.ToFullString();
// Clear the attribute list to avoid duplicates
attributes = Array.Empty<AttributeListSyntax>();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderDataLoaderGenerator>(), SourceText.From(source, Encoding.UTF8));
}
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
[Pure]
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol)
{
int
resourceOffset = 0,
rawDataOffset = sizeof(int) * 3;
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
string typeName = typeSymbol.GetFullMetadataName();
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
yield return ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"),
ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")));
}
else if (HlslKnownTypes.IsScalarOrVectorType(typeName))
{
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
// Since we're in a constant buffer, we need to both pad the starting offset
// to be aligned to the packing size of the type, and also to align the initial
// offset to ensure that values do not cross 16 bytes boundaries either.
rawDataOffset = AlignmentHelper.AlignToBoundary(
AlignmentHelper.Pad(rawDataOffset, fieldPack),
fieldSize,
16);
yield return ExpressionStatement(
ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})"));
rawDataOffset += fieldSize;
}
}
// 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.
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
yield return ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)));
}
}
}
+138
ファイルの表示
@@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators
{
[Generator]
public class IComputeShaderHashCodeGenerator : ISourceGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
{
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Find all the struct declarations
ImmutableArray<StructDeclarationSyntax> structDeclarations = (
from tree in context.Compilation.SyntaxTrees
from structDeclaration in tree.GetRoot().DescendantNodes().OfType<StructDeclarationSyntax>()
select structDeclaration).ToImmutableArray();
// Type attributes
AttributeListSyntax[] attributes = new[]
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This type is not intended to be used directly by user code"))))))
};
foreach (StructDeclarationSyntax structDeclaration in structDeclarations)
{
SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree);
INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!;
// Only process compute shader types
if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue;
TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString());
BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol));
if (block.Statements.Count == 1) continue;
// 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:
//
// using System;
// using System.ComponentModel;
//
// namespace ComputeSharp.__Internals
// {
// internal static partial class HashCodeProvider
// {
// [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
// [System.Obsolete("This method is not intended to be called directly by user code")]
// public static int CombineHashCode(int hash, in ShaderType shader)
// {
// return ...;
// }
// }
// }
var source =
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("System")),
UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers(
NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers(
ClassDeclaration("HashCodeProvider").AddModifiers(
Token(SyntaxKind.InternalKeyword),
Token(SyntaxKind.StaticKeyword),
Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers(
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("CombineHash")).AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be called directly by user code"))))))).AddModifiers(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)).AddParameterListParameters(
Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType))
.WithBody(block))))
.NormalizeWhitespace()
.ToFullString();
// Clear the attribute list to avoid duplicates
attributes = Array.Empty<AttributeListSyntax>();
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName<IComputeShaderHashCodeGenerator>(), SourceText.From(source, Encoding.UTF8));
}
}
/// <summary>
/// Gets a sequence of statements to process the hashcode of the captured delegates.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to hash the captured delegates.</returns>
[Pure]
private static IEnumerable<StatementSyntax> GetDelegateHashCodeStatements(INamedTypeSymbol structDeclarationSymbol)
{
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type;
if (typeSymbol.TypeKind != TypeKind.Delegate) continue;
// hash += hash << 5;
yield return ExpressionStatement(ParseExpression($"hash += hash << 5"));
// hash += shader.Field[#i].Method.GetHashCode();
yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldSymbol.Name}.Method.GetHashCode()"));
}
yield return ReturnStatement(IdentifierName("hash"));
}
}
}
+3 -1
ファイルの表示
@@ -3,6 +3,7 @@ using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
@@ -81,7 +82,8 @@ namespace ComputeSharp.SourceGenerators
// Create the compilation unit with the source attribute
var source =
CompilationUnit().AddAttributeLists(
CompilationUnit().AddUsings(
UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structDeclarationSymbol.GetFullMetadataName()))),
+14 -2
ファイルの表示
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Numerics;
namespace ComputeSharp.SourceGenerators.Mappings
@@ -9,9 +10,9 @@ namespace ComputeSharp.SourceGenerators.Mappings
internal static class HlslKnownSizes
{
/// <summary>
/// Gets the mapping of supported known sizes to HLSL type names.
/// The mapping of supported known sizes to HLSL type names.
/// </summary>
public static IReadOnlyDictionary<string, (int Size, int Pack)> KnownSizes { get; } = new Dictionary<string, (int, int)>
private static IReadOnlyDictionary<string, (int, int)> KnownSizes = new Dictionary<string, (int, int)>
{
[typeof(bool).FullName] = (4, 4),
[typeof(int).FullName] = (4, 4),
@@ -43,5 +44,16 @@ namespace ComputeSharp.SourceGenerators.Mappings
[typeof(Double3).FullName] = (24, 8),
[typeof(Double3).FullName] = (32, 8)
};
/// <summary>
/// Gets the size and alignment info for a specified primitive type.
/// </summary>
/// <param name="typeName">The type name to get info for.</param>
/// <returns>The size and and alignment for the input type.</returns>
[Pure]
public static (int Size, int Pack) GetTypeInfo(string typeName)
{
return KnownSizes[typeName];
}
}
}
+12
ファイルの表示
@@ -78,6 +78,18 @@ namespace ComputeSharp.SourceGenerators.Mappings
};
}
/// <summary>
/// Checks whether or not a given type name matches a typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a typed resource type.</returns>
public static bool IsScalarOrVectorType(string typeName)
{
return
KnownTypes.ContainsKey(typeName) &&
typeName != typeof(ThreadIds).FullName;
}
/// <summary>
/// Gets the mapped HLSL-compatible type name for the input type symbol.
/// </summary>
+1
ファイルの表示
@@ -3,6 +3,7 @@ using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
using Microsoft.CodeAnalysis;
-29
ファイルの表示
@@ -1,29 +0,0 @@
using System;
using System.Reflection.Emit;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests.Internals
{
[TestClass]
[TestCategory("DynamicMethod")]
public class DynamicMethodTests
{
[TestMethod]
public void TestFunc()
{
Func<int, int> square = DynamicMethod<Func<int, int>>.New(il =>
{
// Due to the instance method trick, the first parameter is at offset 1.
// See the docs on DynamicMethod<T>.New for more info on how this works.
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Ret);
});
int result = square(2); // result = 2 * 2
Assert.IsTrue(result == 4);
}
}
}