Elide ldelema type check when array type is known exactly
- Dominant language
- C#
- Stars
- 18.3k
- Forks
- 5.6k
- PR merge metrics
- PR metrics pending
Description
### Description
E.g.,
```csharp
static ref object GetRef1(object obj)
{
object[] arr = [obj];
return ref arr[0];
}
static ref object GetRef2(object obj)
{
object[] arr = [obj];
return ref MemoryMarshal.GetArrayDataReference(arr);
}
```
These should be able to end up with the same codegen, but the first still generates the ldelema helper call, despite knowing that the array is exactly an `object[]` (not a `string[]` or similar).
Similarly, it could apply to `static readonly` fields once the static constructor has run.
Godbolt.org: https://godbolt.org/z/YGEh3zPMv
Codegen:
```asm
Program:GetRef1(System.Object):byref (FullOpts):
push r15
push rbx
push rax
mov rbx, rdi
lea rdi, [(reloc 0x432ec0)] ; System.Object[]
mov esi, 1
call CORINFO_HELP_NEWARR_1_PTR
mov r15, rax
lea rdi, bword ptr [r15+0x10]
mov rsi, rbx
call CORINFO_HELP_ASSIGN_REF
mov rdi, r15
xor esi, esi
lea rdx, [(reloc 0x432fe8)] ; System.Object
call CORINFO_HELP_LDELEMA_REF
nop
add rsp, 8
pop rbx
pop r15
ret
Program:GetRef2(System.Object):byref (FullOpts):
push r15
push rbx
push rax
mov rbx, rdi
lea rdi, [(reloc 0x432ec0)] ; System.Object[]
mov esi, 1
call CORINFO_HELP_NEWARR_1_PTR
mov r15, rax
lea rdi, bword ptr [r15+0x10]
mov rsi, rbx
call CORINFO_HELP_ASSIGN_REF
lea rax, bword ptr [r15+0x10]
add rsp, 8
pop rbx
pop r15
ret
```
### Regression?
No.
### Analysis
Seems like https://github.com/dotnet/runtime/pull/85256 handled it for sealed types in any scenario, but we can also handle it for when we know the type of the array object exactly.
May also be applicable for `stelem.ref`.
Contributor guide
Research direction
Start by reproducing the GetRef1 and GetRef2 examples using the linked Godbolt.org codegen, then read the referenced runtime PR 85256 for the existing sealed-type optimization. Trace the JIT path responsible for the ldelema helper and compare the generated assembly; done means the exactly-known array case matches the direct data-reference codegen, with stelem.ref applicability evaluated separately.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- compilers, performance
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100