dotnet / dotnet/runtime

JIT: coalesce adjacent loads

Open
#127,934 1 comment 3 reactions 0 assignees View on GitHub
area-CodeGen-coreclr reduce-unsafe
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

```cs
uint ReadU32(string str)
{
if (str.Length >= 2)
return str[0] | ((uint)str[1] << 16);
return 0;
}
```
Currently generates:
```asm
; Method Bench:ReadU32(System.String):uint (FullOpts)
mov eax, dword ptr [rcx+0x08]
cmp eax, 2
jge SHORT G_M51559_IG05
xor eax, eax
ret
G_M51559_IG05:
movzx rax, word ptr [rcx+0x0C]
movzx rcx, word ptr [rcx+0x0E]
shl ecx, 16
or eax, ecx
ret
; Total bytes of code: 25
```
While it's fully legal for JIT to merge them into one (string object implies data is 4-bytes aligned).

There is no simple safe API to perform this, so I wanted to just do it in a idiomatic way and rely on JIT. Example real-world usage: String.GetNonRandomizedHashCode

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.