Skip to content

Fold "new T[size].Length" into "size"#114845

Merged
EgorBo merged 1 commit into
dotnet:mainfrom
EgorBo:fold-arr-len-pattern
Apr 22, 2025
Merged

Fold "new T[size].Length" into "size"#114845
EgorBo merged 1 commit into
dotnet:mainfrom
EgorBo:fold-arr-len-pattern

Conversation

@EgorBo

@EgorBo EgorBo commented Apr 20, 2025

Copy link
Copy Markdown
Member

Closes #114744

static void Test(int count)
{
    int[] arrA = new int[count];
    float[] arrB = new float[count];
    for (int i = 0; i < count; i++)
    {
        arrA[i] = 0;     // bounds check
        arrB[i] = 0.0f;  // bounds check
    }
}

Codegen diff: https://www.diffchecker.com/7iCHeDLt/

Seems like this transformation produces nice SPMI diffs.

@ghost ghost added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Apr 20, 2025
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

@EgorBo
EgorBo marked this pull request as ready for review April 20, 2025 17:02
Copilot AI review requested due to automatic review settings April 20, 2025 17:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR implements an optimization to fold the expression new T[size].Length into the original size argument, reducing unnecessary bounds checks and streamlining array length calculations.

  • Introduces a new folding case for ARR_LENGTH with new array expressions.
  • Handles different type cases (TYP_LONG and TYP_INT) to extract the original size.

Comment thread src/coreclr/jit/valuenum.cpp
Comment thread src/coreclr/jit/valuenum.cpp
@EgorBo

EgorBo commented Apr 20, 2025

Copy link
Copy Markdown
Member Author

PTAL @AndyAyersMS @jakobbotsch @dotnet/jit-contrib simple opt with diffs.

@EgorBo
EgorBo requested a review from AndyAyersMS April 20, 2025 17:04
@neon-sunset

This comment was marked as resolved.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JIT: Redundant bounds check for when loopUpperBound==arrayLength

4 participants