编程语言
首页 > 编程语言> > java – 根据执行历史记录,给定指令的操作数堆栈大小是否不同?

java – 根据执行历史记录,给定指令的操作数堆栈大小是否不同?

作者:互联网

例如,对于方法

public int f() {
    int k = 1;
    for (int i = 0; i < 10; i++) {
        k += 2;
    }
    return k;
}

javac生成以下字节码:

public int f();
Code:
   0: iconst_1
   1: istore_1
   2: iconst_0
   3: istore_2
   4: iload_2
   5: bipush        10
   7: if_icmpge     19
  10: iinc          1, 2
  13: iinc          2, 1
  16: goto          4
  19: iload_1
  20: ireturn

在标签4处,堆栈具有相同的大小(0),无论先前是哪个指令:3或16.

对于从java代码生成的字节码,这通常是正确的吗?

解决方法:

有关锑的答案的参考,请参阅
JVM specification §4.9.2. Structural Constraints(谢谢Holger!):

  • If an instruction can be executed along several different execution paths, the operand stack must have the same depth (§2.6.2) prior to the execution of the instruction, regardless of the path taken.

在这个答案的第一个版本中,我引用了§4.10.2.1. The Process of Verification by Type Inference,它适用于不包含StackMapTable属性(版本号为49.0或更低版本)的类文件:

… The verifier ensures that at any given point in the program, no matter what code path is taken to reach that point, all of the following are true:

  • The operand stack is always the same size and contains the same types of values.

标签:java,bytecode,jvm-bytecode
来源: https://codeday.me/bug/20190727/1555212.html