Skip to content

Conversation

@EgorBo
Copy link
Member

@EgorBo EgorBo commented Dec 6, 2025

Closes #122150
Example:

int Test(byte inData)
{
    ReadOnlySpan<byte> base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="u8;
    return base64[((inData & 0x03) << 4) | ((inData & 0xf0) >> 4)];
}

Was:

; Method Program:Test(byte):int:this (FullOpts)
       sub      rsp, 40
       movzx    rax, dl
       mov      ecx, eax
       and      ecx, 3
       shl      ecx, 4
       and      eax, 240
       sar      eax, 4
       or       eax, ecx
       cmp      eax, 65
       jae      SHORT G_M54716_IG04
       mov      rcx, 0x196B4CC2D88      ; static handle
       movzx    rax, byte  ptr [rcx+rax]
       add      rsp, 40
       ret      
G_M54716_IG04:
       call     CORINFO_HELP_RNGCHKFAIL
       int3     
; Total bytes of code: 55

Now:

; Method Program:Test(byte):int:this (FullOpts)
       movzx    rax, dl
       mov      ecx, eax
       and      ecx, 3
       shl      ecx, 4
       and      eax, 240
       sar      eax, 4
       or       eax, ecx
       mov      rcx, 0x171D74A2D88      ; static handle
       movzx    rax, byte  ptr [rcx+rax]
       ret      
; Total bytes of code: 36

As the result, was able to optimize bound checks in Convert.ConvertToBase64Array

@github-actions github-actions bot added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Dec 6, 2025
@dotnet-policy-service
Copy link
Contributor

Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.

@EgorBo
Copy link
Member Author

EgorBo commented Dec 6, 2025

@MihuBot

int i;

// get a pointer to the base64 table to avoid unnecessary range checking
fixed (byte* base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="u8)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we remove unsafe from ConvertToBase64Array's two callers?

@dotnet-policy-service
Copy link
Contributor

Draft Pull Request was automatically closed for 30 days of inactivity. Please let us know if you'd like to reopen it.

@EgorBo EgorBo reopened this Jan 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI reduce-unsafe

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bound Check for arr[(X & 0x3) << 4] pattern

2 participants