Skip to content

[NativeAOT] Accessing static variables, ideally, should not call runtime helpers. #79436

@VSadov

Description

@VSadov

It is a bit surprising that in a completely static scenario, statically compiled code calls helpers like __GetGCStaticBase/__GetNonGCStaticBase.

I am porting some c++ code to c#/NativeAOT and I see impact on performance from this in a few tight spots.
Can the emit for statics be closer to the native compilers?

Repro:

using System.Runtime.CompilerServices;

internal class Program
{
    static int something1;
    static string something2;

    private static void Main(string[] args)
    {
        Test();
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static void Test()
    {
        something1 = 1234;
        something2 = "qwer";
        Console.WriteLine(something1 + something2);

        System.Diagnostics.Debugger.Break();
    }
}

After compiling for nativeAOT/release, I see in debugger:

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static void Test()
    {
        something1 = 1234;
00007FF6ABFE1CA0  push        rdi  
00007FF6ABFE1CA1  push        rsi  
00007FF6ABFE1CA2  sub         rsp,28h  
00007FF6ABFE1CA6  call        __GetNonGCStaticBase_ConsoleApp11_Program (07FF6ABED12F6h)    <===== ????
00007FF6ABFE1CAB  mov         rsi,rax  
00007FF6ABFE1CAE  mov         dword ptr [rsi],4D2h  
        something2 = "qwer";
00007FF6ABFE1CB4  call        __GetGCStaticBase_ConsoleApp11_Program (07FF6ABED1E0Dh)      <======????
00007FF6ABFE1CB9  mov         rdi,rax  
00007FF6ABFE1CBC  lea         rcx,[__Str_qwer (07FF6AC17D1B8h)]  
00007FF6ABFE1CC3  mov         qword ptr [rdi+8],rcx  
        Console.WriteLine(something1 + something2);
00007FF6ABFE1CC7  mov         ecx,dword ptr [rsi]  
00007FF6ABFE1CC9  call        S_P_CoreLib_System_Number__Int32ToDecStr (07FF6ABF62BD0h)  
00007FF6ABFE1CCE  mov         rcx,rax  
00007FF6ABFE1CD1  mov         rdx,qword ptr [rdi+8]  
00007FF6ABFE1CD5  call        String__Concat_5 (07FF6ABF4D150h)  
00007FF6ABFE1CDA  mov         rcx,rax  
00007FF6ABFE1CDD  call        System_Console_System_Console__WriteLine_12 (07FF6AC00ED00h)  

        System.Diagnostics.Debugger.Break();
00007FF6ABFE1CE2  call        S_P_CoreLib_System_Diagnostics_Debugger__Break (07FF6ABFA6D30h)  
    }
00007FF6ABFE1CE7  nop  
00007FF6ABFE1CE8  add         rsp,28h  
00007FF6ABFE1CEC  pop         rsi  
00007FF6ABFE1CED  pop         rdi  
00007FF6ABFE1CEE  ret  

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions