From ac6236fa751269a84071662ff8a539b414207f74 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 22:06:56 +0200 Subject: [PATCH] Added initial draft version of new shader data loader --- .../Mappings/HlslKnownTypes.cs | 10 + .../Models/ReadableMember.GetValue.cs | 2 +- .../Translation/ShaderLoader.IL.cs | 196 ++++++++++++++++++ .../Translation/ShaderLoader.cs | 2 +- 4 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs index 65bd4918..de6c9a36 100644 --- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs @@ -93,6 +93,16 @@ namespace ComputeSharp.Shaders.Mappings type == typeof(Vector3) || type == typeof(Vector4); + /// + /// Checks whether or not the input type is a known buffer type + /// + /// The input instance to check + /// A indicating whether the input is in fact a known buffer type + [Pure] + public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) || + IsReadOnlyBufferType(type) || + IsReadWriteBufferType(type); + /// /// Checks whether or not the input type is a value /// diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs index a3858ec0..70e665c6 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs @@ -71,7 +71,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// Gets or sets the list of parent members to access the current one from the root instance /// - public IEnumerable? Parents { get; set; } + public IReadOnlyList? Parents { get; set; } /// /// Builds a dynamic IL method to retrieve the value of the current member diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs new file mode 100644 index 00000000..297d8365 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -0,0 +1,196 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +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 +{ + internal sealed partial class ShaderLoader + { + private int _ResourcesCount; + + private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count + + /// + /// The of instances mapping the captured variables in the current shader + /// + private readonly List _CapturedMembers = new List(); + + /// + /// A that loads all the captured members from a shader closure + /// + /// The shader closure instance to load the data from + /// A reference to the buffer with all the captured instances + /// A reference to the buffer to use to store all the captured value types + private delegate void MembersLoader(object obj, ref GraphicsResource r0, ref byte r1); + + // The cached loader method + private MembersLoader? _MembersLoader; + + [Pure] + public ShaderDispatchData GetDispatchData(Action action, int x, int y, int z) + { + if (_MembersLoader == null) + { + // Mapping of parent members to index of the relative local variable + var map = + _CapturedMembers + .Where(m => !m.IsStatic && m.Parents != null) + .SelectMany(m => m.Parents) + .Distinct() + .Select((m, i) => (Member: m, Index: i)) + .ToDictionary(p => (object)p.Member, p => p.Index + 1); + object root = new object(); // Placeholder + map.Add(root, 0); + + // Set of indices of the loaded parent members + HashSet loaded = new HashSet(new [] { 0 }); + + // Build the dynamic IL method + _MembersLoader = DynamicMethod.New(il => + { + // Loads a given member on the top of the execution stack + void LoadMember(ReadableMember member) + { + if (!member.IsStatic) + { + // Load the parent instance on the execution stack if the member isn't static + int index = map[member.Parents?.Last() ?? root]; + if (loaded.Contains(index)) il.EmitLoadLocal(index); + else + { + // Seek upwards to find the most in depth loaded parent + int i = member.Parents!.Count - 1; + while (i > 0 && !loaded.Contains(map[member.Parents[i]])) i--; + + // Load the local variables for all the parents of the current member + if (i == 0) il.EmitLoadLocal(0); + for (; i < member.Parents.Count; i++) + { + il.Emit(OpCodes.Ldfld, member.Parents[i].MemberType); + il.EmitStoreLocal(map[member.Parents[i]]); + il.EmitLoadLocal(map[member.Parents[i]]); + } + } + } + + il.EmitReadMember(member); + } + + // Declare the local variables + il.DeclareLocal(ShaderType); + foreach (ReadableMember member in map.OrderBy(p => p.Value).Select(p => p.Key)) + { + il.DeclareLocal(member.MemberType); + } + + // Cast the closure instance and assign it to the local variable + il.Emit(OpCodes.Ldarg_0); + il.EmitCastOrUnbox(ShaderType); + il.Emit(OpCodes.Stloc_0); + + // Handle all the captured members, both resources and variables + foreach (ReadableMember member in _CapturedMembers) + { + if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) + { + // Load the offset address into the resource buffers + il.Emit(OpCodes.Ldarg_0); + if (_ResourcesCount > 0) il.EmitAddOffset(_ResourcesCount); + _ResourcesCount++; + + /* Load the current member accordingly. + * When this method returns, the value of the current + * member will be at the top of the execution stack */ + LoadMember(member); + + il.EmitStoreToAddress(member.MemberType); + } + else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || + HlslKnownTypes.IsKnownVectorType(member.MemberType)) + { + // Calculate the right offset with 16-bytes padding (HLSL constant buffer) + int size = Marshal.SizeOf(member.MemberType); + if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16; + + // Load the target address into the variables buffer + il.Emit(OpCodes.Ldarg_1); + il.EmitAddOffset(_VariablesByteSize); + + // Load the variable and store it in the loaded address + LoadMember(member); + il.EmitStoreToAddress(member.MemberType); + } + else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); + } + + il.Emit(OpCodes.Ret); + }); + } + + // Resources and variables buffers + GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); + byte[] variables = ArrayPool.Shared.Rent(_VariablesByteSize); + ref GraphicsResource r0 = ref resources[0]; + ref byte r1 = ref variables[0]; + + // Set the x, y and z counters + Unsafe.As(ref r1) = x; + Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; + Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; + + // Invoke the dynamic method to extract the captured data + _MembersLoader(action.Target, ref r0, ref r1); + + return new ShaderDispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); + } + + public readonly ref struct ShaderDispatchData + { + private readonly GraphicsResource[] ResourcesArray; + + private readonly byte[] VariablesArray; + + private readonly int ResourcesCount; + + private readonly int VariablesInt4Size; + + public Span Resources + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ResourcesArray.AsSpan(0, ResourcesCount); + } + + public Span Variables + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ref Int4 r = ref Unsafe.As(ref VariablesArray[0]); + return MemoryMarshal.CreateSpan(ref r, VariablesInt4Size); + } + } + + public ShaderDispatchData(GraphicsResource[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesInt4Size) + { + ResourcesArray = resourcesArray; + VariablesArray = variablesArray; + ResourcesCount = resourcesCount; + VariablesInt4Size = variablesInt4Size; + } + + public void Dispose() + { + ArrayPool.Shared.Return(ResourcesArray); + ArrayPool.Shared.Return(VariablesArray); + } + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index d9d1f094..c4cbd824 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -24,7 +24,7 @@ namespace ComputeSharp.Shaders.Translation /// /// A responsible for loading and processing instances /// - internal sealed class ShaderLoader + internal sealed partial class ShaderLoader { /// /// The that represents the shader to load