eclipse-jdt / eclipse-jdt/eclipse.jdt.core
[Switch Expression] Suboptimal code generation for switch expressions with embedded try-finally blocks without catch
- Dominant language
- Java
- Stars
- 237
- Forks
- 195
- Avg merge
- 1d 12h
- Merged PRs (30d)
- 47
Description
```
public class X {
@Override
public String toString() {
return "Some X";
}
static void foo(String s1, X x, int i) {
System.out.println("s1, " + x + ", " + i);
}
public static void main(String[] args) {
foo("Hello", new X(), switch (args.hashCode()) {
default-> { try {
System.out.println();
} finally {
System.out.println();
}
yield 0;
}
});
}
}
```
Given the above code, we produce:
```
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
Code:
stack=3, locals=5, args_size=1
0: ldc #49 // String Hello
2: new #1 // class X
5: dup
6: invokespecial #51 // Method "":()V
9: astore_1
10: astore_2
11: aload_0
12: invokevirtual #52 // Method java/lang/Object.hashCode:()I
15: pop
16: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
19: invokevirtual #56 // Method java/io/PrintStream.println:()V
22: goto 36
25: astore 4
27: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
30: invokevirtual #56 // Method java/io/PrintStream.println:()V
33: aload 4
35: athrow
36: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
39: invokevirtual #56 // Method java/io/PrintStream.println:()V
42: iconst_0
43: istore_3
44: aload_2
45: aload_1
46: iload_3
47: invokestatic #58 // Method foo:(Ljava/lang/String;LX;I)V
50: return
```
I believe bci 9, 10, 43, 44, 45 and 46 is redundant.
Admittedly this is a corner case - but the fix should be very simple. Do not assume the mere presence of a try block inside the switch as calling for spill/fill of operand stack at switch expression evaluation beginning. If a catch clause is not present OR if the catch clause does not complete normally, we don't have to be conservative about saving and restoring operand stack.
This would means try-with-resources and try-finally blocks and try-catch-rethrow-finally blocks could see better sequence
Contributor guide
Assessment
This issue has not been assessed yet.