Overview of operand stack management instructions


The OPERand stack management instructions provided by the JVM can be used directly to manipulate the operand stack, just as they are used to manipulate stacks in normal data structures

Common commands include the following:

To pop one or two elements off the top of the stack and discard them directly, use the: pop, pop2 instructions

Dup, DUp2, duP_x1, dup2_x1, duP_x2, dup2_x2

The: swap instruction is used to swap the values of the two slots at the top of the stack. The Java VIRTUAL machine does not provide the instruction to exchange the values of two 64-bit data types (long, double)

Special instruction: NOP, whose bytecode is EX00. Like noP in assembly language, it means to do nothing. This instruction can generally be used for debugging, placeholder, and so on

These instructions are generic and do not need to specify a data type for a push or pop on the stack

Dup instruction without _x

Dup is to copy data from the top of the stack and push it to the top of the stack. Generally, dUP consists of two instructions: DUP and dup2. The coefficient represents the number of slots to be copied

  • The instruction starting with DUP is used to copy the data of one Slot. Example: 1 int or 1 Reference
  • The instruction beginning with dup2 is used to copy the data of the two slots. Example: 1 long, or 2 ints, or 1 int + 1 float
Dup instruction with _x

Dup_x copies the top of the stack and inserts it into a position below the top of the stack. There are four instructions: dup_x1, dup2_x1, dup_x2, dup2_x2.

  • Dup_x1 insert position :1+1=2, that is, under the top 2 slots of the stack
  • Dup_x2 insert position :1+2=3, that is, under the top 3 slots of the stack
  • Dup2_x1 insert position :2+1=3, that is, under the top 3 slots of the stack
  • Dup2_x2 insert position :2+2=4, that is, under the top 4 slots of the stack
Description of the POP and POP2 directives
  • Pop: Pushes the s1OT value at the top of the stack out of the stack. For example, a value of short
  • Pop2: Pushes the top two slots off the stack. For example, one double, or two ints

For a basic test of operand stack instructions, look at the following example code

public class stackOperateTest { public void print( ){ object obj = new object(); string info = bj.toString(); } // Similar public void foo(){bar(); } public long bar(){ return 0; } private long index = 0; public long nextIndex() { return index++; }}

Let’s compile the code and see what happens to the bytecode of the print method.

Next, we analyzed the diagrams according to the bytecode instructions. What operations did we do?













What bytecode would it be to call the obj. ToString method directly if we didn’t need to take the info variable?

Let’s see what happens to the bytecode of the foo method.

Let’s see what happens to the bytecode of the nextIndex method.

Next, we analyzed the diagrams according to the bytecode instructions. What operations did we do?