Skip to content

Redundant bound check in monotonically decreasing loop #135008

Description

@EgorBo

From #134956 (comment)

struct Test
{
    uint[] _bitmap;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static bool Contains(uint[] bitmap, int value)
    {
        uint offset = (uint)(value >> 5);
        return offset < (uint)bitmap.Length && (bitmap[offset] & (1u << value)) != 0;
    }

    private int LastIndexOfAny(ReadOnlySpan<char> span)
    {
        uint[] bitmap = _bitmap;
        int searchSpaceLength = span.Length;

        while (--searchSpaceLength >= 0)
        {
            char c = span[searchSpaceLength];
            if (Contains(bitmap, c))
            {
                break;
            }
        }

        return searchSpaceLength;
    }
}
Test:LastIndexOfAny(System.ReadOnlySpan`1[char]):int:this (FullOpts):
       push     rbp
       mov      rbp, rsp
       mov      rax, gword ptr [rdi]
       lea      ecx, [rdx-0x01]
       mov      edi, ecx
       test     edi, edi
       jl       SHORT G_M5479_IG06
       align    [0 bytes for IG03]
G_M5479_IG03:  ;; offset=0x0010
       cmp      ecx, edx
       jae      SHORT G_M5479_IG08
       mov      r8d, ecx
       movzx    r8, word  ptr [rsi+2*r8]
       mov      r9d, r8d
       sar      r9d, 5
       mov      r10d, dword ptr [rax+0x08]
       cmp      r10d, r9d
       jbe      SHORT G_M5479_IG05
       mov      r9d, r9d
       mov      r9d, dword ptr [rax+4*r9+0x10]
       bt       r9d, r8d
       jb       SHORT G_M5479_IG06
G_M5479_IG05:  ;; offset=0x003A
       lea      ecx, [rdi-0x01]
       mov      edi, ecx
       test     edi, edi
       jge      SHORT G_M5479_IG03
G_M5479_IG06:  ;; offset=0x0043
       mov      eax, ecx
       pop      rbp
       ret      
G_M5479_IG08:  ;; offset=0x0047
       call     CORINFO_HELP_RNGCHKFAIL
       int3     

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions