Skip to content

JIT: (bug) impImportAndPushBoxForNullable drops GTF_IND_INITCLASS, allowing Nullable<T> loads to be hoisted before static constructor #135817

Closed

Description

@EgorBo

When boxing a Nullable<T> loaded from a static field, the JIT drops GTF_IND_INITCLASS on the decomposed hasValue and value loads, allowing loop hoisting to move the field load ahead of the static constructor check.

Minimal Repro

using System;
using System.Runtime.CompilerServices;

class Holder
{
    public static readonly int? Value = Init();
    static int? Init() => 42;
}

class Program
{
    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static int Test(int n, int denom)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            sum += i / denom;
            object? res = Holder.Value;
            if (res is not null)
                sum += 42;
        }
        return sum;
    }

    static void Main()
    {
        Console.WriteLine(Test(1, 1));
    }
}

Expected

42

Actual

0

Regression?

Yes, since .NET 8.0:

  • .NET 6.0.36: Does not reproduce (42)
  • .NET 7.0.20: Does not reproduce (42)
  • .NET 8.0.32: Reproduces (0)
  • .NET 9.0.21: Reproduces (0)
  • .NET 10.0.13: Reproduces (0)
  • .NET 11.0.0-rc.1.26425.128: Reproduces (0)

Notes

Compiler::impImportAndPushBoxForNullable calls impGetNodeAddr(nullableObj, CHECK_SPILL_ALL, GTF_IND_INITCLASS, &indirFlags), which splits the class-init helper into a separate statement and returns GTF_IND_INITCLASS in indirFlags, but never passes indirFlags to the gtNewLoadValueNode calls for value and hasValue (similarly, gtFoldNullCheck drops GTF_IND_INITCLASS when folding BOX_NULLABLE(&x) != null to x.hasValue).
Consequently, optHoistLoopCode does not recognize the load as treeIsCctorDependent and hoists Holder.Value._hasValue into the loop preheader ahead of CORINFO_HELP_GET_GCSTATIC_BASE.
Same class of bug as #134897 (CopyFieldByField in morphblock.cpp), but in a different code path.
Passing DOTNET_JitMinOpts=1 produces the expected 42.

Activity

  1. added this to the 12.0.0 milestone on Oct 14, 2026
  2. added
    area-CodeGen-coreclr
    on Oct 14, 2026
  3. dotnet-policy-service commented on Oct 14, 2026

    @dotnet-policy-service
    Contributor

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

  4. self-assigned this
    on Oct 15, 2026
  5. added a commit that references this issue on Oct 15, 2026
    3994df1
  6. locked and limited conversation to collaborators on Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions