RyuJIT makes unnecessary use of JIT_Stelem_Ref when storing null in arrays
Sample code (adapted from a Queue
static T Dequeue<T>(T[] array, int index)
{
var head = array[index];
array[index] = default(T);
return head;
}
Generated code:
00007FFF1FB004D0 push rsi
00007FFF1FB004D1 sub rsp,20h
00007FFF1FB004D5 mov ecx,dword ptr [rdx+8]
00007FFF1FB004D8 cmp r8d,ecx
00007FFF1FB004DB jae 00007FFF1FB004FC
00007FFF1FB004DD movsxd rcx,r8d
00007FFF1FB004E0 mov rsi,qword ptr [rdx+rcx*8+10h]
00007FFF1FB004E5 mov rcx,rdx
00007FFF1FB004E8 mov edx,r8d
00007FFF1FB004EB xor r8d,r8d
00007FFF1FB004EE call JIT_Stelem_Ref (07FFF7F171400h)
00007FFF1FB004F3 mov rax,rsi
00007FFF1FB004F6 add rsp,20h
00007FFF1FB004FA pop rsi
00007FFF1FB004FB ret
00007FFF1FB004FC call JIT_RngChkFail (07FFF7F58F048h)
00007FFF1FB00501 int 3
JIT_Stelem_Ref includes an array null check and range check (unnecessary in this case because of a previous range check) and a value null check (unnecessary in this case because the value is known to be null and nulls don't require write barriers nor type checks). The null value should be stored directly.
Optimizing Jit_Stelem_Ref() call to a simple array assignment if the value being assigned is null: Right now RyuJIT importer does a check to see whether value is constant 'null' and eliminates the need for jit_stelem_ref call. In this specific case, value is a initobj(&val, 0) and hence doesn't get optimized. We need a more generic check after global morph and constant prop, to replace calls to Jit_Stelem_Ref() with array assignment if the value is null.