dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.09k stars 4.7k forks source link

Support loop cloning of class member arrays #77071

Open BruceForstall opened 1 year ago

BruceForstall commented 1 year ago

Currently, if the array being iterated is a class member (and not a function local), we can't analyze the access (e.g., can't determine if the array object is loop-invariant).

e.g.,

public class Program
{
    int[] array = new int[1000003];

    public int Sum()
    {
        int sum = 0;
        for (int i = 0; i < array.Length; i++)
            sum += array[i];
        return sum;
    }
}

category:cq theme:loop-opt skill-level:expert cost:large impact:medium

ghost commented 1 year ago

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

Issue Details
Currently, if the array being iterated is a class member (and not a function local), we can't analyze the access (e.g., can't determine if the array object is loop-invariant). e.g., ``` public class Program { int[] array = new int[1000003]; public int Sum() { int sum = 0; for (int i = 0; i < array.Length; i++) sum += array[i]; return sum; } } ```
Author: BruceForstall
Assignees: -
Labels: `area-CodeGen-coreclr`
Milestone: 8.0.0
ChrML commented 5 months ago

Just a question out of curiousity: I guess you can't guarantee that someone else doesn't change the array reference while looping.

What would be the criterias for assuming that the code up to the element-access is "short" enough / that it's safe to fetch the instance once, check and then access it without bound-checks?