Search code examples
javajava-bytecode-asmbytecode-manipulationjvm-bytecode

Splitting InsnList into basic blocks


In the ASM Tree API, I have an InsnList, containing a list of instructions in a method.

I want to split this up into basic blocks: a sequence of instructions such that each instruction except the last one has exactly one successor, and such that no instruction except the first one can be the target of a jump.

How would I accomplish this?


Solution

  • In Java 7+ stack frames will be included in the method opcodes. Iterate through a method's InsnList and make blocks split by each FrameInsn.

    Example:

    List<InsnList> l = Lists.newList();
    InsnList il = new InsnList();
    for (AbstractInsnNode ain : method.instructions.toArray()) {
        if (ain.getType == AbstractInsnNode.FRAME){
            l.add(il);
            il = new InsnList();
        } else {
            il.add(ain);
        }
    }