Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can HotSpot optimize away redundant calls to pure methods without inlining them?

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.

like image 330
BeeOnRope Avatar asked Jan 01 '18 04:01

BeeOnRope


1 Answers

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.

like image 140
apangin Avatar answered Nov 15 '22 18:11

apangin