Sub topic 11
Speculative optimization and uncommon traps
This chapter assumes you know the tier levels and how profiling data is collected. It covers how the C2 compiler uses that data to generate faster code than a static compiler could, and what happens when the data turns out to be wrong.
Why the JIT guesses
A static compiler must produce code that is correct for every input it might see. HotSpot's C2 compiler only has to produce code that is correct for the inputs the program actually uses, plus a safe way out when something new shows up.
That safe way out is the basis of speculative optimization. The compiler reads the profile gathered at tier 0 and tier 3. It assumes the observed behavior will continue. It then drops code for everything it did not observe.
Typical observations and the speculations built on them:
| Profile observation | Speculation | Benefit |
|---|---|---|
| A call site has only ever seen one receiver class | The receiver always has that class | Virtual call becomes a direct call, which can be inlined |
| A branch has never been taken | The branch will never be taken | No code is generated for it, so the surrounding code optimizes better |
| A reference has never been null at a check | It will not be null | The explicit null check is removed |
| A class has never been loaded | It will not be needed on this path | The path is replaced by a trap |
| An array index has always been in range | It stays in range | The compiler can hoist or remove range checks |
What an uncommon trap is
An uncommon trap is a place in compiled code where the compiler left out the real logic. Instead it emitted a call into the runtime. When execution reaches that point, the JVM does the following:
- It stops running the compiled frame.
- It rebuilds the equivalent interpreter frame or frames from the compiled state.
- It resumes execution in the interpreter at the matching bytecode.
The JVM records a reason (why the assumption failed) and an action (what to do with the compiled method). Some common reasons:
class_check: the receiver type was not the one the profile predicted.null_check: a reference assumed non-null was null.unstable_if: a branch assumed never taken was taken.range_check: an index was outside the assumed bounds.unloaded: the code touched a class that was not yet loaded when it was compiled.
Common actions are none (just continue in the interpreter), maybe_recompile, reinterpret, make_not_entrant, and make_not_compiled. The next chapter covers what these do to the method. Here the point is that the trap is part of the compiled code from the start. It is a planned exit, not a crash.
A worked example: a type guard
Consider this program from the earlier chapters.
public class DeoptDemo {
interface Shape { double area(); }
static final class Square implements Shape {
public double area() { return 4.0; }
}
static final class Circle implements Shape {
public double area() { return 3.0; }
}
static double run(Shape s) {
return s.area();
}
public static void main(String[] args) {
double total = 0;
Shape square = new Square();
for (int i = 0; i < 5_000_000; i++) {
total += run(square);
}
Shape circle = new Circle();
for (int i = 0; i < 5_000_000; i++) {
total += run(circle);
}
System.out.println(total);
}
}During the first loop, the profile for the s.area() call site records one receiver class, Square. When C2 compiles run, it applies the following reasoning:
- The site is monomorphic, so it emits a guard: if the receiver's class is
Square, run the inlined body ofSquare.area(). - With the body inlined,
runreduces to roughlyreturn 4.0. - If the guard fails, it jumps to an uncommon trap with reason
class_check.
The compiled run is much cheaper than a virtual call. The cost is one class-pointer comparison, and the program must keep passing Square.
In the second loop, Circle reaches run. The guard fails and the trap fires. The thread continues in the interpreter. The JVM then invalidates the compiled code so that no new calls enter it. Run it and watch the compilation log:
javac DeoptDemo.java
java -XX:+PrintCompilation DeoptDemo | grep -E "DeoptDemo::run|made not entrant"You will typically see DeoptDemo::run compiled, then a line ending in made not entrant, then run compiled again. The exact tiers and timing vary by machine and run.
Branch speculation: unstable_if
The same idea applies to control flow. Suppose a method contains this code:
static int process(int x) {
if (x < 0) {
return slowErrorPath(x);
}
return x * 2;
}If the profile shows that x < 0 has never been true, C2 compiles the if as a trap. The error path is not compiled at all. This shrinks the method, helps inlining, and lets the optimizer treat x as non-negative on the main path. If a negative value arrives later, the trap fires with reason unstable_if.
This is why a warmup that only exercises the happy path can give misleading numbers. The first time a rare branch executes in production, it costs a trap, a switch to the interpreter, and a recompile.
Speculation without a trap: class hierarchy analysis
Not every assumption is guarded at run time. C2 also uses class hierarchy analysis (CHA). If only one loaded class implements an interface method, C2 can inline it with no guard at all. The compiled code records a dependency: "this assumes no other implementor is loaded." When a class loader later loads a second implementor, the JVM finds every compiled method with that dependency and deoptimizes it. Class loading, not execution, triggers the invalidation.
Limits on speculating
The JVM keeps counts of traps per method and per bytecode. If a bytecode keeps causing traps, repeating the same guess is pointless. Flags such as -XX:PerBytecodeTrapLimit (default 4) and -XX:PerMethodTrapLimit (default 100) cap how often C2 will speculate at a given place. Past the limit, C2 compiles the general code instead. A method that has been through this is slower than its first compilation but stable.
Seeing the traps
-XX:+PrintCompilation shows only the consequence: methods marked made not entrant. To see the reason and bytecode index, use the diagnostic log:
java -XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation -XX:LogFile=jit.xml DeoptDemo
grep "uncommon_trap" jit.xmlEach uncommon_trap element names the reason, the action, and the method and bytecode index. The format is not a stable interface and can change between JDK releases.
Common mistakes
- Assuming a trap is a bug. A few traps during startup are normal. Worry only about repeated traps in the same hot method.
- Benchmarking only one type. A microbenchmark that feeds one receiver class measures the monomorphic fast path. Real code with several types will be slower.
- Treating
made not entrantas a failure. It means the old compiled code will not accept new calls. Threads already inside it can finish. - Expecting identical output between runs. Profiles depend on timing and input order, so the set of speculations differs run to run.
Exercise
In DeoptDemo, run is compiled by C2 after the first loop. Which kind of uncommon trap fires when the Circle object first arrives, which profile observation made that speculation, and what is the alternative to a guarded speculation that C2 can use when only one implementor of an interface is loaded?
Show answer
A class_check trap fires. The profile showed that the s.area() call site had only ever seen Square, so C2 inlined Square.area() behind a receiver-class guard. The alternative is class hierarchy analysis. With only one loaded implementor, C2 can inline without a guard and record a dependency, and loading a second implementor later deoptimizes the dependent compiled code.
Exercise
A method's profile shows a branch that was never taken. C2 compiles the method with that branch replaced by a trap. Name the trap reason and give two benefits of leaving the branch out.
Show answer
The reason is unstable_if. Leaving the branch out makes the compiled method smaller, which helps it fit inlining budgets. It also removes control-flow merges, so the optimizer can make stronger assumptions about values on the remaining path.