Repository navigation
In progress
Labels
JitUntriagedCLR JIT issues needing additional triagearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIenhancementProduct code improvement that does NOT require public API changes/additionsoptimizationtenet-performancePerformance related issue
Milestone
Description
When casting a span to a larger type via NonPortableCast, the result should not be able to overflow and the jit should be able to eliminate the check and throw.
This came up in some span conversion work over in CoreFx.
It might be hard to catch all cases of this since the current code for NonPortableCast<FromType, ToType> first multiplies the length by sizeof<FromType> and then divides by sizeof<ToType> but when the from type is char the resulting length will not overflow an int.
For instance:
ReadOnlySpan<byte> span = ...;
ReadOnlySpan<long> longSpan = span.NonPortableCast<byte, long>();Currently this does a fairly expensive and overflow check;
G_M41841_IG01:
4883EC28 sub rsp, 40
G_M41841_IG02:
488B02 mov rax, bword ptr [rdx]
8B5208 mov edx, dword ptr [rdx+8]
4863D2 movsxd rdx, edx
4C8BC2 mov r8, rdx
49C1F83F sar r8, 63
4983E007 and r8, 7
4C03C2 add r8, rdx
49C1F803 sar r8, 3
4981F8FFFFFF7F cmp r8, 0x7FFFFFFF
7F1A jg SHORT G_M41841_IG04
4981F800000080 cmp r8, 0xFFFFFFFF80000000
7C11 jl SHORT G_M41841_IG04
498BD0 mov rdx, r8
488901 mov bword ptr [rcx], rax
895108 mov dword ptr [rcx+8], edx
488BC1 mov rax, rcx
G_M41841_IG03:
4883C428 add rsp, 40
C3 ret
G_M41841_IG04:
E8895EC75F call CORINFO_HELP_OVERFLOW
CC int3We could probably also fix this in the source code by comparing sizes and only using checked math for the cases where size increases.
category:cq
theme:basic-cq
skill-level:expert
cost:small
Metadata
Metadata
Assignees
Labels
JitUntriagedCLR JIT issues needing additional triagearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIenhancementProduct code improvement that does NOT require public API changes/additionsoptimizationtenet-performancePerformance related issue
Activity
mikedn commentedon Dec 19, 2017
It should also use unsigned arithmetic, division by const (especially power of 2) is cheaper. And checked cast from
ulongtointis also cheaper since it only needs to check the upper bound.I'll give it a try, anyway I don't think the JIT will learn to optimize this code properly anytime soon...
mikedn commentedon Dec 19, 2017
Hmm, something like this:
A bit large but fortunately it is still inlined. The entire
NonPortableCastfrom your example reduces toshr ecx, 3. The reverse,longtobyte, generatesomariom commentedon Dec 20, 2017
@mikedn Looks like you don't need the second
ifmikedn commentedon Dec 20, 2017
else if (Unsafe.SizeOf<TFrom>() == 1)?Could be, need to check how well those long operations are handled on 32 bit.
It may also be possible to improve the JIT certain areas to reduce the number of special cases. One significant CQ issues is related to signed arithmetic and that may be difficult to deal with in the JIT. But other issues this code exposes might be more manageable.
mikedn commentedon Dec 30, 2017
Yeah, it looks like JIT's handling of 64 bit
mul.unanddiv.unon 32 bit targets sucks. At the very least it should removex div.un 1but it does not 😕Without special cases for byte sized to/from
NonPortableCast<int, byte>produces something like:mikedn commentedon Dec 31, 2017
Attempting to navigate around all the problems the JIT has with this code (and boy, does it have a few problems...) risks making the code too complicated. I think that the best option is to handle only those cases that are likely to be useful.
sizeof(From) == sizeof(To)- treatingfloatasintorintasRGBAstruct containing 4 bytes seems useful. This cast should practically be a no op because the length does not change.sizeof(From) == 1- treating bytes as ints, floats, RGBAs can be useful, provided that alignment and endianness issues are accounted for. This cast requires only a integer division by constant.sizeof(To) == 1-AsBytesshould cover most needs. Casting tosbyteor a byte sized struct should be a rather rare occurrence. Don't bother special casing this.sizeof(From) < sizeof(To)- withsizeof(From) == 1already handled there doesn't seem to be much value in handling this? Casting fromshorttoint?!?sizeof(From) > sizeof(To)- this one too doesn't seem valuable. Anyway there's not a lot that can be done about it, this needs 64 bit mul/div and checked cast tointno matter what. What helps here is changing all the computation to use unsigned integers.So, we can do something like:
The main purpose of
else if (Unsafe.SizeOf<TFrom>() == 1)is to avoid 64 bit division on 32 bit targets. It could probably be ifdefed out on 64 bit targets to keep the IL size down.UInt64MulDivtoo caters to the needs of 32 bit targets, arranging code this way allows the JIT to generate a "big mul" multiply (a single MUL instruction instead of a helper call).@jkotas Opinions?
mikedn commentedon Dec 31, 2017
A list of the various problems the JIT has with this (original and proposed) code could be useful:
intand the division by constant (especially when the constant is a power of 2) are more expensive when signed arithmetic is used. The JIT does next to nothing in this area and improving things in the general case isn't easy. Perhaps it could handle just the special case of array and span lengths that are known to be positive.x * c / cisxbecausex * ccannot overflow so forsizeof(From) = sizeof(To) = 4the following code is generated:sizeof(From) = 1the JIT generates:CORINFO_HELP_LMUL_OVF(x, 1)orCORINFO_HELP_LDIV(x, 1). This also prevents optimization ofmul/divby power of 2 usingshld/shrdinstructions.jkotas commentedon Dec 31, 2017
Sounds good to me.
Is there no way to do this without a helper method?
mikedn commentedon Dec 31, 2017
Anything that ensures that the calls happen before the int->long casts will do. For example, something like:
The problem is that calls tends tend to spill the stack to local variables and then you end up multiplying 2
longlocal variables. The JIT has no idea that those variables were initialized fromintvalues converted tolongand fails to perform the "big mul" optimization.TIHan commentedon Feb 2, 2023
The API
NonPortableCastdoes not exist anymore. @AndyAyersMS - maybe this has been renamed?AndyAyersMS commentedon Feb 2, 2023
Per dotnet/coreclr#15941 this is now called
MemoryMarshal.Cast.