Skip to content

Better IL output for property/field initializers #11556

Open

Description

@TIHan

F#:

open System.Runtime.CompilerServices

type Test =

    [<DefaultValue(true)>]
    val mutable X : int

    new() = { }

[<MethodImpl(MethodImplOptions.NoInlining)>]
let test() =
    Test(X = 1)

[<EntryPoint>]
let main _ =
    0

Currently, F# compiler produces this IL:

.method public static class Program/Test 
        test() cil managed noinlining
{
  // Code size       15 (0xf)
  .maxstack  4
  .locals init (class Program/Test V_0)
  IL_0000:  newobj     instance void Program/Test::.ctor()
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  ldc.i4.1
  IL_0008:  stfld      int32 Program/Test::X
  IL_000d:  ldloc.0
  IL_000e:  ret
} // end of method Program::test

However, the IL could be simplified to:

.method public static class Program/Test 
        test() cil managed noinlining
{
  .maxstack  4
  IL_0xxx:  newobj     instance void Program/Test::.ctor()
  IL_0xxx:  dup
  IL_0xxx:  ldc.i4.1
  IL_0xxx:  stfld      int32 Program/Test::X
  IL_0xxx:  ret
}

No locals are produced and we have less instructions emitted.

@kerams - pinging you as I know you are interested in this stuff :)

I have some ideas on how to tackle this, but there may be better approaches that I'm not aware of.

Activity

  1. changed the title [-]Better IL output for property initializers[/-] [+]Better IL output for property/field initializers[/+] on May 12, 2021
  2. kerams commented on May 12, 2021

    @kerams
    Contributor
  3. TIHan commented on May 18, 2021

    @TIHan
    ContributorAuthor

    I believe there is still merit to cleaner IL even if the JIT produces the same efficient code. The JIT may or may not inline a method depending on its size.

  4. added this to the Backlog milestone on May 18, 2021
  5. added
    Area-Compiler-CodeGen
    on Apr 20, 2022
  6. added 4 commits that reference this issue on Feb 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-Compiler-CodeGenFeature Request

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions