Skip to content

JIT can't elide span.Slice range checks after a manual check #112953

Closed

Description

@MihaZupan

https://godbolt.org/z/hjqc5rodx

For a case like this:

public static ReadOnlySpan<char> Test(ReadOnlySpan<char> span, int offset)
{
    if ((uint)offset < (uint)span.Length)
    {
        return span.Slice(offset + 1);
    }
    
    return span;
}

public ReadOnlySpan<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _reference, (nint)(uint)start /* force zero-extension */), _length - start);
}

The JIT isn't removing the if ((uint)start > (uint)_length) check.

You can hit that in IndexOf + slice loops, e.g.

int count = 0;
int pos;
while ((uint)(pos = span.IndexOf(c)) < (uint)span.Length)
{
    count++;
    span = span.Slice(pos + 1);
}

Activity

  1. added
    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
    on Feb 26, 2025
  2. dotnet-policy-service commented on Feb 26, 2025

    @dotnet-policy-service
    Contributor

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

  3. self-assigned this
    on Feb 26, 2025
  4. added this to the Future milestone on Feb 26, 2025
  5. removed
    untriagedNew issue has not been triaged by the area owner
    on Feb 26, 2025
  6. EgorBo commented on Feb 26, 2025

    @EgorBo
    Member

    Hopefully, should be handled by the PRs I'm currently working on (e.g. #112907 + #112824 + more changes)

  7. added
    in-prThere is an active PR which will close this issue when it is merged
    on Feb 28, 2025
  8. tannergooding commented on Apr 28, 2025

    @tannergooding
    Member

    @EgorBo can this be closed now?

  9. EgorBo commented on May 2, 2025

    @EgorBo
    Member

    @EgorBo can this be closed now?

    Nope, still needs work

  10. modified the milestones: Future, 11.0.0 on May 12, 2026
  11. modified the milestones: 11.0.0, 12.0.0 on Jul 30, 2026
  12. added a commit that references this issue on Oct 29, 2026
    aa1a3d6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions