1 /* 2 * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 import java.lang.classfile.Attributes; 25 import java.lang.classfile.ClassFile; 26 import java.lang.classfile.Instruction; 27 import java.lang.classfile.components.ClassPrinter; 28 import static java.lang.classfile.Opcode.*; 29 import java.lang.constant.ClassDesc; 30 import java.lang.constant.ConstantDescs; 31 import jdk.incubator.code.bytecode.BranchCompactor; 32 import java.util.List; 33 import org.testng.Assert; 34 import org.testng.annotations.Test; 35 36 /* 37 * @test 38 * @modules jdk.incubator.code 39 * @enablePreview 40 * @run testng TestBranchCompactor 41 */ 42 public class TestBranchCompactor { 43 44 @Test 45 public void testBranchCompactor() { 46 var cc = ClassFile.of(ClassFile.StackMapsOption.DROP_STACK_MAPS); 47 var clm = cc.parse(cc.build(ClassDesc.of("c"), clb -> clb.withMethodBody("m", ConstantDescs.MTD_void, 0, 48 cb -> cb.transforming(new BranchCompactor(), cob -> { 49 var l = cob.newLabel(); 50 cob.goto_(l) //compact 51 .lineNumber(1) 52 .labelBinding(l) 53 .nop(); 54 55 l = cob.newLabel(); 56 cob.goto_w(l) //compact 57 .lineNumber(2) 58 .labelBinding(l); 59 60 l = cob.newLabel(); 61 cob.goto_(l) //compact 62 .labelBinding(l); 63 64 cob.iconst_0(); 65 l = cob.newLabel(); 66 cob.ifeq(l) //do not compact 67 .labelBinding(l); 68 69 l = cob.newLabel(); 70 cob.goto_(l) //do not compact 71 .nop() 72 .labelBinding(l) 73 .return_(); 74 })))); 75 var code = clm.methods().get(0).code().get(); 76 ClassPrinter.toYaml(code, ClassPrinter.Verbosity.TRACE_ALL, System.out::print); 77 Assert.assertEquals( 78 code.elementList().stream().mapMulti((e, ec) -> {if (e instanceof Instruction i) ec.accept(i.opcode());}).toList(), 79 List.of(NOP, ICONST_0, IFEQ, GOTO, NOP, RETURN)); 80 Assert.assertEquals(code.findAttribute(Attributes.lineNumberTable()).get().lineNumbers().size(), 2); 81 } 82 }