iTranslated by AI
Reading the JVM | Hacking the JVM Part 5 - Handling Control Variables
Continuation from the previous article. The previous article is available here:
This series is structured as a guide to deciphering the JVM specification.
The JVM specification is vast and contains many complex details, so I will summarize the key points for each section.
Additionally, by understanding the JVM's internal structure and operating principles, this is an attempt to deeply understand Java's performance, security, and memory management mechanisms.
The series starts here:
Chapter 3: Compiling for the Java Virtual Machine
Chapter 3 of the JVM specification is titled "Compilation for the Java Virtual Machine."
This chapter explains how to compile Java source code into bytecode executable by the JVM.
Starting from this article, let's look at concrete examples to understand actual JVM instructions and their behavior.
In this article, we will learn about handling various control variables.
The handbook is available here:
3.5 More Control Examples (› 3.5 More Control Examples)
In Reading the JVM | Hacking the JVM Part 3 - Controlling with Constants and Variables, we learned how to compile for statements.
This time, we will look at how to compile other control constructs of the Java language.
These can be compiled in a straightforward manner, similar to the for statement.
(Note: The compilation of the switch statement will be covered in a separate article.)
Compiling while Statements
A while loop can be implemented using a simple combination of instructions available in the JVM.
Furthermore, it is very similar to the compilation method of for statements introduced in the previous article.
In the example below, an int control variable i is used, and the loop executes as long as i is less than 100. Inside the loop, the value of i is incremented by 1.
void whileInt() {
int i = 0;
while (i < 100) {
i++;
}
}
When compiled, this becomes:
void whileInt() {
iconst_0 // Push constant 0 onto the stack
istore_1 // Store value into local variable i
goto LoopCheck // Jump to the loop condition check
LoopBody:
iinc 1 1 // Increment local variable i by 1
LoopCheck:
iload_1 // Load the value of local variable i onto the stack
bipush 100 // Push constant 100 onto the stack
if_icmplt LoopBody // If i < 100, jump to the loop body
return // End the method
}
Example instructions in javap style
Method whileInt()
0 iconst_0 // Push constant 0 onto the stack
1 istore_1 // Store into local variable i
2 goto 8 // Jump to the loop condition check
5 iinc 1 1 // Increment local variable i by 1
8 iload_1 // Load local variable i onto the stack
9 bipush 100 // Push constant 100 onto the stack
11 if_icmplt 5 // If i < 100, jump to the loop body
14 return // End the method
In this example, the if_icmplt instruction is used to check the condition of the while statement.
As learned in the previous article, since the control variable is of type int, all instructions used are of the int family.
The following diagram shows the flow of this sequence of instructions.
Loop Condition Check: Before or After?
In a typical Java while statement, the condition is written at the top.
Therefore, one might expect that when compiled, the condition check would be placed at the beginning of the instruction sequence.
However, in reality, the condition check is not at the top; rather, it is placed after the loop body.
Why is this done deliberately?
By placing the loop condition after the body, the number of instructions executed when the loop runs multiple times can be significantly reduced.
When the loop condition is placed at the beginning
Let's consider what would happen if the loop condition were placed at the top.
Look at the excerpted instruction sequence below:
LoopCheck:
if_icmpge End // Check the loop condition
... // Loop body
goto LoopCheck // After the loop body, go back to the top (condition check).
End:
In this sequence, the condition is checked first, and if the loop should terminate, it jumps to End. If the loop should continue, it naturally proceeds to the loop body, after which a goto LoopCheck instruction returns to the top to check the condition again.
For example, consider this instruction sequence looping 100 times:
-
if_icmpge Endinstruction: 100 times -
goto LoopCheckinstruction: 99 times
That is a total of 199 jump instructions executed.
When the loop condition is placed after the body
Now consider the case where the loop condition is placed after the body.
Look at the excerpted instruction sequence below:
goto LoopCheck // Initially skip the loop body and jump to the condition check.
LoopBody:
... // Loop body
LoopCheck:
if_icmplt LoopBody // Check the loop condition and jump to the loop body.
In this sequence, by placing the condition check immediately after the loop body, the execution can naturally transition to the condition check without a jump after the loop body.
Again, consider this instruction sequence looping 100 times:
-
goto LoopCheckinstruction: 1 time -
if_icmplt LoopBodyinstruction: 99 times
That is a total of 100 jump instructions executed.
Advantage of placing the loop condition after the body
By placing the loop condition after the body, the number of jump instructions executed is reduced by about half.
This optimization is especially effective for constructs like while statements, which are assumed to loop many times.
Of course, in cases where the loop body never executes, the initial goto instruction is wasted.
However, from an overall perspective, the performance gain from multiple loop iterations is overwhelmingly more beneficial.
This approach is also applied to other loop constructs like for statements, clearly showing that the Java compiler and JVM generate instruction sequences with awareness of the number of jump instructions.
Compiling while Statements with double Type
Let's look at control constructs using other data types.
They can be compiled similarly to the while statement with int control variable, but they require instructions appropriate for their types.
This requires more instructions and results in somewhat less efficient code.
In the example below, a double control variable d is used, and the loop executes as long as d is less than 100.1. Inside the loop, d is incremented by 1.
void whileDouble() {
double d = 0.0;
while (d < 100.1) {
d++;
}
}
When compiled, this becomes:
void whileDouble() {
dconst_0 // Push constant 0.0 onto the stack
dstore_1 // Store value into local variable d
goto LoopCheck // Jump to the loop condition check
LoopBody:
dload_1 // Load the value of local variable d onto the stack
dconst_1 // Push constant 1.0 onto the stack
dadd // Add the two top stack values and push the result
dstore_1 // Store the result into local variable d
LoopCheck:
dload_1 // Load the value of local variable d onto the stack
ldc2_w 100.1 // Push constant 100.1 onto the stack
dcmpg // Compare the two top stack values and push the result
iflt LoopBody // If d < 100.1, jump to the loop body
return // End the method
}
Example instructions in javap style
Method whileDouble()
0 dconst_0 // Push constant 0.0 onto the stack
1 dstore_1 // Store into local variable d
2 goto 9 // Jump to the loop condition check
5 dload_1 // Load local variable d onto the stack
6 dconst_1 // Push constant 1.0 onto the stack
7 dadd // Add the two top stack values
8 dstore_1 // Store result into local variable d
9 dload_1 // Load local variable d onto the stack
10 ldc2_w #4 // Push constant 100.1 onto the stack
13 dcmpg // Compare the two top stack values
14 iflt 5 // If d < 100.1, jump to the loop body
17 return // End the method
Note: The runtime constant pool excerpt:
#4: double 100.1
Thus, in a while statement with a double control variable, initial values are set with dconst_0, and the control variable is loaded onto the stack with dload_1. The value is incremented by 1 using dadd, and comparison between the control variable and the constant is performed using dcmpg. Finally, the loop condition is checked with iflt, jumping to the loop body if necessary.
The following diagram shows the flow of this sequence of instructions.
#### Instructions Are Not Fully Orthogonal
Here, some readers might think: "In the loop using an int control variable, the if_icmplt instruction was used, but here, after dcmpg, the iflt instruction is used. Why is that?"
I understand what you mean.
Indeed, in the loop with an int control variable, the combined compare-and-branch instruction if_icmplt was used. On the other hand, in the loop with a double control variable, first a dcmpg instruction is used for comparison, and then the jump is performed with iflt. That is, the comparison and jump are separated.
So, you might think, "Couldn't we use icmpg and iflt for int as well?" or "Shouldn't there be a if_dcmpgt instruction for double?" (Note: icmpg does not exist, and neither does if_dcmpgt.)
This relates to constraints in the JVM instruction set design.
There Is a Limit on the Number of Instructions
JVM instructions consist of an opcode and operands. The opcode is a 1-byte (8-bit = 256 values) value that represents the instruction type. This means that the JVM can only define up to 256 instructions.
Because of this limited number, it is not possible to define a large number of dedicated instructions for each type.
Why int Type Is Treated Specially
Despite that, why are there if_icmp<op> instructions for int but no if_dcmp<op> instructions for double?
Let's look at which types can use if_icmp_<op> instructions and which can use dcmpg and fcmpg instructions.
| Type |
if_icmp_<op> instruction |
dcmpg instruction |
fcmpg instruction |
|---|---|---|---|
byte |
○ Yes | × No | × No |
char |
○ Yes | × No | × No |
short |
○ Yes | × No | × No |
int |
○ Yes | × No | × No |
boolean |
○ Yes | × No | × No |
long |
× No | × No | × No |
float |
× No | × No | ○ Yes |
double |
× No | ○ Yes | × No |
From this, we can see that if_icmp<op> is a general-purpose instruction applicable not only to int but also to byte, char, short, and boolean types. All these are treated the same as int on the stack (they are 32 bits wide), so a single instruction suffices.
In other words, only the int family of types, which are frequently used and easily unified, have special combined compare-and-branch instructions.
But that is not the only reason.
Why Combined Compare-and-Jump Instructions Cannot Be Unified for long, float, and double
Consider the comparison process. When comparing int values, it's simply a matter of comparing 32-bit integers, so instructions like if_icmplt are sufficient. On the other hand, long and double are 64-bit wide, so a single value occupies two stack slots. This makes stack operations more complex, and the same approach cannot be universally implemented.
Furthermore, comparisons for float and double types need to account for special values like NaN (Not a Number) and infinity (Infinity). Notably, NaN is never "equal" to anything, and ordering comparisons always yield false. For this reason, the JVM defines instructions like fcmpg and dcmpg, which treat NaN as greater, and fcmpl and dcmpl, which treat NaN as less.
Thus, rather than defining individual branch instructions, centralizing the comparison logic helps save instruction count and contributes to better performance.
Choosing the Appropriate Floating-Point Instruction
In the example of a while statement with a double control variable, the dcmpg instruction was used. As mentioned, for floating-point comparisons, different instructions are available for each type.
-
floattype:-
fcmpg: Treats NaN as greater -
fcmpl: Treats NaN as less
-
-
doubletype:-
dcmpg: Treats NaN as greater -
dcmpl: Treats NaN as less
-
These instructions differ only in how they handle NaN.
As noted earlier, NaN has no order. Therefore, floating-point comparisons always yield false when an operand is NaN.
The compiler must choose the appropriate comparison instruction so that the result is the same whether a non-NaN comparison fails or not. Consider the following code:
void lessThan100(double d) {
if (d < 100.0) {
return 1;
} else {
return -1;
}
}
When compiled, this becomes:
void lessThan100(double d) {
dload_1 // Load the value of local variable d onto the stack
ldc2_w 100.0 // Push constant 100.0 onto the stack
dcmpg // If d is NaN or d > 100.0, push 1
// If d == 100.0, push 0
ifge Else // If d >= 100.0, jump to Else
iconst_1 // Push 1
ireturn // Return 1
Else:
iconst_m1 // Push -1
ireturn // Return -1
}
Example instructions in javap style
Method lessThan100(double)
0 dload_1 // Load local variable d onto stack
1 ldc2_w #4 // Push constant 100.0 onto stack
4 dcmpg // If d is NaN or d > 100.0, push 1
5 ifge 10 // If d >= 100.0, jump to Else
8 iconst_1 // Push 1
9 ireturn // Return 1
10 iconst_m1 // Push -1
11 ireturn // Return -1
Note: The runtime constant pool excerpt:
#4: double 100.0
In this example, the dcmpg instruction is used to check whether d is NaN. The dcmpg instruction works as follows:
- If
dis NaN, push1onto the stack - If
dis less than100.0, push-1 - If
dis equal to100.0, push0 - If
dis greater than100.0, push1
Thus, the code is correctly compiled to return 1 if d is less than 100.0, and -1 otherwise.
What If the Wrong Instruction Is Used?
Now, let's consider what would happen if the dcmpl instruction were mistakenly used instead of dcmpg.
In this case, the handling of NaN changes: if d is NaN, it will push -1. Furthermore, the ifge instruction will not branch when d is NaN, so the iconst_1 instruction will be executed.
In other words, even when d < 100.0 or d == NaN, it will return 1, which contradicts the intended meaning of the code.
According to the IEEE 754 floating-point specification, NaN is not equal to any value, so all comparisons are false. Therefore, the compiler must choose between the Tcmpg or Tcml instruction based on this difference in NaN handling to produce semantically correct comparisons.
Note that using dcmpl and ifle can achieve the same result, as shown below:
int greaterThan100(double d) {
if (d > 100.0) {
return 1;
} else {
return -1;
}
}
This compiles as follows:
int greaterThan100(double d) {
dload_1 // Load the value of local variable d onto the stack
ldc2_w 100.0 // Push constant 100.0 onto the stack
dcmpl // If d is NaN or d < 100.0, push 1
// If d == 100.0, push 0
ifle Else // If d <= 100.0, jump to Else
iconst_1 // Push 1
ireturn // Return 1
Else:
iconst_m1 // Push -1
ireturn // Return -1
}
Example instructions in javap style
Method greaterThan100(double)
0 dload_1 // Load local variable d onto stack
1 ldc2_w #4 // Push constant 100.0 onto stack
4 dcmpl // If d is NaN or d < 100.0, push 1
5 ifle 10 // If d <= 100.0, jump to Else
8 iconst_1 // Push 1
9 ireturn // Return 1
10 iconst_m1 // Push -1
11 ireturn // Return -1
Note: The runtime constant pool excerpt:
#4: double 100.0
The following diagram shows the flow of this sequence of instructions.
In this way, by properly considering the handling of NaN, the compiler selects the correct comparison instruction and achieves the intended behavior. If both dcmpg and dcmpl instructions did not exist, detecting NaN would require many more instructions.
Summary
In this article, we learned about various flow control methods using JVM instructions. In particular, we examined the compilation of while statements and the importance of selecting the correct floating-point comparison instruction.
Next time, we will learn about calling methods.
Next Article
References & Links
- Lindholm, T., Yellin, F., Bracha, G., & Smith, W. M. D. (2025). The Java® Virtual Machine Specification: Java SE 24 Edition.
- Lindholm, T., & Yellin, F. (1999). The Java™ Virtual Machine Specification (2nd ed.). Addison-Wesley. ISBN 978-0-201-43294-7
- Otavio, S. (2024). Mastering the Java Virtual Machine. Packet Publishing. ISBN 978-1-835-46796-1
- Godfrey, N., & Koichi , M. (2010). Decompiling Java: Reverse Analysis and Code Obfuscation ISBN 978-4-87311-449-1
Discussion