diff --git a/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs
new file mode 100644
index 00000000..3b08edd3
--- /dev/null
+++ b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs
@@ -0,0 +1,63 @@
+using System.Diagnostics.Contracts;
+using System.Linq;
+using System.Threading;
+
+namespace System.Reflection.Emit
+{
+ ///
+ /// A that can be used to easily (lol) create dynamic methods
+ ///
+ /// The type of that will be used to wrap the new methods
+ internal static class DynamicMethod where T : Delegate
+ {
+ ///
+ /// The owner type for new dynamic methods
+ ///
+ private static readonly Type OwnerType = typeof(DynamicMethod);
+
+ ///
+ /// The return type of the
+ ///
+ private static readonly Type ReturnType;
+
+ ///
+ /// The types of the arguments of the
+ ///
+ private static readonly Type[] ParameterTypes;
+
+ ///
+ /// Loads all the necessary info for the current parameter
+ ///
+ static DynamicMethod()
+ {
+ MethodInfo method = typeof(T).GetMethod("Invoke");
+ ReturnType = method.ReturnType;
+ ParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();
+ }
+
+ ///
+ /// Local counter for dynamic methods of type ever generated
+ ///
+ private static int _Count;
+
+ ///
+ /// Creates a new for the target owner
+ ///
+ /// An that builds the IL bytecode for the new method
+ /// A new dynamic method wrapped as a
+ [Pure]
+ public static T New(Action builder)
+ {
+ // Create a new dynamic method with a unique id
+ string id = $"__IL__{typeof(T).Name}_{Interlocked.Increment(ref _Count)}";
+ DynamicMethod method = new DynamicMethod(id, ReturnType, ParameterTypes, OwnerType);
+
+ // Build the IL bytecode
+ ILGenerator il = method.GetILGenerator();
+ builder(il);
+
+ // Build and delegate instance
+ return (T)method.CreateDelegate(typeof(T));
+ }
+ }
+}
diff --git a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs
index 401321a3..16f21407 100644
--- a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs
+++ b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs
@@ -1,9 +1,8 @@
-using System;
-using System.Diagnostics.Contracts;
+using System.Diagnostics.Contracts;
using System.Linq;
using System.Text.RegularExpressions;
-namespace ComputeSharp.Shaders.Extensions
+namespace System
{
///
/// A that provides extension methods for the type
diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs
index efc7b4be..8c7a0259 100644
--- a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs
+++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs
@@ -5,11 +5,8 @@ using System.Linq;
using System.Reflection;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Translation.Models;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-namespace ComputeSharp.Shaders.Extensions
+namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
///
/// A with some extension methods for C# syntax nodes
diff --git a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs
index 0b31f9cc..56b40454 100644
--- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs
+++ b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs
@@ -1,10 +1,9 @@
-using System;
-using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
-namespace ComputeSharp.Shaders.Extensions
+namespace System
{
///
/// A that provides extension methods for the type
diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs
index 411f6cb4..db9df14d 100644
--- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs
+++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs
@@ -79,39 +79,35 @@ namespace ComputeSharp.Shaders.Translation.Models
[Pure]
private Getter BuildDynamicGetter()
{
- // Create a new dynamic method for the current member
- DynamicMethod method = new DynamicMethod($"Get{Name}", typeof(object), new[] { typeof(object) }, DeclaringType);
- ILGenerator il = method.GetILGenerator();
-
- // Info for hierarchical access
- ReadableMember[] hierarchy = (Parents ?? Array.Empty()).Concat(new[] { this }).ToArray();
-
- // Load the argument (the object instance) and cast it to the right type, if needed
- if (!IsStatic)
+ return DynamicMethod.New(il =>
{
- il.Emit(OpCodes.Ldarg_0);
+ // Info for hierarchical access
+ ReadableMember[] hierarchy = (Parents ?? Array.Empty()).Concat(new[] { this }).ToArray();
- Type unboxType = hierarchy[0].DeclaringType;
- il.Emit(unboxType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, unboxType);
- }
+ // Load the argument (the object instance) and cast it to the right type, if needed
+ if (!IsStatic)
+ {
+ il.Emit(OpCodes.Ldarg_0);
- // Unroll the member access
- foreach (ReadableMember member in hierarchy)
- {
- // Get the member value with the appropriate method
- if (member.Property != null) il.EmitCall(member.IsStatic ? OpCodes.Call : OpCodes.Callvirt, member.Property.GetMethod, null);
- else if (member.Field != null) il.Emit(member.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, member.Field);
- else throw new InvalidOperationException("Field and property can't both be null at the same time");
- }
+ Type unboxType = hierarchy[0].DeclaringType;
+ il.Emit(unboxType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, unboxType);
+ }
- // Box the value, if needed
- if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType);
+ // Unroll the member access
+ foreach (ReadableMember member in hierarchy)
+ {
+ // Get the member value with the appropriate method
+ if (member.Property != null) il.EmitCall(member.IsStatic ? OpCodes.Call : OpCodes.Callvirt, member.Property.GetMethod, null);
+ else if (member.Field != null) il.Emit(member.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, member.Field);
+ else throw new InvalidOperationException("Field and property can't both be null at the same time");
+ }
- // Return the member value from the top of the evaluation stack
- il.Emit(OpCodes.Ret);
+ // Box the value, if needed
+ if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType);
- // Build and return the delegate
- return (Getter)method.CreateDelegate(typeof(Getter));
+ // Return the member value from the top of the evaluation stack
+ il.Emit(OpCodes.Ret);
+ });
}
}
}
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
index 44829285..9a361ab4 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
@@ -5,7 +5,6 @@ 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
@@ -67,58 +66,54 @@ namespace ComputeSharp.Shaders.Translation
[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();
-
- // 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)
+ return DynamicMethod.New(il =>
{
- Label label = il.DefineLabel();
+ // Declare the local variable to store the target instance
+ il.DeclareLocal(declaringType);
- // if (fieldInfo.GetValue(obj) != null) {
- il.Emit(OpCodes.Ldloc_0);
- il.Emit(OpCodes.Ldfld, fieldInfo);
- il.Emit(OpCodes.Brfalse_S, label);
+ // Load the argument (the object instance)
+ il.Emit(OpCodes.Ldarg_1);
+ il.Emit(OpCodes.Castclass, declaringType);
+ il.Emit(OpCodes.Stloc_0);
- // 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);
+ // 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();
- // hash = hash * 17 + field.Method.GetHashCode();
+ // 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.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));
+ il.Emit(OpCodes.Ret);
+ });
}
///
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
index ff2a4ae6..d9d1f094 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
@@ -6,7 +6,6 @@ using System.Reflection;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Extensions;
-using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs
index 0199e610..37d1f584 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Reflection;
-using ComputeSharp.Shaders.Extensions;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
diff --git a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs
new file mode 100644
index 00000000..a00a7726
--- /dev/null
+++ b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs
@@ -0,0 +1,45 @@
+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 square = DynamicMethod>.New(il =>
+ {
+ il.Emit(OpCodes.Ldarg_0);
+ il.Emit(OpCodes.Dup);
+ il.Emit(OpCodes.Mul);
+ il.Emit(OpCodes.Ret);
+ });
+
+ int result = square(2); // result = 2 * 2
+
+ Assert.IsTrue(result == 4);
+ }
+
+ public delegate int Square(int x);
+
+ [TestMethod]
+ public void TestSquare()
+ {
+ Square square = DynamicMethod.New(il =>
+ {
+ il.Emit(OpCodes.Ldarg_0);
+ il.Emit(OpCodes.Dup);
+ il.Emit(OpCodes.Mul);
+ il.Emit(OpCodes.Ret);
+ });
+
+ int result = square(2); // result = 2 * 2
+
+ Assert.IsTrue(result == 4);
+ }
+ }
+}