dotnet / dotnet/runtime

JIT: Optimization opportunity (extra jumps/checks)

Open
#128,458 1 comment 1 reaction 1 assignee Claimed by @EgorBo View on GitHub
area-CodeGen-coreclr
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

[godbolt](https://godbolt.org/z/3Ke3Kjh68)

```csharp
public static Span Trim(Span s)
{
while (s.Length != 0 && s[ 0] == '/') s = s.Slice(1);
while (s.Length != 0 && s[^1] == '/') s = s.Slice(0, s.Length - 1);

return s;
}
```

**Current codegen:**
coreclr trunk-20260521+2a65f102aaad2e0b97bf4554dd510ae57801ae5e

```asm
Program:Trim(System.Span`1[char]):System.Span`1[char] (FullOpts):
push rbp
mov rbp, rsp
test esi, esi
je SHORT G_M48643_IG04 ; <-- 1: could jump directly to G_M48643_IG06
align [0 bytes for IG03]

G_M48643_IG03:
cmp word ptr [rdi], 47
jne SHORT G_M48643_IG04 ; <-- 2: could jump directly to G_M48643_IG05
add rdi, 2
dec esi
jne SHORT G_M48643_IG03

G_M48643_IG04:
test esi, esi ; <-- 3: dead test
je SHORT G_M48643_IG06 ; jmp SHORT G_M48643_IG06
align [6 bytes for IG05]

G_M48643_IG05:
lea eax, [rsi-0x01]
mov edx, eax
cmp word ptr [rdi+2*rdx], 47
jne SHORT G_M48643_IG06
mov esi, eax
test esi, esi
jne SHORT G_M48643_IG05

G_M48643_IG06:
mov rax, rdi
mov rdx, rsi
pop rbp
ret
```

1. since `G_M48643_IG04` immediately repeats the same condition
2. we already know `esi != 0`
3. the condition is already known `esi == 0`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.