Merge pull request #55 from Sergio0694/feature_il-hashcode
Unrolled hashcode generation
このコミットが含まれているのは:
5ファイル変更
+227
-29
検索条件に一致するファイルはありません
@@ -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
|
||||
/// <summary>
|
||||
/// The mapping used to cache and reuse compiled shaders
|
||||
/// </summary>
|
||||
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>();
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
|
||||
@@ -60,10 +61,10 @@ namespace ComputeSharp.Shaders
|
||||
Action<ThreadIds> action)
|
||||
{
|
||||
// Try to get the cache shader
|
||||
(ShaderLoader Loader, ShaderBytecode Bytecode) shaderData;
|
||||
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
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using Vortice.Direct3D12;
|
||||
|
||||
namespace ComputeSharp.Shaders.Translation.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="struct"/> that contains info on a cached shader
|
||||
/// </summary>
|
||||
internal readonly struct CachedShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="ShaderLoader"/> instance with the shader metadata
|
||||
/// </summary>
|
||||
public readonly ShaderLoader Loader;
|
||||
|
||||
/// <summary>
|
||||
/// The compiled shader bytecode
|
||||
/// </summary>
|
||||
public readonly ShaderBytecode Bytecode;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="CachedShader"/> instance with the specified parameters
|
||||
/// </summary>
|
||||
/// <param name="loader">The <see cref="ShaderLoader"/> instance with the shader metadata</param>
|
||||
/// <param name="bytecode">The compiled shader bytecode</param>
|
||||
public CachedShader(ShaderLoader loader, ShaderBytecode bytecode)
|
||||
{
|
||||
Loader = loader;
|
||||
Bytecode = bytecode;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="static"/> <see langword="class"/> that handles the cache system for the generated shaders
|
||||
/// </summary>
|
||||
internal static class ShaderHashCodeProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping of hashcodes to aggregate hashing functions
|
||||
/// </summary>
|
||||
private static readonly Dictionary<int, Hasher?> HasherMapping = new Dictionary<int, Hasher?>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a unique hashcode for the input shader closure
|
||||
/// </summary>
|
||||
/// <param name="action">The input <see cref="Action{T}"/> representing the shader to run</param>
|
||||
[Pure]
|
||||
public static int GetHashCode(Action<ThreadIds> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="delegate"/> that represents an aggregate hash function for a given instance
|
||||
/// </summary>
|
||||
/// <param name="hash">The initial hash value</param>
|
||||
/// <param name="instance">The closure instance to use to compute the final hash value</param>
|
||||
/// <returns>The final hash value for the input closure</returns>
|
||||
private delegate int Hasher(int hash, object instance);
|
||||
|
||||
/// <summary>
|
||||
/// Builds a new <see cref="Hasher"/> instance for the target <see cref="Type"/> and sequence of <see cref="FieldInfo"/> values
|
||||
/// </summary>
|
||||
/// <param name="declaringType">The declaring <see cref="Type"/> to analyze</param>
|
||||
/// <param name="fieldInfos">The list of captured fields to inspect</param>
|
||||
[Pure]
|
||||
private static Hasher BuildDynamicHasher(Type declaringType, IReadOnlyCollection<FieldInfo> 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();
|
||||
|
||||
// Declare the local variable to store the target instance
|
||||
il.DeclareLocal(declaringType);
|
||||
|
||||
// Load the argument (the object instance)
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
il.Emit(OpCodes.Castclass, declaringType);
|
||||
il.Emit(OpCodes.Stloc_0);
|
||||
|
||||
// Unroll the member access
|
||||
MethodInfo
|
||||
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)
|
||||
{
|
||||
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.Call, 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A method that checks whether an input <see cref="Delegate"/> is supported in HLSL
|
||||
/// </summary>
|
||||
/// <param name="candidate">The input <see cref="Delegate"/> instance to check</param>
|
||||
[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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,31 +147,6 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList => _LocalFunctionsList;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a unique hash code for a given <see cref="Action{T}"/>
|
||||
/// </summary>
|
||||
/// <param name="action">The input <see cref="Action{T}"/> instance to inspect</param>
|
||||
[Pure]
|
||||
public static int GetHashCode(Action<ThreadIds> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads and processes an input <see cref="Action{T}"/>
|
||||
/// </summary>
|
||||
|
||||
@@ -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<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
|
||||
|
||||
Action<ThreadIds> action1 = id => buffer[0] = value;
|
||||
|
||||
int
|
||||
hash1 = ShaderHashCodeProvider.GetHashCode(action1),
|
||||
hash2 = ShaderHashCodeProvider.GetHashCode(action1);
|
||||
|
||||
Assert.IsTrue(hash1 == hash2);
|
||||
|
||||
Action<ThreadIds> action2 = id => buffer[0] = value;
|
||||
|
||||
int hash3 = ShaderHashCodeProvider.GetHashCode(action2);
|
||||
|
||||
Assert.IsFalse(hash1 == hash3);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ShaderWithCapturedDelegates()
|
||||
{
|
||||
Func<float, float> f = x => x * x;
|
||||
|
||||
using ReadWriteBuffer<float> buffer = Gpu.Default.AllocateReadWriteBuffer<float>(1);
|
||||
|
||||
Action<ThreadIds> action = id => buffer[0] = f(2);
|
||||
|
||||
int
|
||||
hash1 = ShaderHashCodeProvider.GetHashCode(action),
|
||||
hash2 = ShaderHashCodeProvider.GetHashCode(action);
|
||||
|
||||
Assert.IsTrue(hash1 == hash2);
|
||||
|
||||
f = x => x + 1;
|
||||
|
||||
int hash3 = ShaderHashCodeProvider.GetHashCode(action);
|
||||
|
||||
Assert.IsFalse(hash1 == hash3);
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする