-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
No way to avoid bounds checks when multiple spans are involved #97285
Comments
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch Issue DetailsGiven a pattern like: for (int i = 0; i < span.Length; i++)
{
span[i] *= 2;
} the JIT can elide the bounds checks on the span, but if there are multiple spans involved, e.g. using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
public void M1(ReadOnlySpan<int> source, Span<int> destination)
{
if (source.Length > destination.Length) Throw();
for (int i = 0; i < source.Length; i++)
{
destination[i] = source[i] * 2;
}
}
private static void Throw() => throw new Exception();
} the JIT doesn't elide the bounds checks on both source and destination, only on source. The only way today to get rid of all these bounds checks is to use unsafe code.
|
@jakobbotsch, is this a case where we might be able to avoid loop cloning for some kinds of trivial inputs? I don't believe we require cloning for single spans and instead simply emit one loop with no bounds checks. Ideally we'd be able to recognize some of these patterns and similarly not require a cloned loop for multiple spans, to help avoid code bloat and assembly size increases for "trivial" cases like this. |
Loop cloning should not result in any bloat for cases like this. You can see that the array version has the bounds checks optimized away without any bloat, despite the fact that loop cloning is what made that possible. The cold version only exists temporarily -- the JIT is later able to remove it because it notices that there is a dominating compare that makes the cold version unreachable. |
Gotcha, I had thought we had a special path to handle the common case and avoid the temporary IR introduction. But if that's not the case then sounds like all will be right anyways 👍 |
Closing as duplicate. |
Given a pattern like:
the JIT can elide the bounds checks on the span, but if there are multiple spans involved, e.g.
the JIT doesn't elide the bounds checks on both source and destination, only on source. The only way today to get rid of all these bounds checks is to use unsafe code.
The text was updated successfully, but these errors were encountered: