tags:

views:

384

answers:

2

Im generating some IL with the ILGenerator here is my code:

DynamicMethod method = new DynamicMethod("test", null, Type.EmptyTypes);
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Ldc_I4_S, 100);

This generated this IL:

IL_0000:  ldarg.0    
IL_0001:  ldarg.1    
IL_0002:  ldc.i4.s   100
IL_0004:  nop        
IL_0005:  nop        
IL_0006:  nop

(I get the IL Code from a VS Virtulizer named ILStream)

From where do the nops code? is there any way to get rid of them? Im trying to imitate some c# code and it doesn't have 3 nops.

+1  A: 

Compile in release mode to get rid of the nop opcodes.

Romain Verdier
how do i tell the ILGenerator to write Release mode code?
Petoj
Well, you obviously can't, since when you're emitting opcodes, you basically act as a compiler: you write IL. So my answer is a bit dumb, but at least it emphasis the fact that nop codes don't change anything. They often are generated for debugging purposes, but a DynamicMethod can't be debugged, so they will be ignored during the JITing. Also, maybe the visualizer you use is just wrong.
Romain Verdier
Well i guess the visualizer is right as it haven't shown any thing wrong so far.. and sure nop doesn't change any thing but why generate them if they aren't any use?
Petoj
+2  A: 

I solved the problem by casting the int to a value:

Code:

private static bool IsBetween(int value, int min, int max)
{
    return (value >= min && value <= max);
}

private static void WriteInt(ILGenerator gen, int value)
{
    gen.Emit(OpCodes.Ldarg_1);
    if (IsBetween(value, sbyte.MinValue, sbyte.MaxValue))
    {
        gen.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
    }
    else if (IsBetween(value, byte.MinValue, byte.MaxValue))
    {
        gen.Emit(OpCodes.Ldc_I4_S, (byte)value);
    }
    else if (IsBetween(value, short.MinValue, short.MaxValue))
    {
        gen.Emit(OpCodes.Ldc_I4_S, (short)value);
    }
    else
    {
        gen.Emit(OpCodes.Ldc_I4_S, value);
    }
}
Petoj