Skip to content

JIT: Load coalescing for "bitwise or" and shifts #116168

Open
@EgorBo

Description

@EgorBo

In order to make the Unsafe version safe, I need these both to have exactly the same codegen:

private static unsafe int Unsafe(MessageField field)
{
    ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(&field, sizeof(MessageField));
    return BinaryPrimitives.ReadInt16LittleEndian(span.Slice(4));
}

private static unsafe int Safe(MessageField field)
{
    // Assuming LE
    return (ushort)field.PayloadOffset | (ushort)(field.PayloadOffset >> 16);
}

[StructLayout(LayoutKind.Sequential)]
public struct MessageField
{
    public ushort Length;
    public ushort MaximumLength;
    public int PayloadOffset;
}

Asm:

; Method Program:Unsafe(Program+MessageField):int (FullOpts)
       mov      qword ptr [rsp+0x08], rcx
       lea      rax, [rsp+0x08]
       add      rax, 4
       movsx    rax, word  ptr [rax]
       ret      
; Total bytes of code: 19


; Method Program:Safe(Program+MessageField):int (FullOpts)
       mov      qword ptr [rsp+0x08], rcx
       mov      eax, dword ptr [rsp+0x0C]
       movzx    rcx, ax
       sar      eax, 16
       movzx    rax, ax
       or       eax, ecx
       ret      
; Total bytes of code: 21

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIreduce-unsafe

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions