From f369c019a511c599ebb4b03fab8759b0d7e29dd5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 00:53:44 +0200 Subject: [PATCH 1/9] Added unit tests for the shader hashcode --- .../ShaderHashCodeTests.cs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs new file mode 100644 index 00000000..b8d06d9a --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -0,0 +1,54 @@ +using System; +using ComputeSharp.Shaders.Translation; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.Internals +{ + [TestClass] + [TestCategory("ShaderHashCodes")] + public class ShaderHashCodeTests + { + [TestMethod] + public void ShaderWithNoCapturedDelegates() + { + float value = 10; + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action1 = id => buffer[0] = value; + + int + hash1 = ShaderLoader.GetHashCode(action1), + hash2 = ShaderLoader.GetHashCode(action1); + + Assert.IsTrue(hash1 == hash2); + + Action action2 = id => buffer[0] = value; + + int hash3 = ShaderLoader.GetHashCode(action2); + + Assert.IsFalse(hash1 == hash3); + } + + [TestMethod] + public void ShaderWithCapturedDelegates() + { + Func f = x => x * x; + + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action = id => buffer[0] = f(2); + + int + hash1 = ShaderLoader.GetHashCode(action), + hash2 = ShaderLoader.GetHashCode(action); + + Assert.IsTrue(hash1 == hash2); + + f = x => x + 1; + + int hash3 = ShaderLoader.GetHashCode(action); + + Assert.IsFalse(hash1 == hash3); + } + } +} From 90a326aef55451285bfad0360b68c5fbbe3f8db1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 03:03:42 +0200 Subject: [PATCH 2/9] Added draft ShaderCacheManager class --- .../Translation/ShaderCacheManager.cs | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Translation/ShaderCacheManager.cs diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCacheManager.cs b/src/ComputeSharp.Shaders/Translation/ShaderCacheManager.cs new file mode 100644 index 00000000..3a451d62 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderCacheManager.cs @@ -0,0 +1,132 @@ +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; +using ComputeSharp.Shaders.Mappings; + +namespace ComputeSharp.Shaders.Translation +{ + /// + /// A that handles the cache system for the generated shaders + /// + internal static class ShaderCacheManager + { + /// + /// The mapping of hashcodes to aggregate hashing functions + /// + private static readonly Dictionary HasherMapping = new Dictionary(); + + /// + /// Gets a unique key for the input shader closure + /// + /// The input representing the shader to run + private static int GetKey(Action action) + { + // Get the delegate hashcode + MethodInfo methodInfo = action.Method; + int hash = methodInfo.GetHashCode(); + + if (!HasherMapping.TryGetValue(hash, out Hasher? hasher)) + { + // Get the candidate fields for delegate checking + FieldInfo[] delegateFieldInfos = ( + from fieldInfo in methodInfo.DeclaringType.GetFields() + where fieldInfo.FieldType.IsDelegate() && + fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || HlslKnownTypes.IsKnownVectorType(type)) + select fieldInfo).ToArray(); + + // If at least one captured delegate is present, build the hasher method + hasher = delegateFieldInfos.Length == 0 ? null : BuildDynamicHasher(action.Method.DeclaringType, delegateFieldInfos); + HasherMapping.Add(hash, hasher); + } + + // Aggregate the hash of the captured delegates, if needed + if (hasher != null) hash = hasher(hash, action.Target); + + return hash; + } + + /// + /// A that represents an aggregate hash function for a given instance + /// + /// The source object to get the member from + /// The value of the member, upcast to + private delegate int Hasher(int hash, object instance); + + /// + /// Builds a new instance for the target and sequence of values + /// + /// The declaring to analyze + /// The list of captured fields to inspect + [Pure] + private static Hasher BuildDynamicHasher(Type declaringType, IReadOnlyCollection fieldInfos) + { + // Create a new dynamic method for the current member + DynamicMethod method = new DynamicMethod("GetHashCodeForHlslDelegates", typeof(int), new[] { typeof(int), typeof(object) }, declaringType); + ILGenerator il = method.GetILGenerator(); + + // Load the argument (the object instance) + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Castclass, declaringType); + il.Emit(OpCodes.Stloc_0); + + // Unroll the member access + MethodInfo + validateDelegateInfo = typeof(ShaderCacheManager).GetMethod(nameof(ValidateDelegate)), + getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, + getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); + foreach (FieldInfo fieldInfo in fieldInfos) + { + Label label = il.DefineLabel(); + + // if (fieldInfo.GetValue(obj) != null) { + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldfld, fieldInfo); + il.Emit(OpCodes.Brfalse_S, label); + + // if (ValidateDelegate(field)) { + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldfld, fieldInfo); + il.EmitCall(OpCodes.Callvirt, validateDelegateInfo, null); + il.Emit(OpCodes.Brfalse_S, label); + + // hash = hash * 17 + field.Method.GetHashCode(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, 17); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Ldloc_0); + 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, 0); + + il.MarkLabel(label); + } + + // Return the computed hash + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ret); + + // Build and return the delegate + return (Hasher)method.CreateDelegate(typeof(Hasher)); + } + + /// + /// A method that checks whether an input is supported in HLSL + /// + /// The input instance to check + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool ValidateDelegate(Delegate candidate) + { + MethodInfo methodInfo = candidate.Method; + return (methodInfo.IsStatic || methodInfo.DeclaringType.IsStatelessDelegateContainer()) && + (HlslKnownTypes.IsKnownScalarType(methodInfo.ReturnType) || HlslKnownTypes.IsKnownVectorType(methodInfo.ReturnType)); + } + } +} From 0be404c9b32356a501b6c8fe2204109e58d3dbca Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 03:20:21 +0200 Subject: [PATCH 3/9] Minor code refactoring --- src/ComputeSharp.Shaders/ShaderRunner.cs | 7 +++-- .../Translation/Models/CachedShader.cs | 31 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 2b0ac27f..40da9b5e 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -7,6 +7,7 @@ using ComputeSharp.Graphics.Buffers.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; +using ComputeSharp.Shaders.Translation.Models; using Vortice.Direct3D12; using CommandList = ComputeSharp.Graphics.Commands.CommandList; using PipelineState = ComputeSharp.Graphics.Commands.PipelineState; @@ -40,7 +41,7 @@ namespace ComputeSharp.Shaders /// /// The mapping used to cache and reuse compiled shaders /// - private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), (ShaderLoader, ShaderBytecode)> ShadersCache = new Dictionary<(int, int, int, int), (ShaderLoader, ShaderBytecode)>(); + private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), CachedShader> ShadersCache = new Dictionary<(int, int, int, int), CachedShader>(); /// /// Compiles and runs the input shader on a target instance, with the specified parameters @@ -60,7 +61,7 @@ namespace ComputeSharp.Shaders Action action) { // Try to get the cache shader - (ShaderLoader Loader, ShaderBytecode Bytecode) shaderData; + CachedShader shaderData; lock (ShadersCache) { var key = (ShaderLoader.GetHashCode(action), threadsX, threadsY, threadsZ); @@ -88,7 +89,7 @@ namespace ComputeSharp.Shaders ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource); // Cache for later use - shaderData = (shaderLoader, shaderBytecode); + shaderData = new CachedShader(shaderLoader, shaderBytecode); ShadersCache.Add(key, shaderData); } } diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs new file mode 100644 index 00000000..8c5cf20c --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs @@ -0,0 +1,31 @@ +using Vortice.Direct3D12; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A that contains info on a cached shader + /// + internal readonly struct CachedShader + { + /// + /// The instance with the shader metadata + /// + public readonly ShaderLoader Loader; + + /// + /// The compiled shader bytecode + /// + public readonly ShaderBytecode Bytecode; + + /// + /// Creates a new instance with the specified parameters + /// + /// The instance with the shader metadata + /// The compiled shader bytecode + public CachedShader(ShaderLoader loader, ShaderBytecode bytecode) + { + Loader = loader; + Bytecode = bytecode; + } + } +} From 57ae15ab7f826177921c6d57f95d74497976e874 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 03:23:58 +0200 Subject: [PATCH 4/9] Renamed shader hash code class --- .../{ShaderCacheManager.cs => ShaderHashCodeProvider.cs} | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) rename src/ComputeSharp.Shaders/Translation/{ShaderCacheManager.cs => ShaderHashCodeProvider.cs} (94%) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCacheManager.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs similarity index 94% rename from src/ComputeSharp.Shaders/Translation/ShaderCacheManager.cs rename to src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 3a451d62..faa65d0b 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCacheManager.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.Shaders.Translation /// /// A that handles the cache system for the generated shaders /// - internal static class ShaderCacheManager + internal static class ShaderHashCodeProvider { /// /// The mapping of hashcodes to aggregate hashing functions @@ -21,10 +21,11 @@ namespace ComputeSharp.Shaders.Translation private static readonly Dictionary HasherMapping = new Dictionary(); /// - /// Gets a unique key for the input shader closure + /// Gets a unique hashcode for the input shader closure /// /// The input representing the shader to run - private static int GetKey(Action action) + [Pure] + public static int GetHashCode(Action action) { // Get the delegate hashcode MethodInfo methodInfo = action.Method; @@ -76,7 +77,7 @@ namespace ComputeSharp.Shaders.Translation // Unroll the member access MethodInfo - validateDelegateInfo = typeof(ShaderCacheManager).GetMethod(nameof(ValidateDelegate)), + validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate)), getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); foreach (FieldInfo fieldInfo in fieldInfos) From 64c39499621a1368c7e21445dedf47764e1f5478 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 03:25:51 +0200 Subject: [PATCH 5/9] Moved code to new hashcode implementation --- src/ComputeSharp.Shaders/ShaderRunner.cs | 2 +- .../Translation/ShaderLoader.cs | 25 ------------------- .../ShaderHashCodeTests.cs | 12 ++++----- 3 files changed, 7 insertions(+), 32 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 40da9b5e..944aee43 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -64,7 +64,7 @@ namespace ComputeSharp.Shaders CachedShader shaderData; lock (ShadersCache) { - var key = (ShaderLoader.GetHashCode(action), threadsX, threadsY, threadsZ); + var key = (ShaderHashCodeProvider.GetHashCode(action), threadsX, threadsY, threadsZ); if (!ShadersCache.TryGetValue(key, out shaderData)) { // Load the input shader diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 7c6faaa8..ed75fcee 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -147,31 +147,6 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyList LocalFunctionsList => _LocalFunctionsList; - /// - /// Gets a unique hash code for a given - /// - /// The input instance to inspect - [Pure] - public static int GetHashCode(Action action) - { - int hashcode = action.Method.GetHashCode(); - - foreach (FieldInfo fieldInfo in action.Method.DeclaringType.GetFields()) - { - if (fieldInfo.FieldType.IsDelegate() && - fieldInfo.GetValue(action.Target) is Delegate func && - (func.Method.IsStatic || func.Method.DeclaringType.IsStatelessDelegateContainer()) && - (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) && - fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || - HlslKnownTypes.IsKnownVectorType(type))) - { - hashcode = unchecked(hashcode * 17 + func.Method.GetHashCode()); - } - } - - return hashcode; - } - /// /// Loads and processes an input /// diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs index b8d06d9a..bd0dfa99 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -17,14 +17,14 @@ namespace ComputeSharp.Tests.Internals Action action1 = id => buffer[0] = value; int - hash1 = ShaderLoader.GetHashCode(action1), - hash2 = ShaderLoader.GetHashCode(action1); + hash1 = ShaderHashCodeProvider.GetHashCode(action1), + hash2 = ShaderHashCodeProvider.GetHashCode(action1); Assert.IsTrue(hash1 == hash2); Action action2 = id => buffer[0] = value; - int hash3 = ShaderLoader.GetHashCode(action2); + int hash3 = ShaderHashCodeProvider.GetHashCode(action2); Assert.IsFalse(hash1 == hash3); } @@ -39,14 +39,14 @@ namespace ComputeSharp.Tests.Internals Action action = id => buffer[0] = f(2); int - hash1 = ShaderLoader.GetHashCode(action), - hash2 = ShaderLoader.GetHashCode(action); + hash1 = ShaderHashCodeProvider.GetHashCode(action), + hash2 = ShaderHashCodeProvider.GetHashCode(action); Assert.IsTrue(hash1 == hash2); f = x => x + 1; - int hash3 = ShaderLoader.GetHashCode(action); + int hash3 = ShaderHashCodeProvider.GetHashCode(action); Assert.IsFalse(hash1 == hash3); } From f398852bbba09744abf916e36426672f7966626c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 03:26:03 +0200 Subject: [PATCH 6/9] Added missing binding flags --- src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index faa65d0b..f913da95 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -77,7 +77,7 @@ namespace ComputeSharp.Shaders.Translation // Unroll the member access MethodInfo - validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate)), + validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate), BindingFlags.NonPublic | BindingFlags.Static), getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); foreach (FieldInfo fieldInfo in fieldInfos) From fdcaa8906d48e37be2529cb1b068207df842788e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 03:36:09 +0200 Subject: [PATCH 7/9] Fixed IL errors --- .../Translation/ShaderHashCodeProvider.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index f913da95..c429b779 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -70,8 +70,11 @@ namespace ComputeSharp.Shaders.Translation DynamicMethod method = new DynamicMethod("GetHashCodeForHlslDelegates", typeof(int), new[] { typeof(int), typeof(object) }, declaringType); ILGenerator il = method.GetILGenerator(); + // Declare the local variable to store the target instance + il.DeclareLocal(declaringType); + // Load the argument (the object instance) - il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Castclass, declaringType); il.Emit(OpCodes.Stloc_0); From f4ae1ab5ab54463d7a682e38a50f55d171ce677b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 03:40:25 +0200 Subject: [PATCH 8/9] Fixed call opcode in hasher IL generation --- src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index c429b779..1c398ca0 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -95,7 +95,7 @@ namespace ComputeSharp.Shaders.Translation // if (ValidateDelegate(field)) { il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldfld, fieldInfo); - il.EmitCall(OpCodes.Callvirt, validateDelegateInfo, null); + il.EmitCall(OpCodes.Call, validateDelegateInfo, null); il.Emit(OpCodes.Brfalse_S, label); // hash = hash * 17 + field.Method.GetHashCode(); From 5918371e58fe6dd4a38465aefbfaabd272a79574 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 16 Sep 2019 12:35:54 +0200 Subject: [PATCH 9/9] Fixed some XML comments --- .../Translation/ShaderHashCodeProvider.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 1c398ca0..44829285 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -54,8 +54,9 @@ namespace ComputeSharp.Shaders.Translation /// /// A that represents an aggregate hash function for a given instance /// - /// The source object to get the member from - /// The value of the member, upcast to + /// The initial hash value + /// The closure instance to use to compute the final hash value + /// The final hash value for the input closure private delegate int Hasher(int hash, object instance); ///