Skip to content

Linker substitutions don't optimize as much as they can #1106

@rolfbjarne

Description

@rolfbjarne

Sample code:

static void Optimizable ()
{
	if (IntPtr.Size == 8)
		Console.WriteLine ("64bit");
	else
		Console.WriteLine ("32bit");
}

Substitution xml:

<linker>
  <assembly fullname="System.Private.CoreLib">
    <type fullname="System.IntPtr">
      <method signature="System.Int32 get_Size()" body="stub" value="8" />
    </type>
  </assembly>
</linker>

Initial IL:

default void Optimizable ()  cil managed 
    {
	.maxstack 2
	.locals init (
		bool	V_0)
	IL_0000:  nop 
	IL_0001:  call int32 native int::get_Size()
	IL_0006:  ldc.i4.8 
	IL_0007:  ceq 
	IL_0009:  stloc.0 
	IL_000a:  ldloc.0 
	IL_000b:  brfalse.s IL_001a

	IL_000d:  ldstr "64bit"
	IL_0012:  call void class [mscorlib]System.Console::WriteLine(string)
	IL_0017:  nop 
	IL_0018:  br.s IL_0025

	IL_001a:  ldstr "32bit"
	IL_001f:  call void class [mscorlib]System.Console::WriteLine(string)
	IL_0024:  nop 
	IL_0025:  ret 
    } // end of method Application::Optimizable

Post-linked IL:

default void Optimizable ()  cil managed 
    {
	.maxstack 2
	.locals init (
		bool	V_0)
	IL_0000:  nop 
	IL_0001:  call int32 class [System.Private.CoreLib]System.IntPtr::get_Size()
	IL_0006:  ldc.i4.8 
	IL_0007:  ceq 
	IL_0009:  stloc.0 
	IL_000a:  ldloc.0 
	IL_000b:  pop 
	IL_000c:  ldstr "64bit"
	IL_0011:  call void class [mscorlib]System.Console::WriteLine(string)
	IL_0016:  nop 
	IL_0017:  br.s IL_0019

	IL_0019:  ret 
    } // end of method Application::Optimizable

it seems the optimized C# would be:

static void Optimizable ()
{
	if (IntPtr.Size == 8)
		Console.WriteLine ("64bit");
}

But we can do better, I want the optimized C# to look like this:

static void Optimizable ()
{
	Console.WriteLine ("64bit");
}

Desired IL:

default void Optimized ()  cil managed 
    {
	.maxstack 8
	IL_0000:  ldstr "64bit"
	IL_0005:  call void class [mscorlib]System.Console::WriteLine(string)
	IL_000c:  ret 
    } // end of method Application::Optimized

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions