uruk-project / Jwt

JSON Web Token implementation for .Net & .Net Core
MIT License
80 stars 13 forks source link

Constant `stackalloc` can be optimized by the JIT. #569

Closed ycrumeyrolle closed 2 years ago

ycrumeyrolle commented 2 years ago

https://github.com/dotnet/runtime/pull/54186#discussion_r661724474

For example:

    private int Variable(int length) {
        Span<byte> array = stackalloc byte[length];
        return array[0] + length;
    }

    L0000: push ebp
    L0001: mov ebp, esp
    L0003: sub esp, 8
    L0006: xor eax, eax
    L0008: mov [ebp-8], eax
    L000b: mov [ebp-4], eax
    L000e: mov [ebp-4], esp
    L0011: mov dword ptr [ebp-8], 0xe96c2ce5
    L0018: mov eax, edx
    L001a: mov ecx, eax
    L001c: test ecx, ecx
    L001e: je short L002e
    L0020: add ecx, 3
    L0023: shr ecx, 2
    L0026: push 0
    L0028: dec ecx
    L0029: jne short L0026
    L002b: lea ecx, [esp]
    L002e: mov [ebp-4], esp
    L0031: test eax, eax
    L0033: jl short L0052
    L0035: cmp edx, 0
    L0038: jbe short L0058
    L003a: movzx eax, byte ptr [ecx]
    L003d: add eax, edx
    L003f: cmp dword ptr [ebp-8], 0xe96c2ce5
    L0046: je short L004d
    L0048: call 0x71e32050
    L004d: lea esp, [ebp]
    L0050: pop ebp
    L0051: ret
    L0052: call System.ThrowHelper.ThrowArgumentOutOfRangeException()
    L0057: int3
    L0058: call 0x71e31070
    L005d: int3
    private const int ConstantLength = 32;   
    private int Constant(int length) {
       Span<byte> array = stackalloc byte[ConstantLength];
        return array[0]+length;
    }

    L0000: sub esp, 0x24
    L0003: vxorps xmm4, xmm4, xmm4
    L0007: vmovdqu [esp], xmm4
    L000c: vmovdqu [esp+0x10], xmm4
    L0012: xor eax, eax
    L0014: mov [esp+0x20], eax
    L0018: mov dword ptr [esp+0x20], 0xe96c2ce5
    L0020: lea eax, [esp]
    L0023: movzx eax, byte ptr [eax]
    L0026: add eax, edx
    L0028: cmp dword ptr [esp+0x20], 0xe96c2ce5
    L0030: je short L0037
    L0032: call 0x71e32050
    L0037: add esp, 0x24
    L003a: ret