Search code examples
jvmbytecode-manipulationjvm-bytecode

Is there a way to swap long (or double) and reference values on JVM stack?


Let's say I have following bytecode sequence

aload 0 // this
lload 1
aload 3

For the sake of the question, let's assume that these instructions are generated by other code and I don't have control over it.

I need to swap last two items on a stack, a long and a reference. I can't do it with swap, cause long takes two slots on a stack and swap doesn't care about that.

I'll get something like this when loading the class:

java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    bytecode/generated/SomeClasName.someMethod(Ljava/lang/Object;)Z @18: swap
  Reason:
    Type long_2nd (current frame, stack[3]) is not assignable to category1 type

Is there a way to swap category1 and category2 types on a stack without resorting to locals?


Solution

  • Use dup_x2 + pop.

    This requires one extra stack slot though.