Skip to content

stelem.ref type check should take the static type of the array into account #58487

Open

Description

@jfd16

The current implementation of stelem.ref does the type check using only the runtime type of the array; it does not receive any information about the array's static type which could be used to optimize the common case where the static element type of the array is the same as the runtime type. Because of this, it is currently more efficient to get a reference to an array element (using ldelema, which does use static type information) and write to that reference than to write to the array element directly, if the type of the object being assigned is a derived type of (but not the same as) the array's element type, as the following benchmark shows: (Results are from .NET 5)

public class Benchmark {
    public class A { }
    public class B : A { }
    public class C : B { }
    public class D : C { }

    private A[] arr = new A[1000];
    public IEnumerable<object> args => new[] { new A(), new B(), new C(), new D() };

    [Benchmark(Baseline = true)]
    [ArgumentsSource(nameof(args))]
    public void AssignToArray(A obj) {
        A[] arr = this.arr;
        for (int i = 0; i < arr.Length; i++) {
            arr[i] = obj;
        }
    }

    [Benchmark]
    [ArgumentsSource(nameof(args))]
    public void AssignToArrayWithRef(A obj) {
        A[] arr = this.arr;
        for (int i = 0; i < arr.Length; i++) {
            ref A elemRef = ref arr[i];
            elemRef = obj;
        }
    }
}
Method obj Mean Error StdDev Ratio RatioSD Code Size
AssignToArray Benchmark+A 2.574 μs 0.0396 μs 0.0371 μs 1.00 0.00 52 B
AssignToArray Benchmark+B 9.948 μs 0.0777 μs 0.0727 μs 1.00 0.00 52 B
AssignToArray Benchmark+C 8.383 μs 0.0716 μs 0.0559 μs 1.00 0.00 52 B
AssignToArray Benchmark+D 6.104 μs 0.1185 μs 0.1268 μs 1.00 0.00 52 B
AssignToArrayWithRef Benchmark+A 3.958 μs 0.0362 μs 0.0339 μs 1.54 0.02 70 B
AssignToArrayWithRef Benchmark+B 3.997 μs 0.0250 μs 0.0222 μs 0.40 0.00 70 B
AssignToArrayWithRef Benchmark+C 3.983 μs 0.0340 μs 0.0318 μs 0.47 0.00 70 B
AssignToArrayWithRef Benchmark+D 4.008 μs 0.0543 μs 0.0508 μs 0.66 0.01 70 B

There is a special case check for object[] here which can be replaced with a check for the array static type (passed in as an additional handle argument to StelemRef).

  • This would not regress the case where the array's type is object[], aside from the cost of passing in the additional argument. This is because if the runtime type of an array is object[], its static type must also be object[].
  • With this, it would be safe to pass object[] as the static type for any array, which could be used in cases where the static type handle is expensive to obtain (for example, in shared generic code) or is unknown.

category:proposal
theme:basic-cq
skill-level:intermediate
cost:medium
impact:small

Activity

  1. ghost added
    untriaged
    on Sep 1, 2021
  2. added
    area-CodeGen-coreclr
    on Sep 1, 2021
  3. EgorBo commented on Sep 1, 2021

    @EgorBo
    Member
    class A { }
    class B : A { }
    
    static void AssignToArray(A[] arr, A obj)
    {
        arr[0] = obj;
    }

    So if I understand it correctly, the only way we can optimize AssignToArray here are the following tricks:

    • arr and obj are both known to be of the same exact class (means it's either A is sealed or jit sees where and how both array and obj were created)
    • arr is exactly of object[] type - it means we can safely assign everything to it
    • obj is null
    • arr[i1] = arr[i2]; arr[i2] is guaranteed to return the same type so we don't need a check here.

    the rest of the cases we have to call the slow covariance-aware helper 🙁

    However, we can optimize it in JIT like this (what you suggest if I am not mistaken):

    if (arr[0]->pMT == A)
       // skip covariant check
    else
       // fallback.

    or

    if (obj == null || arr[0]->pMT == obj->pMT)
       // skip covariant check
    else
       // fallback.

    PGO can help us here to get a better type info cc @AndyAyersMS

  4. added this to the 7.0.0 milestone on Sep 1, 2021
  5. self-assigned this
    on Sep 1, 2021
  6. removed
    untriaged
    on Sep 1, 2021
  7. EgorBo commented on Sep 1, 2021

    @EgorBo
    Member

    Another missing opportunity in JIT:

    B[] array = new B[1];
    array[0] = new B();

    JIT should be able to skip covariant checks here

  8. AndyAyersMS commented on Sep 1, 2021

    @AndyAyersMS
    Member

    We can extend impCanSkipCovariantStoreCheck for that second case.

    For the first case I wonder how the cost of the checks to avoid the store check compares to the cost of the store check.

  9. jkotas commented on Sep 1, 2021

    @jkotas
    Member

    For the first case I wonder how the cost of the checks to avoid the store check compares to the cost of the store check.

    You will end up calling a write barrier helper for this case in any situation, so there is always going to be call overhead.

    Here is the existing code of the helper that performs the array store checks

    if (obj == null)
    goto assigningNull;
    if (elementType != RuntimeHelpers.GetMethodTable(obj))
    goto notExactMatch;
    . This helper has the same fast path and it will tail call the write barrier helper. The potential savings from partial inlining of the store check are the frame setup of this helper and the tail call.

    It may be interesting to look at:

    • treating the JIT helpers written in managed code as ordinary methods and inlining them in the super hot loops. More powerful than special-casing the casting helpers in the JIT that we do today and that often makes the fallback path slower than it needs to be.
    • partially inlining the write barrier code in the super hot loops and thus avoiding the call overhead of the write barrier most of the time. Again, more widely applicable optimization.
  10. jfd16 commented on Sep 1, 2021

    @jfd16
    ContributorAuthor

    For the first case I wonder how the cost of the checks to avoid the store check compares to the cost of the store check.

    The static type check would make the check for object[] redundant, so the only additional overhead would be that of having one additional parameter in CastHelpers.StelemRef.

  11. EgorBo commented on Sep 2, 2021

    @EgorBo
    Member

    Thanks for ideas!

    treating the JIT helpers written in managed code as ordinary methods and inlining them

    The idea has been floating around for a while, it's currently a bit tricky to mark custom calls as inline-candidates in jit by hands but should be possible 👍

    We can extend impCanSkipCovariantStoreCheck for that second case.

    Yes, should be pretty straightforward to fix since gtGetClassHandle returns all the needed info

  12. modified the milestones: 7.0.0, 8.0.0 on May 30, 2022
  13. modified the milestones: 8.0.0, Future on Apr 10, 2023
  14. moved this to Optimizations in .NET Core CodeGenon Jun 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

Relationships

None yet

Development

No branches or pull requests

Issue actions