diff --git a/src/ComputeSharp.Shaders/Properties/AssemblyInfo.cs b/src/ComputeSharp.Shaders/Properties/AssemblyInfo.cs index 6b57bd31..1b03d252 100644 --- a/src/ComputeSharp.Shaders/Properties/AssemblyInfo.cs +++ b/src/ComputeSharp.Shaders/Properties/AssemblyInfo.cs @@ -1,3 +1,4 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("ComputeSharp")] +[assembly: InternalsVisibleTo("ComputeSharp.Tests.Internals")] diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs new file mode 100644 index 00000000..ce0150e3 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Reflection.Emit; + +namespace ComputeSharp.Shaders.Translation.Models +{ + internal sealed partial class ReadableMember + { + /// + /// The mapping of members to getter delegates + /// + private static readonly Dictionary GettersMapping = new Dictionary(); + + /// + /// The local instance, if already loaded + /// + private Getter? _Getter; + + /// + /// Returns the value of the wrapped member for the current instance + /// + /// The target instance to use to read the value from + [Pure] + public object GetValue(object? instance) + { + if (_Getter == null) + { + /* If the local delegate is available, use it and save the dictionary + * access entirely. If it's not, try to get the delegate from the dictionary + * first. This can save unnecessary overhead if a delegate for the same member has + * already been built, eg. if it belongs to a captured field that is used by two different + * shaders in the same closure. Once the getter is built, cache it and invoke it */ + if (GettersMapping.TryGetValue(Id, out Getter getter)) _Getter = getter; + else + { + _Getter = getter = BuildDynamicGetter(); + GettersMapping.Add(Id, getter); + } + + } + + return _Getter(instance); + } + + /// + /// A that represents a getter for a specific member + /// + /// The source object to get the member from + /// The value of the member, upcast to + private delegate object Getter(object? obj); + + /// + /// Builds a dynamic IL method to retrieve the value of the current member + /// + [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(); + + // Load the argument (the object instance) and cast it to the right type, if needed + if (!IsStatic) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(DeclaringType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, DeclaringType); + } + + // Get the member value with the appropriate method + if (Property != null) il.EmitCall(IsStatic ? OpCodes.Call : OpCodes.Callvirt, Property.GetMethod, null); + else if (Field != null) il.Emit(IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, Field); + else throw new InvalidOperationException("Field and property can't both be null at the same time"); + + // Box the value, if needed + if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType); + + // Return the member value from the top of the evaluation stack + il.Emit(OpCodes.Ret); + + // Build and return the delegate + return (Getter)method.CreateDelegate(typeof(Getter)); + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs index b0ba6344..9883fd52 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics.Contracts; using System.Reflection; namespace ComputeSharp.Shaders.Translation.Models @@ -7,8 +6,13 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// A that wraps a readable member of another and provides access to it /// - internal sealed class ReadableMember + internal sealed partial class ReadableMember { + /// + /// The id of the current member + /// + private readonly string Id; + /// /// The object wrapped by the current instance, if present /// @@ -22,70 +26,60 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// Creates a new instance with the given parameters /// - /// The optional object wrapped by the current instance - /// The optional object wrapped by the current instance - private ReadableMember(FieldInfo? field, PropertyInfo? property) + /// The target object wrapped by the current instance + private ReadableMember(MemberInfo memberInfo) { - Field = field; - Property = property; - } + // General properties + Name = memberInfo.Name; + Id = $"{memberInfo.DeclaringType.FullName}{Type.Delimiter}{Name}"; + DeclaringType = memberInfo.DeclaringType; - /// - /// Gets the where the current member is declared in - /// - public Type DeclaringType - { - get + // Type specific properties + if (memberInfo is FieldInfo fieldInfo) { - if (Field != null) return Field.DeclaringType; - if (Property != null) return Property.DeclaringType; - - throw new InvalidOperationException("Field and property can't both be null at the same time"); + Field = fieldInfo; + IsStatic = Field.IsStatic; + MemberType = Field.FieldType; } - } - - /// - /// Gets the of the wrapped member for the current instance - /// - public Type MemberType - { - get + else if (memberInfo is PropertyInfo propertyInfo) { - if (Field != null) return Field.FieldType; - if (Property != null) return Property.PropertyType; - - throw new InvalidOperationException("Field and property can't both be null at the same time"); + Property = propertyInfo; + IsStatic = Property.GetMethod.IsStatic; + MemberType = Property.PropertyType; } + else throw new InvalidOperationException("Field and property can't both be null at the same time"); } /// /// Gets the name of the wrapped member for the current instance /// - public string Name => (Field?.Name ?? Property?.Name) ?? throw new InvalidOperationException("Field and property can't both be null at the same time"); + public string Name { get; } /// - /// Returns the value of the wrapped member for the current instance + /// Gets whether or not the current member is not an instance member /// - /// The target instance to use to read the value from - [Pure] - public object GetValue(object? instance) - { - if (Field != null) return Field.GetValue(instance); - if (Property != null) return Property.GetValue(instance); + public bool IsStatic { get; } - throw new InvalidOperationException("Field and property can't both be null at the same time"); - } + /// + /// Gets the where the current member is declared in + /// + public Type DeclaringType { get; } + + /// + /// Gets the of the wrapped member for the current instance + /// + public Type MemberType { get; } /// /// Converts a object into a instance /// /// The input object to wrap - public static implicit operator ReadableMember(FieldInfo field) => new ReadableMember(field, null); + public static implicit operator ReadableMember(FieldInfo field) => new ReadableMember(field); /// /// Converts a object into a instance /// /// The input object to wrap - public static implicit operator ReadableMember(PropertyInfo property) => new ReadableMember(null, property); + public static implicit operator ReadableMember(PropertyInfo property) => new ReadableMember(property); } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index ad044b2d..cda801e0 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -85,14 +85,15 @@ namespace ComputeSharp.Shaders.Translation /// The to use to build the shader public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) { - foreach (var (item, i) in _BufferMembers.Select((item, i) => (item, i))) + int index = 1; + foreach (var item in _BufferMembers) { - if (item.Parents == null) yield return (i + 1, (GraphicsResource)item.Member.GetValue(action.Target)); - else - { - object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj)); - yield return (i + 1, (GraphicsResource)item.Member.GetValue(target)); - } + object target = action.Target; + if (item.Parents != null) + foreach (var parent in item.Parents) + target = parent.GetValue(target); + + yield return (index++, (GraphicsResource)item.Member.GetValue(target)); } } @@ -109,12 +110,12 @@ namespace ComputeSharp.Shaders.Translation { foreach (var item in _VariableMembers) { - if (item.Parents == null) yield return item.Member.GetValue(action.Target); - else - { - object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj)); - yield return item.Member.GetValue(target); - } + object target = action.Target; + if (item.Parents != null) + foreach (var parent in item.Parents) + target = parent.GetValue(target); + + yield return item.Member.GetValue(target); } } diff --git a/tests/ComputeSharp.Tests.Internals/ReadableMemberTests.cs b/tests/ComputeSharp.Tests.Internals/ReadableMemberTests.cs new file mode 100644 index 00000000..396ced28 --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals/ReadableMemberTests.cs @@ -0,0 +1,72 @@ +using ComputeSharp.Shaders.Translation.Models; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Numerics; +using System.Reflection; + +namespace ComputeSharp.Tests.Internals +{ + /// + /// A container for static fields and properties to test + /// + public sealed class StaticMembersContainer + { + /// + /// A field + /// + public static readonly int Field = 7; + + /// + /// A property + /// + public static int Property { get; } = 44; + } + + [TestClass] + [TestCategory("ReadableMembers")] + public class ReadableMemberTests + { + [TestMethod] + public void PropertyGetter() + { + string text = "Hello world"; + + ReadableMember member = typeof(string).GetProperty(nameof(string.Length)); + + object value = member.GetValue(text); + + Assert.IsTrue((int)value == text.Length); + } + + [TestMethod] + public void FieldGetter() + { + Vector4 vector = new Vector4(7, 0, 0, 0); + + ReadableMember member = typeof(Vector4).GetField(nameof(Vector4.X)); + + object value = member.GetValue(vector); + + Assert.IsTrue((int)(float)value == (int)vector.X); + } + + [TestMethod] + public void StaticFieldGetter() + { + ReadableMember member = typeof(StaticMembersContainer).GetField(nameof(StaticMembersContainer.Field), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + + object value = member.GetValue(null); + + Assert.IsTrue((int)value == StaticMembersContainer.Field); + } + + [TestMethod] + public void StaticPropertyGetter() + { + ReadableMember member = typeof(StaticMembersContainer).GetProperty(nameof(StaticMembersContainer.Property), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + + object value = member.GetValue(null); + + Assert.IsTrue((int)value == StaticMembersContainer.Property); + } + } +}