Skip to content

JIT: (bug) Tier0: ArgumentNullException.ThrowIfNull(Nullable<T>, paramName) evaluates paramName before reading the source #137639

Closed

Description

@EgorBo

At Tier0, ArgumentNullException.ThrowIfNull(s.Field, names[idx]) with a Nullable<T> source reads hasValue only after paramName is evaluated, so the exception from names[idx] is thrown instead of the NullReferenceException from the (null) source byref. Optimized code throws NullReferenceException.

Minimal Repro

using System;
using System.Runtime.CompilerServices;

ref struct S
{
    public ref int? Field;
}

class Program
{
    static void Main()
    {
        try
        {
            Test(default, new string[1], 5);
            Console.WriteLine("no exception");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.GetType().Name);
        }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void Test(S s, string[] names, int idx)
    {
        ArgumentNullException.ThrowIfNull(s.Field, names[idx]);
    }
}

Expected

Left-to-right evaluation: s.Field is read from the null byref first.

NullReferenceException

Actual

Default settings (tiered compilation, Tier0):

IndexOutOfRangeException

DOTNET_TieredCompilation=0 and DOTNET_JITMinOpts=1 give NullReferenceException.

Regression?

Default settings, same repro:

Runtime Result
.NET 8 (8.0.34) OK (NullReferenceException)
.NET 9 (9.0.23) Reproduces
.NET 10 (10.0.15) Reproduces
.NET 11 (11.0.0-rtm.26529.118) / main (584bd32) Reproduces

Notes

  • Compiler::impThrowIfNull (importercalls.cpp), nullable case: only the box-helper address and paramName are spilled; the hasValue read happens later in the QMARK condition, i.e. after paramName is evaluated.
  • The non-nullable CORINFO_HELP_BOX case emits gtNewNullCheck(addr) between the two spills; the nullable case lacks the equivalent.
  • Only exception ordering is affected: paramName must have a non-call exceptional side effect (range check, division, cast, ...) and the source byref must be null.

Activity

  1. added this to the 12.0.0 milestone on Nov 16, 2026
  2. added
    area-CodeGen-coreclr
    on Nov 16, 2026
  3. dotnet-policy-service commented on Nov 16, 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. added a commit that references this issue on Nov 16, 2026
    99d3004
  5. self-assigned this
    on Nov 17, 2026
  6. added a commit that references this issue on Nov 18, 2026
    9d756a9
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