Pure methods are those without side effects: their only effect is to return a value which is a function of their arguments.
Two calls to the same pure method with the same arguments will return the same value. So, given two calls to a pure method with identical arguments, can HotSpot optimize away the second call, simply re-using the value from the first call?
For example:
int add(int x, int y) {
return x + y;
}
int addTwice(int x, int y) {
return add(x, y) + add(x, y);
}
If HotSpot doesn't inline add
inside addTwice
does it understand that add
is pure and thus call add
only once and double the return value?
Of course, such a trivial [mcve] isn't likely to be of direct interest, but similar situations can occur in practice due to inlining, divergent control flow, auto-generated code, etc.
HotSpot cannot do this so far.
If not inlined, a method call is typically opaque for JIT compiler. It is hard to make cross-method optimizations. One of the reasons is that a method entry point is volatile, i.e. it can change concurrently at run-time due to JIT compilation, re-compilation, deoptimization, JVMTI calls and so on. When HotSpot makes an explicit method call, it does not know whether the target method is interpreted or compiled, wether it collects JIT statistics, whether it is being debugged, if it has a breakpoint inside, or if JVMTI method events are enabled.
On the other hand, even if such optimization existed, it would not be too useful. Pure methods are very limited in what they can do, so they are typically short and simple and have much chances to be inlined. It is much easier for JIT to do optimizations within the same compilation scope after inlining.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With