Added TerraFX ShaderLoader and DispatchData types

このコミットが含まれているのは:
Sergio Pedri committed 2020-11-16 18:39:01 +01:00
1 親 5ffa20e548
コミット 86229ac764
3ファイル変更
+573

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

+87
ファイルの表示
@@ -0,0 +1,87 @@
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
namespace ComputeSharp.Shaders.Translation.Models
{
/// <summary>
/// A <see langword="struct"/> that contains all the captured data to dispatch a shader.
/// </summary>
internal readonly ref struct DispatchData2
{
/// <summary>
/// The <see cref="GraphicsResource2"/> array with the captured buffers.
/// </summary>
private readonly GraphicsResource2[] resourcesArray;
/// <summary>
/// The number of <see cref="GraphicsResource"/> instances in <see cref="resourcesArray"/>.
/// </summary>
private readonly int resourcesCount;
/// <summary>
/// The <see cref="byte"/> array with all the captured variables, with proper padding.
/// </summary>
private readonly byte[] variablesArray;
/// <summary>
/// The actual size in bytes to use from <see cref="variablesArray"/>.
/// </summary>
private readonly int variablesByteSize;
/// <summary>
/// Creates a new <see cref="DispatchData"/> instance with the specified parameters.
/// </summary>
/// <param name="resourcesArray">The <see cref="GraphicsResource2"/> array with the captured buffers.</param>
/// <param name="resourcesCount">The number of <see cref="GraphicsResource2"/> 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 DispatchData2(GraphicsResource2[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize)
{
this.resourcesArray = resourcesArray;
this.variablesArray = variablesArray;
this.resourcesCount = resourcesCount;
this.variablesByteSize = variablesByteSize;
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with all the captured buffers.
/// </summary>
public ReadOnlySpan<GraphicsResource2> Resources
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref GraphicsResource2 r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray);
return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount);
}
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the padded data representing all the captured variables.
/// </summary>
public ReadOnlySpan<Int4> Variables
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray);
ref Int4 r1 = ref Unsafe.As<byte, Int4>(ref r0);
bool mod = (this.variablesByteSize & 15) > 0;
int length = variablesByteSize / 4 + Unsafe.As<bool, byte>(ref mod);
return MemoryMarshal.CreateReadOnlySpan(ref r1, length);
}
}
/// <inheritdoc cref="IDisposable.Dispose"/>
public void Dispose()
{
ArrayPool<GraphicsResource2>.Shared.Return(this.resourcesArray, true);
ArrayPool<byte>.Shared.Return(this.variablesArray);
}
}
}
+131
ファイルの表示
@@ -0,0 +1,131 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
namespace ComputeSharp.Shaders.Translation
{
/// <inheritdoc cref="ShaderLoader2{T}"/>
internal sealed partial class ShaderLoader2<T>
{
/// <summary>
/// A <see langword="delegate"/> that loads all the captured members from a shader instance.
/// </summary>
/// <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="GraphicsResource2"/> instances.</param>
/// <param name="r1">A reference to the buffer to use to store all the captured value types.</param>
private delegate void DispatchDataLoader(in T shader, ref GraphicsResource2 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="ReadableMember"/> instances mapping the captured variables in the current shader.
/// </summary>
private readonly List<ReadableMember> capturedMembers = new();
/// <summary>
/// Gets a new <see cref="DispatchData2"/> instance with all the captured data for the current shader instance.
/// </summary>
/// <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 DispatchData2 GetDispatchData(in T shader, int x, int y, int z)
{
// Resources and variables buffers
GraphicsResource2[] resources = ArrayPool<GraphicsResource2>.Shared.Rent(this.totalResourceCount);
byte[] variables = ArrayPool<byte>.Shared.Rent(this.totalVariablesByteSize);
ref GraphicsResource2 r0 = ref MemoryMarshal.GetArrayDataReference(resources);
ref byte r1 = ref variables[0];
// 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!(shader, ref r0, ref r1);
return new DispatchData2(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()
{
this.dispatchDataLoader = DynamicMethod<DispatchDataLoader>.New(il =>
{
foreach (ReadableMember member in this.capturedMembers)
{
if (HlslKnownTypes.IsKnownBufferType(member.MemberType))
{
// Load the offset address into the resource buffers
il.Emit(OpCodes.Ldarg_1);
if (totalResourceCount > 0)
{
il.EmitAddOffset<GraphicsResource>(this.totalResourceCount);
}
this.totalResourceCount++;
}
else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) ||
HlslKnownTypes.IsKnownVectorType(member.MemberType))
{
// Calculate the right offset with 16-bytes padding (HLSL constant buffer)
int size = member.MemberType == typeof(bool)
? sizeof(uint)
: Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL
if (this.totalVariablesByteSize % 16 > 16 - size)
{
this.totalVariablesByteSize += 16 - this.totalVariablesByteSize % 16;
}
// Load the target address into the variables buffer
il.Emit(OpCodes.Ldarg_2);
il.EmitAddOffset(totalVariablesByteSize);
this.totalVariablesByteSize += size;
}
else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}");
// Load the reference to the input delegate if the member is not static
if (!member.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
// Read the current member and store it to the target address
il.EmitReadMember(member);
il.EmitStoreToAddress(member.MemberType);
}
il.Emit(OpCodes.Ret);
});
}
}
}
+355
ファイルの表示
@@ -0,0 +1,355 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using ComputeSharp.Shaders.Renderer.Models.Functions;
using ComputeSharp.Shaders.Translation.Enums;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> responsible for loading and processing shaders of a given type.
/// </summary>
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
internal sealed partial class ShaderLoader2<T>
where T : struct, IComputeShader
{
/// <summary>
/// The number of constant buffers to define in the shader.
/// </summary>
private uint constantBuffersCount;
/// <summary>
/// The number of readonly buffers to define in the shader.
/// </summary>
private uint readOnlyBuffersCount;
/// <summary>
/// The number of read write buffers to define in the shader.
/// </summary>
private uint readWriteBuffersCount;
/// <summary>
/// The <see cref="List{T}"/> of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
/// </summary>
private readonly List<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1 = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
private readonly List<HlslBufferInfo> hlslBuffersInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
private readonly List<CapturedFieldInfo> fieldsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader functions.
/// </summary>
private readonly List<FunctionInfo> functionsInfo = new();
/// <summary>
/// The <see cref="List{T}"/> with the <see cref="FunctionInfo"/> items for the shader local functions.
/// </summary>
private readonly List<LocalFunctionInfo> localFunctionsInfo = new();
/// <summary>
/// Creates a new <see cref="ShaderLoader2{T}"/> instance.
/// </summary>
private ShaderLoader2()
{
}
/// <summary>
/// Gets a <see cref="Span{T}"/> with the loaded <see cref="D3D12_DESCRIPTOR_RANGE1"/> items for the shader.
/// </summary>
public ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> D3D12DescriptorRanges1
{
get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1);
}
/// <summary>
/// Gets the name of the <see cref="ThreadIds"/> variable used as input for the shader method.
/// </summary>
public string ThreadsIdsVariableName { get; private set; }
/// <summary>
/// Gets the generated source code for the method in the current shader.
/// </summary>
public string MethodBody { get; private set; }
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<HlslBufferInfo> HslsBuffersInfo => this.hlslBuffersInfo;
/// <summary>
/// Gets the collection of <see cref="CapturedFieldInfo"/> items for the shader fields.
/// </summary>
public IReadOnlyList<CapturedFieldInfo> FieldsInfo => this.fieldsInfo;
/// <summary>
/// Gets the collection of <see cref="FunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsInfo => this.functionsInfo;
/// <summary>
/// Gets the collection of <see cref="LocalFunctionInfo"/> items for the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsInfo => this.localFunctionsInfo;
/// <summary>
/// Loads and processes an input<typeparamref name="T"/> shadeer
/// </summary>
/// <param name="shader">The <typeparamref name="T"/> instance to use to build the shader</param>
/// <returns>A new <see cref="ShaderLoader"/> instance representing the input shader</returns>
[Pure]
public static ShaderLoader2<T> Load(in T shader)
{
ShaderLoader2<T> @this = new ShaderLoader2<T>();
// Reading members through reflection requires an object parameter,
// so here we're just boxing the input shader once to avoid allocating
// it multiple times in the managed heap while processing the shader.
object box = shader;
@this.LoadFieldsInfo(box);
@this.LoadMethodSource(box);
@this.BuildDispatchDataLoader();
return @this;
}
/// <summary>
/// Loads the fields info for the current shader being loaded
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadFieldsInfo(object shader)
{
IReadOnlyList<FieldInfo> shaderFields = typeof(T).GetFields(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic).ToArray();
if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body");
// Descriptor for the buffer for captured scalar/vector variables
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
// Inspect the captured fields
foreach (FieldInfo fieldInfo in shaderFields)
{
LoadFieldInfo(shader, fieldInfo);
}
}
/// <summary>
/// Loads a specified <see cref="ReadableMember"/> and adds it to the shader model
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="memberInfo">The target <see cref="ReadableMember"/> to load</param>
/// <param name="name">The optional explicit name to use for the field</param>
private void LoadFieldInfo(object shader, ReadableMember memberInfo, string? name = null)
{
Type fieldType = memberInfo.MemberType;
string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name);
// Constant buffer
if (HlslKnownTypes.IsConstantBufferType(fieldType))
{
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
1,
this.constantBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]);
this.hlslBuffersInfo.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, (int)this.constantBuffersCount));
}
else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType))
{
// Root parameter for a readonly buffer
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
1,
this.readOnlyBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.hlslBuffersInfo.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readOnlyBuffersCount));
}
else if (HlslKnownTypes.IsReadWriteBufferType(fieldType))
{
// Root parameter for a read write buffer
D3D12_DESCRIPTOR_RANGE1.Init(
out D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1,
D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
1,
this.readWriteBuffersCount++);
this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1);
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.hlslBuffersInfo.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, (int)this.readWriteBuffersCount));
}
else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType))
{
this.capturedMembers.Add(memberInfo);
string typeName = HlslKnownTypes.GetMappedName(fieldType);
this.fieldsInfo.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
}
else if (fieldType.IsDelegate() &&
memberInfo.GetValue(shader) is Delegate func &&
(func.Method.IsStatic || func.Method.DeclaringType!.IsStatelessDelegateContainer()) &&
(HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) &&
fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) ||
HlslKnownTypes.IsKnownVectorType(type)))
{
// Captured static delegates with a return type
LoadStaticMethodSource(shader, fieldName, func.Method);
}
else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\"");
}
/// <summary>
/// Loads the entry method for the current shader being loaded
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadMethodSource(object shader)
{
// Decompile the shader method
MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute))!;
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T));
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Extract the implicit local functions
var locals = root.DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray();
root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia)!;
foreach (var local in locals)
{
string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n');
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the thread ids identifier name and shader method body
ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text;
MethodBody = root.Body!.ToFullString();
// Additional preprocessing
MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
MethodBody = HlslKnownKeywords.GetMappedText(MethodBody);
}
/// <summary>
/// Loads additional static methods used by the shader
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="name">The HLSL name of the new method to load</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/> instance for the method to load</param>
private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo)
{
// Decompile the target method
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the method
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType!);
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the function parameters
IReadOnlyList<ParameterInfo> parameters = (
from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i))
let modifiers = parameter.Node.Modifiers
let type = parameter.Node.Type!.ToFullString()
let parameterName = parameter.Node.Identifier.ToFullString()
let last = parameter.Index == root.ParameterList.Parameters.Count - 1
select new ParameterInfo(modifiers, type, parameterName, last)).ToArray();
// Get the function body
string body = root.Body!.ToFullString();
body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
body = body.TrimEnd('\n', '\r', ' ');
body = HlslKnownKeywords.GetMappedText(body);
// Get the final function info instance
FunctionInfo functionInfo = new FunctionInfo(
methodInfo.ReturnType,
$"{methodInfo.DeclaringType!.FullName}{Type.Delimiter}{methodInfo.Name}",
string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")),
root.ReturnType.ToString(),
name,
parameters,
body);
this.functionsInfo.Add(functionInfo);
}
}
}