我有以下Java代码:
public int sign(int a) {
if(a<0) return -1;
else if (a>0) return 1;
else return 0;
}
编译时生成以下字节码:
public int sign(int);
Code:
0: iload_1
1: ifge 6
4: iconst_m1
5: ireturn
6: iload_1
7: ifle 12
10: iconst_1
11: ireturn
12: iconst_0
13: ireturn
我想知道如何计算字节偏移计数(第一列),特别是当所有其他指令都是3字节时,为什么ifge
和ifle
指令的字节数是单字节指令?
答案 0 :(得分:5)
正如评论中已经指出的那样:ifge
和ifle
指令有额外的偏移量。
Java Virtual Machine Instruction Set specification for ifge
and ifle
包含相关提示:
格式的
if<cond> branchbyte1 branchbyte2
这表示该指令有两个附加字节,即“分支字节”。这些字节由单个short
值组成,以确定偏移量 - 即,当条件满足时,指令指针应该“跳转”多远。
编辑:
评论让我很好奇:offset
被定义为签名的 16位值,将跳转限制在+/- 32k的范围内。这不包括may contain up to 65535 bytes according to the code_length
in the class file的可能方法的整个范围。
所以我创建了一个测试类,看看会发生什么。这个类看起来像这样:
class FarJump
{
public static void main(String args[])
{
call(0, 1);
}
public static void call(int x, int y)
{
if (x < y)
{
y++;
y++;
... (10921 times) ...
y++;
y++;
}
System.out.println(y);
}
}
每个y++
行将被转换为iinc
指令,由3个字节组成。所以生成的字节码是
public static void call(int, int);
Code:
0: iload_0
1: iload_1
2: if_icmpge 32768
5: iinc 1, 1
8: iinc 1, 1
...(10921 times) ...
32762: iinc 1, 1
32765: iinc 1, 1
32768: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
32771: iload_1
32772: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
32775: return
可以看到它仍然使用if_icmpge
指令,偏移量为32768(编辑:它是绝对偏移。相对偏移量是32766.另见this question)
通过在原始代码中再添加一个y++
,编译后的代码突然变为
public static void call(int, int);
Code:
0: iload_0
1: iload_1
2: if_icmplt 10
5: goto_w 32781
10: iinc 1, 1
13: iinc 1, 1
....
32770: iinc 1, 1
32773: iinc 1, 1
32776: goto_w 32781
32781: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
32784: iload_1
32785: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
32788: return
因此它将条件从if_icmpge
反转为if_icmplt
,并使用goto_w
指令处理远跳,该指令包含四个分支字节,因此可以覆盖(超过)一个完整的方法范围。
答案 1 :(得分:2)