I was asked to consider how specialization should interact with SIP-23. Here is a quick test I did with some thoughts on where we are now versus where we should be.
See tlc.scala
for the code and tlc.bytecode
for the Java
bytecode that code produced (using Typelevel Scala with the
-Yliteral-types
flag enabled).
The tlc.Demo
code has four methods defined (which after
specialization compile to six methods worth of bytecode).
Here is a breakdown of those six methods:
We can see that summoning ValueOf[1]
produces a boxed value.
This is not great, but if someone knows which singleton type
they want at this moment they'd probably just write 1
so I
don't think this is a big deal.
This case does box. I think given the signature this ends up
compiling to (A => A
) there isn't a better option available
in this case.
These methods are both the generic case of specialized methods,
and have the same contours as generic
above.
This method takes an (implicit) int
parameter, and returns an
int
parameter, so from the signature (int => int
) things seem
fine. However, we do end up auto-boxing the int
to be able to
call BoxesRunTime.unboxToInt
which does introduce boxing. This
is unfortunate, although there is some chance that if the unboxToInt
method gets inlined, that Hotspot might optimize it away. (I have
no evidence either way; it would be better if this call was not
emitted by scalac.)
This method exists to show how we'd like for spec$mIc$sp
to be
compiled. Logically they have the same signature, but this one just
returns the int
it was given, which will be easily inlined and
should be suitable for basically any purpose.
I don't think there's any way that using singletons in generic,
non-specialized code can avoid boxing. I do think that the erased
form of ValueOf
should work correctly with respect to specialization
and I think we are relatively close to having that working.
It would be nice if A <: Int
implied specialization and/or never
generated any Java code that mentioned Object
. I'm uncertain how
hard it would be to achieve this but will give it some more thought.