A popular loop pattern when there are two (or more) monotonically increasing counters, unfortunately, JIT doesn't optimize bounds checks for them. ```cs public int DecodeBytes_safe(Span<byte> buffer) { int j = 0; for (int i = 0; i < buffer.Length; i++) { // e.g. under some condition buffer[j++] = 0; } return j; } ``` Current codegen: ```asm ; Method Progam:DecodeBytes_safe(System.Span`1[ubyte]):int:this (FullOpts) G_M20838_IG01: ;; offset=0x0000 sub rsp, 40 G_M20838_IG02: ;; offset=0x0004 mov rax, bword ptr [rdx] mov ecx, dword ptr [rdx+0x08] xor edx, edx test ecx, ecx jg SHORT G_M20838_IG06 G_M20838_IG03: ;; offset=0x0010 mov r10d, edx G_M20838_IG04: ;; offset=0x0013 mov eax, r10d G_M20838_IG05: ;; offset=0x0016 add rsp, 40 ret G_M20838_IG06: ;; offset=0x001B mov r8d, ecx align [2 bytes for IG07] G_M20838_IG07: ;; offset=0x0020 lea r10d, [rdx+0x01] cmp edx, ecx jae SHORT G_M20838_IG09 mov edx, edx mov byte ptr [rax+rdx], 0 dec r8d je SHORT G_M20838_IG04 G_M20838_IG08: ;; offset=0x0033 mov edx, r10d jmp SHORT G_M20838_IG07 G_M20838_IG09: ;; offset=0x0038 call CORINFO_HELP_RNGCHKFAIL int3 ; Total bytes of code: 62 ```
Activity
dotnet-policy-service commentedon Jun 3, 2025
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
jakobbotsch commentedon Jun 3, 2025
That's something that a bounds checks elimination pass based on SCEVs would be able to handle.
EgorBo commentedon Jun 3, 2025
Yeah I was about to ping you about it
[-]Bounds checks: multiple monotonically increasing counters (withing bounds)[/-][+]Bounds checks: multiple monotonically increasing counters (within bounds)[/+]