Skip to content

Conversation

EgorBo
Copy link
Member

@EgorBo EgorBo commented Sep 12, 2025

I noticed that sometimes developers make assumptions that it's fine to use Unsafe.AsPointer over RVA fields since they're not movable, which is fairly unreliable thing to do (e.g. Unloadable ALCs). So let's just optimize the pinning overhead in JIT when we know it's safe to do so:

// Case 0: RVA fields
void Test0()
{
    ReadOnlySpan<int> rva = [1,2,3,4,5];
    fixed (int* p = rva)
        Consume(p);
}

// Case 1: Primitive static fields (unmanaged memory)
static int _primitiveFld;
void Test1()
{
    fixed (int* p = &_primitiveFld)
        Consume(p);
}


// Case 2: Struct static fields (boxed and stored on the NonGC heap)
static MyStruct _structFld;
void Test2()
{
    fixed (int* p = &_structFld.Y)
        Consume(p);
}

Codegen diff: https://www.diffchecker.com/LgIALnAn/

@github-actions github-actions bot added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Sep 12, 2025
Copy link
Contributor

Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.

@EgorBo
Copy link
Member Author

EgorBo commented Sep 13, 2025

@MihuBot

private bool canOmitPinning(CORINFO_FIELD_STRUCT_* fldHnd)
{
FieldDesc field = HandleToObject(fldHnd);
if (!field.IsStatic || field.IsThreadStatic || field.HasGCStaticBase || field.OwningType.IsCanonicalSubtype(CanonicalFormKind.Any))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HasGCStaticBase condition should not be needed for NativeAOT.

See dotnet/runtimelab#870

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI reduce-unsafe
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants