Skip to content

JIT: (bug) Wrong exception order for stelem.ref: the array range check runs before the value expression #133860

Closed

Description

@EgorBo

For stelem.ref the value operand must be evaluated before the array store's range check. When morph
demotes the array-store helper call into a plain STOREIND, the range check ends up first and the wrong
exception is reported.

Minimal Repro

using System;
using System.Runtime.CompilerServices;

class C
{
    public object F;
}

class Program
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static object[] Make(int len) => new object[len];

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void Use(object[] a) { }

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static void Test(int len, int index, C c)
    {
        object[] arr = Make(len);
        arr[index] = c.F; // 'c.F' must be evaluated before the store's range check
        Use(arr);
    }

    static void Main()
    {
        try
        {
            Test(1, 5, null);
            Console.WriteLine("no exception");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.GetType().Name);
        }
    }
}

Expected

NullReferenceException

Actual

IndexOutOfRangeException

The bounds check precedes the faulting load of c.F:

       cmp      rcx, rdx
       jae      SHORT G_M62848_IG04       ; <-- range check first
       lea      rcx, bword ptr [rdi+8*rcx+0x10]
       mov      rdx, gword ptr [rbx+0x08] ; <-- 'c.F' (must fault first) second
       call     CORINFO_HELP_ASSIGN_REF

Notes

The CEE_STELEM_REF helper-call path in importer.cpp does not apply the ARR_ST ("strict ordering of
exceptions for array store") spill that the inline INDEX_ADDR path applies. When gtCanSkipCovariantStoreCheck
later succeeds in fgMorphCall and rewrites the helper call into STOREIND(INDEX_ADDR(arr, index), value),
that ordering guarantee is lost. Writing new object[len] directly (no inlined Make) takes the inline path
and behaves correctly. Also reproduces on .NET 10.0.12, so not a main-only regression.

Activity

  1. added this to the 12.0.0 milestone on Sep 14, 2026
  2. added
    area-CodeGen-coreclr
    on Sep 14, 2026
  3. dotnet-policy-service commented on Sep 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. EgorBo commented on Sep 18, 2026

    @EgorBo
    MemberAuthor

    Affected SDK versions:

    • 10.0.401
    • 11.0.100-rc.2.26467.112
  5. locked and limited conversation to collaborators on Nov 13, 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