Skip to content

JIT: Bounds check not hoisted or eliminated for simple InlineArray iteration #119693

Closed

Description

@BoyBaykiller

https://godbolt.org/z/Mqa1rEs38

[InlineArray(3)]
struct Data
{
    int[] _element;
}

private static void Test1(Data data, int axis)
{
    for (int i = 0; i < data[axis].Length; i++)
    {
        _ = data[axis][i];
    }
}

Both bounds check (for axis against 3, and i against .Length) exist.

Main codegen
G_M7138_IG01:  ;; offset=0x0000
       sub      rsp, 40
						;; size=4 bbWeight=1 PerfScore 0.25
G_M7138_IG02:  ;; offset=0x0004
       xor      eax, eax
       mov      r8d, edx
       jmp      SHORT G_M7138_IG04
       align    [5 bytes for IG03]
						;; size=12 bbWeight=1 PerfScore 2.50
G_M7138_IG03:  ;; offset=0x0010
       cmp      eax, dword ptr [r10+0x08]
       jae      SHORT G_M7138_IG06
       inc      eax
						;; size=8 bbWeight=4 PerfScore 17.00
G_M7138_IG04:  ;; offset=0x0018
       cmp      edx, 3
       jae      SHORT G_M7138_IG06
       mov      r10, gword ptr [rcx+8*r8]
       cmp      dword ptr [r10+0x08], eax
       jg       SHORT G_M7138_IG03
						;; size=15 bbWeight=8 PerfScore 58.00
G_M7138_IG05:  ;; offset=0x0027
       add      rsp, 40
       ret      
						;; size=5 bbWeight=1 PerfScore 1.25
G_M7138_IG06:  ;; offset=0x002C
       call     CORINFO_HELP_RNGCHKFAIL
       int3     
						;; size=6 bbWeight=0 PerfScore 0.00

Now with JitStressModeNames=STRESS_NO_OLD_PROMOTION + JitSynthesizeCounts=1 the axis bounds check gets hoisted, but the other one persists. And the load isnt hoisted.

Main + STRESS_NO_OLD_PROMOTION + JitSynthesizeCounts codegen
G_M7138_IG01:  ;; offset=0x0000
       sub      rsp, 40
						;; size=4 bbWeight=1 PerfScore 0.25
G_M7138_IG02:  ;; offset=0x0004
       xor      eax, eax
       cmp      edx, 3
       jae      SHORT G_M7138_IG05
       mov      edx, edx
       mov      rcx, gword ptr [rcx+8*rdx]
       cmp      dword ptr [rcx+0x08], 0
       jle      SHORT G_M7138_IG04
       align    [9 bytes for IG03]
						;; size=28 bbWeight=1 PerfScore 8.00
G_M7138_IG03:  ;; offset=0x0020
       mov      rdx, rcx
       cmp      eax, dword ptr [rdx+0x08]
       jae      SHORT G_M7138_IG05
       inc      eax
       cmp      dword ptr [rcx+0x08], eax
       jg       SHORT G_M7138_IG03
						;; size=15 bbWeight=9.00 PerfScore 76.50
G_M7138_IG04:  ;; offset=0x002F
       add      rsp, 40
       ret      
						;; size=5 bbWeight=1 PerfScore 1.25
G_M7138_IG05:  ;; offset=0x0034
       call     CORINFO_HELP_RNGCHKFAIL
       int3     
						;; size=6 bbWeight=0 PerfScore 0.00

Activity

  1. added
    untriaged
    on Sep 14, 2025
  2. added
    area-CodeGen-coreclr
    on Sep 14, 2025
  3. dotnet-policy-service commented on Sep 14, 2025

    @dotnet-policy-service
    Contributor

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

  4. xtqqczze commented on Sep 15, 2025

    @xtqqczze
    Contributor

    Notably, the InlineArray codegen is much worse than a regular array:

    static void Test2(int[][] data, int axis)
    {
        for (int i = 0; i < data[axis].Length; I++)
        {
            float cost = data[axis][I];
        }
    }

    godbolt.org

  5. added this to the Future milestone on Sep 15, 2025
  6. removed
    untriaged
    on Sep 15, 2025
  7. tannergooding commented on Sep 15, 2025

    @tannergooding
    Member

    The codegen for the above is also "worse" because it actually looks like:

    [InlineArray(3)]
    private struct Data
    {
        [Nullable(1)]
        private int[] _element;
    }
    
    private static void Test1(Data data, int axis)
    {
        for (int i = 0; i < PrivateImplementationDetails.InlineArrayAsSpan<Data, int[]>(ref data, 3)[axis].Length; i++)
        {
            _ = PrivateImplementationDetails.InlineArrayAsSpan<Data, int[]>(ref data, 3)[axis][i];
        }
    }
    
    [CompilerGenerated]
    internal sealed class PrivateImplementationDetails
    {
        internal static Span<TElement> InlineArrayAsSpan<TBuffer, TElement>(ref TBuffer buffer, int length)
        {
            return MemoryMarshal.CreateSpan(ref Unsafe.As<TBuffer, TElement>(ref buffer), length);
        }
    }

    If you change this to be a little more explicit, it cleans up more, but still only as far as the JIT can safely determine:

    private static void Test2(Data data, int axis)
    {
        int[] axisArr = data[axis];
        
        for (int i = 0; i < axisArr.Length; i++)
        {
            _ = axisArr[i];
        }
    }

    The JIT probably could do more here, but its fairly non-trivial particularly with all the 2-field structs being created, so it likely plays into promotion some.

  8. AndyAyersMS commented on Jun 14, 2026

    @AndyAyersMS
    Member

    Note

    This comment was generated with assistance from GitHub Copilot.

    Traced through Test1's loop body. LICM does correctly identify IND[data[axis]] (the array-ref load) as a hoist candidate per IsTreeVNInvariant — memory state is loop-invariant, liberal VN [245] is stable across iterations. The hoist is then blocked by IsHoistableOverExcepSibling:

    The IND has GTF_EXCEPT (VN attaches NullPtrExc(V00 + 8*axis)) and the preceding sibling BOUNDS_CHECK_Rng also throws. LICM refuses to reorder two potentially-throwing operations, so even though the IND is invariant and would otherwise hoist cleanly, it stays in the loop. CSE then reuses the cached array-ref across the body and condition (CSE #2), which is why we see one mov r9, [rcx+8*axis] per iteration rather than two — but the entire cmp axis, 3 / mov r9, [rcx+8*axis] pair still re-executes every iteration.

    The IND's NRE comes from V00 being a byref arg without VNFOA_KnownNonNull — only PtrToLoc (i.e. LCL_ADDR of a local) carries that attribute. optAssertionIsNonNull also only peels GT_ADD with a constant offset, so even marking V00 as known-non-null wouldn't help the V00 + LSH(axis, 3) address shape.

    Three angles I see for a real fix, each non-trivial:

    1. Mark byref args (and any LCL_VAR byref defined by an arg) as VNFOA_KnownNonNull. The runtime does guarantee byref args are non-null, but flowing that through VN/assertions has broad downstream effects.
    2. Extend optAssertionIsNonNull to recognize GT_ADD(non-null-byref, int-typed-offset) as still non-null.
    3. Relax IsHoistableOverExcepSibling for the common case where the throw-sibling and the candidate get hoisted into the preheader in the same source order (preserving exception order).

    @tannergooding's comment noted this was non-trivial — confirmed. Not opening a PR.

  9. AndyAyersMS commented on Jun 14, 2026

    @AndyAyersMS
    Member

    Note

    This comment was generated with assistance from GitHub Copilot.

    Follow-up to the previous root-cause analysis. The chain that prevents this loop from being optimized is:

    1. optTryInvertWhileLoop rejects the loop: estimated duplication cost is 43, max is 34, and the existing ARR_LENGTH boost only adds +8 (just barely losing).
    2. Without inversion, the IV-increment is in BB02 (body) and the test is in BB03 (header). optExtractTestIncr requires both in the same block, so loop cloning fails (Could not extract an IV).
    3. Without cloning, no BCE.
    4. LICM does correctly mark IND[data[axis]] as a hoist candidate but IsHoistableOverExcepSibling blocks the hoist past the preceding BOUNDS_CHECK.
    5. CSE deduplicates the two IND accesses within the loop body, but the load still re-executes every iteration.

    So the most natural fix is at step 1 — get the loop inverted, then everything downstream may have a chance.

    Prototype tried: extend optInvertCountTreeInfo to also count "loop-invariant-base IND loads" alongside ARR_LENGTH and shared statics, using a cheap pre-SSA approximation: walk the loop blocks once to collect locals stored anywhere in the loop, then count any indirection whose address is built only from non-stored locals (transitively through ADD/SUB/LSH/CAST). Apply the same +8 * count boost as ARR_LENGTH.

    For the issue's repro this works exactly as hoped: Test1 flips to the same inverted shape as Test2, the axis bounds-check and the data[axis] load hoist to the preheader, and PerfScore drops from 75.25 to 42.75 (vs Test2's 23.00).

    SPMI x64 (aspnet2 / benchmarks.run{,_pgo} / libraries.{crossgen2,pmi}, ~770k contexts): 580 contexts with diffs, 0 size improvements / 579 size regressions / +24,561 net bytes; PerfScore 222 method-level improvements / 358 regressions, overall FullOpts PerfScore essentially flat (-0.006% to +0.009%). The boost over-applies: many loops get the extra inversion-duplication cost without any downstream hoist/cloning actually exploiting the opportunity. The PerfScore improvements where they happen are large (-10% to -20%), but they're swamped by the broad +2-3% regressions in newly-inverted loops where the hoist never materializes.

    Conclusion: the inversion gate is the right lever, but a "looks-stable-base" IND count isn't a strong enough predictor — at inversion time we can't tell whether the downstream LICM/CSE chain will actually pay back the duplication. Need a tighter signal, or to do something at LICM time instead (e.g., relax IsHoistableOverExcepSibling for the "siblings get hoisted into the preheader in the same source order" case, which preserves exception ordering).

    Not opening a PR. Leaving the issue open with these findings.

  10. added a commit that references this issue on Jul 15, 2026
    33a6864
  11. locked and limited conversation to collaborators on Jul 18, 2026
  12. added a commit that references this issue on Jul 22, 2026
    d2f3850
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclr

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions