Skip to content

JIT doesn't eliminate bounds checks on const strings #1343

Closed

Description

Consider a method like:

    private static bool M(int pos) {
        const string Str = "hello";
        return (uint)pos < Str.Length && Str[pos] == 'e';
    }

The JIT is currently generating code like:

G_M23807_IG01:
       4883EC28             sub      rsp, 40
                                                ;; bbWeight=1    PerfScore 0.25
G_M23807_IG02:
       48B8C0300090BF020000 mov      rax, 0x2BF900030C0
       488B00               mov      rax, gword ptr [rax]
       8B5008               mov      edx, dword ptr [rax+8]
       4863D2               movsxd   rdx, edx
       448BC1               mov      r8d, ecx
       493BD0               cmp      rdx, r8
       7E19                 jle      SHORT G_M23807_IG05
                                                ;; bbWeight=1    PerfScore 6.00
G_M23807_IG03:
       3B4808               cmp      ecx, dword ptr [rax+8]
       731B                 jae      SHORT G_M23807_IG07
       4863D1               movsxd   rdx, ecx
       66837C500C65         cmp      word  ptr [rax+2*rdx+12], 101
       0F94C0               sete     al
       0FB6C0               movzx    rax, al
                                                ;; bbWeight=0.50 PerfScore 3.25
G_M23807_IG04:
       4883C428             add      rsp, 40
       C3                   ret
                                                ;; bbWeight=0.50 PerfScore 0.63
G_M23807_IG05:
       33C0                 xor      eax, eax
                                                ;; bbWeight=0.50 PerfScore 0.13
G_M23807_IG06:
       4883C428             add      rsp, 40
       C3                   ret
                                                ;; bbWeight=0.50 PerfScore 0.63
G_M23807_IG07:
       E8DC5CC95F           call     CORINFO_HELP_RNGCHKFAIL
       CC                   int3

In theory it seems the JIT should be able to both a) remove the redundant bounds check (and the corresponding fallback to rngchkfail), and b) encode the string length as a constant rather than reading it from the object.

cc: @AndyAyersMS

category:cq
theme:bounds-checks
skill-level:intermediate
cost:medium

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

Metadata

Assignees

Labels

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

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions