When writing generic types, using a pattern as seen in Vector<T> (if (typeof(T) == typeof(int)) ... if (typeof(T) == typeof(float)) ...) once this construct grows to 9 blocks JIT will end up not correctly eliding some casts:
See sharplab
Removing any two blocks from As2<T> will improve code gen significantly (matching a non-generic version & the other version)
splitting up the function will also resolve the issue.
The sharplab link is showing codegen for . Net Framework x86 jit. For core this sharplab is more relevant.
Either way we're tail calling into C.As2 instead of inlining it, which seems odd. I'll dig in and see what's up.
C.AsByte2(Single)
L0000: vzeroupper
L0003: mov rax, C.As2[[System.Byte, System.Private.CoreLib]](Single)
L000d: jmp rax
@AndyAyersMS This is a bit of common pattern that I've noticed while using Sharplab, primarily because it comes up when doing this. I've always assumed it was some bug "in the toolchain".
The inliner has a budget that it uses to prevent runaway inlining, and it is tripping (prematurely) in this case, as (generally speaking) AggressiveInlining methods should be exempt from budgeting.
Inlines into 06000003 C:AsByte2(float):ubyte
[0 IL=0001 TR=000001 06000006] [FAILED: inline exceeds budget] C:As2(float):ubyte
That explains why the behavior changes as more checks are added -- at some point the extra IL pushes As2 over budget.
Let me look into fixing this.
Most helpful comment
The inliner has a budget that it uses to prevent runaway inlining, and it is tripping (prematurely) in this case, as (generally speaking)
AggressiveInliningmethods should be exempt from budgeting.That explains why the behavior changes as more checks are added -- at some point the extra IL pushes
As2over budget.Let me look into fixing this.