Skip to content

Redundant bounds check #104890

@rameel

Description

@rameel

Unnecessary bounds check in the following snippet

static int Test(ReadOnlySpan<char> value)
{
    var i = 0;
    for (; i < value.Length; i++)
        if (value[i] != '/')
            break;

    value = value.Slice(i);

    foreach (var c in value)
    { }

    return 0;
}

Codegen: sharplab, (godbolt)

G_M000_IG01:                ;; offset=0x0000
       sub      rsp, 40

G_M000_IG02:                ;; offset=0x0004
       mov      rax, bword ptr [rcx]
       mov      ecx, dword ptr [rcx+0x08]
       xor      edx, edx
       xor      r8d, r8d
       test     ecx, ecx
       jle      SHORT G_M000_IG05
       align    [13 bytes for IG03]

G_M000_IG03:                ;; offset=0x0020
       cmp      word  ptr [rax+2*r8], 47
       jne      SHORT G_M000_IG04
       inc      r8d
       cmp      r8d, ecx
       jl       SHORT G_M000_IG03

G_M000_IG04:                ;; offset=0x0030
       mov      edx, r8d

G_M000_IG05:                ;; offset=0x0033
       cmp      edx, ecx
       ja       SHORT G_M000_IG09
       sub      ecx, edx
       xor      eax, eax
       test     ecx, ecx
       jle      SHORT G_M000_IG07
       align    [1 bytes for IG06]

G_M000_IG06:                ;; offset=0x0040
       cmp      eax, ecx
       jae      SHORT G_M000_IG10
       inc      eax
       cmp      eax, ecx
       jl       SHORT G_M000_IG06

G_M000_IG07:                ;; offset=0x004A
       xor      eax, eax

G_M000_IG08:                ;; offset=0x004C
       add      rsp, 40
       ret      

G_M000_IG09:                ;; offset=0x0051
       call     [System.ThrowHelper:ThrowArgumentOutOfRangeException()]
       int3     

G_M000_IG10:                ;; offset=0x0058
       call     CORINFO_HELP_RNGCHKFAIL
       int3     
; Total bytes of code: 94

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions