From 533f07f10e18f51faaa4ef1e4aca67872686da25 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 15:09:58 +0200 Subject: [PATCH] Added initial ILGeneratorExtensions class --- .../Extensions/ILGeneratorExtensions.cs | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs new file mode 100644 index 00000000..57855ccb --- /dev/null +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -0,0 +1,58 @@ +using System.Runtime.InteropServices; + +namespace System.Reflection.Emit +{ + /// + /// A that provides extension methods for the type + /// + internal static class ILGeneratorExtensions + { + /// + /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions + /// + /// The input instance to use to emit instructions + /// The offset to use to advance the current reference on top of the execution stack + public static void EmitAddByteOffset(this ILGenerator il, int offset) + { + // Push the offset to the stack + if (offset > 8) il.Emit(OpCodes.Ldc_I4, offset); + else + { + il.Emit(offset switch + { + 1 => OpCodes.Ldc_I4_1, + 2 => OpCodes.Ldc_I4_2, + 4 => OpCodes.Ldc_I4_4, + 8 => OpCodes.Ldc_I4_8, + _ => throw new InvalidOperationException("Huh?") + }); + } + + // Converts the offset to native int and adds to the address + il.Emit(OpCodes.Conv_I); + il.Emit(OpCodes.Add); + } + + /// + /// Puts the appropriate or instruction to write to a reference onto the stream of instructions + /// + /// The input instance to use to emit instructions + /// The type of value being written to the current reference on top of the execution stack + public static void EmitStoreToAddress(this ILGenerator il, Type type) + { + il.Emit(Marshal.SizeOf(type) switch + { + // Use the faster op codes for sizes <= 8 + 1 => OpCodes.Stind_I1, + 2 => OpCodes.Stind_I2, + 4 when type == typeof(float) => OpCodes.Stind_R4, + 4 => OpCodes.Stind_I4, + 8 when type == typeof(double) => OpCodes.Stind_R8, + 8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8, + + // Default to stobj for all other value types + _ => OpCodes.Stobj + }); + } + } +}