1 /* 2 * Copyright (c) 2012, 2021, 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. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.org.objectweb.asm.ClassWriter; 29 import jdk.internal.org.objectweb.asm.FieldVisitor; 30 import jdk.internal.org.objectweb.asm.Label; 31 import jdk.internal.org.objectweb.asm.MethodVisitor; 32 import jdk.internal.org.objectweb.asm.Opcodes; 33 import jdk.internal.org.objectweb.asm.Type; 34 import sun.invoke.util.VerifyAccess; 35 import sun.invoke.util.VerifyType; 36 import sun.invoke.util.Wrapper; 37 import sun.reflect.misc.ReflectUtil; 38 39 import java.io.File; 40 import java.io.FileOutputStream; 41 import java.io.IOException; 42 import java.lang.reflect.Modifier; 43 import java.util.ArrayList; 44 import java.util.Arrays; 45 import java.util.HashMap; 46 import java.util.List; 47 import java.util.Set; 48 import java.util.stream.Stream; 49 50 import static java.lang.invoke.LambdaForm.BasicType; 51 import static java.lang.invoke.LambdaForm.BasicType.*; 52 import static java.lang.invoke.LambdaForm.*; 53 import static java.lang.invoke.MethodHandleNatives.Constants.*; 54 import static java.lang.invoke.MethodHandleStatics.*; 55 import static java.lang.invoke.MethodHandles.Lookup.*; 56 57 /** 58 * Code generation backend for LambdaForm. 59 * <p> 60 * @author John Rose, JSR 292 EG 61 */ 62 class InvokerBytecodeGenerator { 63 /** Define class names for convenience. */ 64 private static final String MH = "java/lang/invoke/MethodHandle"; 65 private static final String MHI = "java/lang/invoke/MethodHandleImpl"; 66 private static final String LF = "java/lang/invoke/LambdaForm"; 67 private static final String LFN = "java/lang/invoke/LambdaForm$Name"; 68 private static final String CLS = "java/lang/Class"; 69 private static final String OBJ = "java/lang/Object"; 70 private static final String OBJARY = "[Ljava/lang/Object;"; 71 72 private static final String LOOP_CLAUSES = MHI + "$LoopClauses"; 73 private static final String MHARY2 = "[[L" + MH + ";"; 74 private static final String MH_SIG = "L" + MH + ";"; 75 76 77 private static final String LF_SIG = "L" + LF + ";"; 78 private static final String LFN_SIG = "L" + LFN + ";"; 79 private static final String LL_SIG = "(L" + OBJ + ";)L" + OBJ + ";"; 80 private static final String LLV_SIG = "(L" + OBJ + ";L" + OBJ + ";)V"; 81 private static final String CLASS_PREFIX = LF + "$"; 82 private static final String SOURCE_PREFIX = "LambdaForm$"; 83 84 /** Name of its super class*/ 85 static final String INVOKER_SUPER_NAME = OBJ; 86 87 /** Name of new class */ 88 private final String name; 89 private final String className; 90 91 private final LambdaForm lambdaForm; 92 private final String invokerName; 93 private final MethodType invokerType; 94 95 /** Info about local variables in compiled lambda form */ 96 private int[] localsMap; // index 97 private Class<?>[] localClasses; // type 98 99 /** ASM bytecode generation. */ 100 private ClassWriter cw; 101 private MethodVisitor mv; 102 private final List<ClassData> classData = new ArrayList<>(); 103 104 /** Single element internal class name lookup cache. */ 105 private Class<?> lastClass; 106 private String lastInternalName; 107 108 private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory(); 109 private static final Class<?> HOST_CLASS = LambdaForm.class; 110 private static final MethodHandles.Lookup LOOKUP = lookup(); 111 112 private static MethodHandles.Lookup lookup() { 113 try { 114 return MethodHandles.privateLookupIn(HOST_CLASS, IMPL_LOOKUP); 115 } catch (IllegalAccessException e) { 116 throw newInternalError(e); 117 } 118 } 119 120 /** Main constructor; other constructors delegate to this one. */ 121 private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize, 122 String name, String invokerName, MethodType invokerType) { 123 int p = invokerName.indexOf('.'); 124 if (p > -1) { 125 name = invokerName.substring(0, p); 126 invokerName = invokerName.substring(p + 1); 127 } 128 if (DUMP_CLASS_FILES) { 129 name = makeDumpableClassName(name); 130 } 131 this.name = name; 132 this.className = CLASS_PREFIX + name; 133 this.lambdaForm = lambdaForm; 134 this.invokerName = invokerName; 135 this.invokerType = invokerType; 136 this.localsMap = new int[localsMapSize+1]; // last entry of localsMap is count of allocated local slots 137 this.localClasses = new Class<?>[localsMapSize+1]; 138 } 139 140 /** For generating LambdaForm interpreter entry points. */ 141 private InvokerBytecodeGenerator(String name, String invokerName, MethodType invokerType) { 142 this(null, invokerType.parameterCount(), 143 name, invokerName, invokerType); 144 MethodType mt = invokerType.erase(); 145 // Create an array to map name indexes to locals indexes. 146 localsMap[0] = 0; // localsMap has at least one element 147 for (int i = 1, index = 0; i < localsMap.length; i++) { 148 Wrapper w = Wrapper.forBasicType(mt.parameterType(i - 1)); 149 index += w.stackSlots(); 150 localsMap[i] = index; 151 } 152 } 153 154 /** For generating customized code for a single LambdaForm. */ 155 private InvokerBytecodeGenerator(String name, LambdaForm form, MethodType invokerType) { 156 this(name, form.lambdaName(), form, invokerType); 157 } 158 159 /** For generating customized code for a single LambdaForm. */ 160 InvokerBytecodeGenerator(String name, String invokerName, 161 LambdaForm form, MethodType invokerType) { 162 this(form, form.names.length, 163 name, invokerName, invokerType); 164 // Create an array to map name indexes to locals indexes. 165 Name[] names = form.names; 166 for (int i = 0, index = 0; i < localsMap.length; i++) { 167 localsMap[i] = index; 168 if (i < names.length) { 169 BasicType type = names[i].type(); 170 index += type.basicTypeSlots(); 171 } 172 } 173 } 174 175 /** instance counters for dumped classes */ 176 private static final HashMap<String,Integer> DUMP_CLASS_FILES_COUNTERS; 177 /** debugging flag for saving generated class files */ 178 private static final File DUMP_CLASS_FILES_DIR; 179 180 static { 181 if (DUMP_CLASS_FILES) { 182 DUMP_CLASS_FILES_COUNTERS = new HashMap<>(); 183 try { 184 File dumpDir = new File("DUMP_CLASS_FILES"); 185 if (!dumpDir.exists()) { 186 dumpDir.mkdirs(); 187 } 188 DUMP_CLASS_FILES_DIR = dumpDir; 189 System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/..."); 190 } catch (Exception e) { 191 throw newInternalError(e); 192 } 193 } else { 194 DUMP_CLASS_FILES_COUNTERS = null; 195 DUMP_CLASS_FILES_DIR = null; 196 } 197 } 198 199 private void maybeDump(final byte[] classFile) { 200 if (DUMP_CLASS_FILES) { 201 maybeDump(className, classFile); 202 } 203 } 204 205 // Also used from BoundMethodHandle 206 @SuppressWarnings("removal") 207 static void maybeDump(final String className, final byte[] classFile) { 208 if (DUMP_CLASS_FILES) { 209 java.security.AccessController.doPrivileged( 210 new java.security.PrivilegedAction<>() { 211 public Void run() { 212 try { 213 String dumpName = className.replace('.','/'); 214 File dumpFile = new File(DUMP_CLASS_FILES_DIR, dumpName+".class"); 215 System.out.println("dump: " + dumpFile); 216 dumpFile.getParentFile().mkdirs(); 217 FileOutputStream file = new FileOutputStream(dumpFile); 218 file.write(classFile); 219 file.close(); 220 return null; 221 } catch (IOException ex) { 222 throw newInternalError(ex); 223 } 224 } 225 }); 226 } 227 } 228 229 private static String makeDumpableClassName(String className) { 230 Integer ctr; 231 synchronized (DUMP_CLASS_FILES_COUNTERS) { 232 ctr = DUMP_CLASS_FILES_COUNTERS.get(className); 233 if (ctr == null) ctr = 0; 234 DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1); 235 } 236 String sfx = ctr.toString(); 237 while (sfx.length() < 3) 238 sfx = "0" + sfx; 239 className += sfx; 240 return className; 241 } 242 243 static class ClassData { 244 final String name; 245 final String desc; 246 final Object value; 247 248 ClassData(String name, String desc, Object value) { 249 this.name = name; 250 this.desc = desc; 251 this.value = value; 252 } 253 254 public String name() { return name; } 255 public String toString() { 256 return name + ",value="+value; 257 } 258 } 259 260 String classData(Object arg) { 261 String desc; 262 if (arg instanceof Class) { 263 desc = "Ljava/lang/Class;"; 264 } else if (arg instanceof MethodHandle) { 265 desc = MH_SIG; 266 } else if (arg instanceof LambdaForm) { 267 desc = LF_SIG; 268 } else { 269 desc = "Ljava/lang/Object;"; 270 } 271 272 // unique static variable name 273 String name; 274 if (DUMP_CLASS_FILES) { 275 Class<?> c = arg.getClass(); 276 while (c.isArray()) { 277 c = c.getComponentType(); 278 } 279 name = "_DATA_" + c.getSimpleName() + "_" + classData.size(); 280 } else { 281 name = "_D_" + classData.size(); 282 } 283 ClassData cd = new ClassData(name, desc, arg); 284 classData.add(cd); 285 return name; 286 } 287 288 List<Object> classDataValues() { 289 final List<ClassData> cd = classData; 290 return switch(cd.size()) { 291 case 0 -> List.of(); 292 case 1 -> List.of(cd.get(0).value); 293 case 2 -> List.of(cd.get(0).value, cd.get(1).value); 294 case 3 -> List.of(cd.get(0).value, cd.get(1).value, cd.get(2).value); 295 case 4 -> List.of(cd.get(0).value, cd.get(1).value, cd.get(2).value, cd.get(3).value); 296 default -> { 297 Object[] data = new Object[classData.size()]; 298 for (int i = 0; i < classData.size(); i++) { 299 data[i] = classData.get(i).value; 300 } 301 yield List.of(data); 302 } 303 }; 304 } 305 306 private static String debugString(Object arg) { 307 if (arg instanceof MethodHandle mh) { 308 MemberName member = mh.internalMemberName(); 309 if (member != null) 310 return member.toString(); 311 return mh.debugString(); 312 } 313 return arg.toString(); 314 } 315 316 /** 317 * Extract the MemberName of a newly-defined method. 318 */ 319 private MemberName loadMethod(byte[] classFile) { 320 Class<?> invokerClass = LOOKUP.makeHiddenClassDefiner(className, classFile, Set.of()) 321 .defineClass(true, classDataValues()); 322 return resolveInvokerMember(invokerClass, invokerName, invokerType); 323 } 324 325 private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) { 326 MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic); 327 try { 328 member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, 329 HOST_CLASS, LM_TRUSTED, 330 ReflectiveOperationException.class); 331 } catch (ReflectiveOperationException e) { 332 throw newInternalError(e); 333 } 334 return member; 335 } 336 337 /** 338 * Set up class file generation. 339 */ 340 private ClassWriter classFilePrologue() { 341 final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC 342 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); 343 setClassWriter(cw); 344 cw.visit(CLASSFILE_VERSION, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, 345 className, null, INVOKER_SUPER_NAME, null); 346 cw.visitSource(SOURCE_PREFIX + name, null); 347 return cw; 348 } 349 350 private void methodPrologue() { 351 String invokerDesc = invokerType.toMethodDescriptorString(); 352 mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null); 353 } 354 355 /** 356 * Tear down class file generation. 357 */ 358 private void methodEpilogue() { 359 mv.visitMaxs(0, 0); 360 mv.visitEnd(); 361 } 362 363 /* 364 * <clinit> to initialize the static final fields with the live class data 365 * LambdaForms can't use condy due to bootstrapping issue. 366 */ 367 static void clinit(ClassWriter cw, String className, List<ClassData> classData) { 368 if (classData.isEmpty()) 369 return; 370 371 for (ClassData p : classData) { 372 // add the static field 373 FieldVisitor fv = cw.visitField(Opcodes.ACC_STATIC|Opcodes.ACC_FINAL, p.name, p.desc, null, null); 374 fv.visitEnd(); 375 } 376 377 MethodVisitor mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null); 378 mv.visitCode(); 379 mv.visitLdcInsn(Type.getType("L" + className + ";")); 380 mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles", 381 "classData", "(Ljava/lang/Class;)Ljava/lang/Object;", false); 382 // we should optimize one single element case that does not need to create a List 383 mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/List"); 384 mv.visitVarInsn(Opcodes.ASTORE, 0); 385 int index = 0; 386 for (ClassData p : classData) { 387 // initialize the static field 388 mv.visitVarInsn(Opcodes.ALOAD, 0); 389 emitIconstInsn(mv, index++); 390 mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", 391 "get", "(I)Ljava/lang/Object;", true); 392 mv.visitTypeInsn(Opcodes.CHECKCAST, p.desc.substring(1, p.desc.length()-1)); 393 mv.visitFieldInsn(Opcodes.PUTSTATIC, className, p.name, p.desc); 394 } 395 mv.visitInsn(Opcodes.RETURN); 396 mv.visitMaxs(2, 1); 397 mv.visitEnd(); 398 } 399 400 /* 401 * Low-level emit helpers. 402 */ 403 private void emitConst(Object con) { 404 if (con == null) { 405 mv.visitInsn(Opcodes.ACONST_NULL); 406 return; 407 } 408 if (con instanceof Integer) { 409 emitIconstInsn((int) con); 410 return; 411 } 412 if (con instanceof Byte) { 413 emitIconstInsn((byte)con); 414 return; 415 } 416 if (con instanceof Short) { 417 emitIconstInsn((short)con); 418 return; 419 } 420 if (con instanceof Character) { 421 emitIconstInsn((char)con); 422 return; 423 } 424 if (con instanceof Long) { 425 long x = (long) con; 426 short sx = (short)x; 427 if (x == sx) { 428 if (sx >= 0 && sx <= 1) { 429 mv.visitInsn(Opcodes.LCONST_0 + (int) sx); 430 } else { 431 emitIconstInsn((int) x); 432 mv.visitInsn(Opcodes.I2L); 433 } 434 return; 435 } 436 } 437 if (con instanceof Float) { 438 float x = (float) con; 439 short sx = (short)x; 440 if (x == sx) { 441 if (sx >= 0 && sx <= 2) { 442 mv.visitInsn(Opcodes.FCONST_0 + (int) sx); 443 } else { 444 emitIconstInsn((int) x); 445 mv.visitInsn(Opcodes.I2F); 446 } 447 return; 448 } 449 } 450 if (con instanceof Double) { 451 double x = (double) con; 452 short sx = (short)x; 453 if (x == sx) { 454 if (sx >= 0 && sx <= 1) { 455 mv.visitInsn(Opcodes.DCONST_0 + (int) sx); 456 } else { 457 emitIconstInsn((int) x); 458 mv.visitInsn(Opcodes.I2D); 459 } 460 return; 461 } 462 } 463 if (con instanceof Boolean) { 464 emitIconstInsn((boolean) con ? 1 : 0); 465 return; 466 } 467 // fall through: 468 mv.visitLdcInsn(con); 469 } 470 471 private void emitIconstInsn(final int cst) { 472 emitIconstInsn(mv, cst); 473 } 474 475 private static void emitIconstInsn(MethodVisitor mv, int cst) { 476 if (cst >= -1 && cst <= 5) { 477 mv.visitInsn(Opcodes.ICONST_0 + cst); 478 } else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) { 479 mv.visitIntInsn(Opcodes.BIPUSH, cst); 480 } else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) { 481 mv.visitIntInsn(Opcodes.SIPUSH, cst); 482 } else { 483 mv.visitLdcInsn(cst); 484 } 485 } 486 487 /* 488 * NOTE: These load/store methods use the localsMap to find the correct index! 489 */ 490 private void emitLoadInsn(BasicType type, int index) { 491 int opcode = loadInsnOpcode(type); 492 mv.visitVarInsn(opcode, localsMap[index]); 493 } 494 495 private int loadInsnOpcode(BasicType type) throws InternalError { 496 return switch (type) { 497 case I_TYPE -> Opcodes.ILOAD; 498 case J_TYPE -> Opcodes.LLOAD; 499 case F_TYPE -> Opcodes.FLOAD; 500 case D_TYPE -> Opcodes.DLOAD; 501 case L_TYPE -> Opcodes.ALOAD; 502 default -> throw new InternalError("unknown type: " + type); 503 }; 504 } 505 private void emitAloadInsn(int index) { 506 emitLoadInsn(L_TYPE, index); 507 } 508 509 private void emitStoreInsn(BasicType type, int index) { 510 int opcode = storeInsnOpcode(type); 511 mv.visitVarInsn(opcode, localsMap[index]); 512 } 513 514 private int storeInsnOpcode(BasicType type) throws InternalError { 515 return switch (type) { 516 case I_TYPE -> Opcodes.ISTORE; 517 case J_TYPE -> Opcodes.LSTORE; 518 case F_TYPE -> Opcodes.FSTORE; 519 case D_TYPE -> Opcodes.DSTORE; 520 case L_TYPE -> Opcodes.ASTORE; 521 default -> throw new InternalError("unknown type: " + type); 522 }; 523 } 524 private void emitAstoreInsn(int index) { 525 emitStoreInsn(L_TYPE, index); 526 } 527 528 private byte arrayTypeCode(Wrapper elementType) { 529 return (byte) switch (elementType) { 530 case BOOLEAN -> Opcodes.T_BOOLEAN; 531 case BYTE -> Opcodes.T_BYTE; 532 case CHAR -> Opcodes.T_CHAR; 533 case SHORT -> Opcodes.T_SHORT; 534 case INT -> Opcodes.T_INT; 535 case LONG -> Opcodes.T_LONG; 536 case FLOAT -> Opcodes.T_FLOAT; 537 case DOUBLE -> Opcodes.T_DOUBLE; 538 case OBJECT -> 0; // in place of Opcodes.T_OBJECT 539 default -> throw new InternalError(); 540 }; 541 } 542 543 private int arrayInsnOpcode(byte tcode, int aaop) throws InternalError { 544 assert(aaop == Opcodes.AASTORE || aaop == Opcodes.AALOAD); 545 int xas = switch (tcode) { 546 case Opcodes.T_BOOLEAN -> Opcodes.BASTORE; 547 case Opcodes.T_BYTE -> Opcodes.BASTORE; 548 case Opcodes.T_CHAR -> Opcodes.CASTORE; 549 case Opcodes.T_SHORT -> Opcodes.SASTORE; 550 case Opcodes.T_INT -> Opcodes.IASTORE; 551 case Opcodes.T_LONG -> Opcodes.LASTORE; 552 case Opcodes.T_FLOAT -> Opcodes.FASTORE; 553 case Opcodes.T_DOUBLE -> Opcodes.DASTORE; 554 case 0 -> Opcodes.AASTORE; 555 default -> throw new InternalError(); 556 }; 557 return xas - Opcodes.AASTORE + aaop; 558 } 559 560 /** 561 * Emit a boxing call. 562 * 563 * @param wrapper primitive type class to box. 564 */ 565 private void emitBoxing(Wrapper wrapper) { 566 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 567 String name = "valueOf"; 568 String desc = "(" + wrapper.basicTypeChar() + ")L" + owner + ";"; 569 mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false); 570 } 571 572 /** 573 * Emit an unboxing call (plus preceding checkcast). 574 * 575 * @param wrapper wrapper type class to unbox. 576 */ 577 private void emitUnboxing(Wrapper wrapper) { 578 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 579 String name = wrapper.primitiveSimpleName() + "Value"; 580 String desc = "()" + wrapper.basicTypeChar(); 581 emitReferenceCast(wrapper.wrapperType(), null); 582 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false); 583 } 584 585 /** 586 * Emit an implicit conversion for an argument which must be of the given pclass. 587 * This is usually a no-op, except when pclass is a subword type or a reference other than Object or an interface. 588 * 589 * @param ptype type of value present on stack 590 * @param pclass type of value required on stack 591 * @param arg compile-time representation of value on stack (Node, constant) or null if none 592 */ 593 private void emitImplicitConversion(BasicType ptype, Class<?> pclass, Object arg) { 594 assert(basicType(pclass) == ptype); // boxing/unboxing handled by caller 595 if (pclass == ptype.basicTypeClass() && ptype != L_TYPE) 596 return; // nothing to do 597 switch (ptype) { 598 case L_TYPE: 599 if (VerifyType.isNullConversion(Object.class, pclass, false)) { 600 if (PROFILE_LEVEL > 0) 601 emitReferenceCast(Object.class, arg); 602 return; 603 } 604 emitReferenceCast(pclass, arg); 605 return; 606 case I_TYPE: 607 if (!VerifyType.isNullConversion(int.class, pclass, false)) 608 emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass)); 609 return; 610 } 611 throw newInternalError("bad implicit conversion: tc="+ptype+": "+pclass); 612 } 613 614 /** Update localClasses type map. Return true if the information is already present. */ 615 private boolean assertStaticType(Class<?> cls, Name n) { 616 int local = n.index(); 617 Class<?> aclass = localClasses[local]; 618 if (aclass != null && (aclass == cls || cls.isAssignableFrom(aclass))) { 619 return true; // type info is already present 620 } else if (aclass == null || aclass.isAssignableFrom(cls)) { 621 localClasses[local] = cls; // type info can be improved 622 } 623 return false; 624 } 625 626 private void emitReferenceCast(Class<?> cls, Object arg) { 627 Name writeBack = null; // local to write back result 628 if (arg instanceof Name n) { 629 if (lambdaForm.useCount(n) > 1) { 630 // This guy gets used more than once. 631 writeBack = n; 632 if (assertStaticType(cls, n)) { 633 return; // this cast was already performed 634 } 635 } 636 } 637 if (isStaticallyNameable(cls)) { 638 String sig = getInternalName(cls); 639 mv.visitTypeInsn(Opcodes.CHECKCAST, sig); 640 } else { 641 mv.visitFieldInsn(Opcodes.GETSTATIC, className, classData(cls), "Ljava/lang/Class;"); 642 mv.visitInsn(Opcodes.SWAP); 643 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLS, "cast", LL_SIG, false); 644 if (Object[].class.isAssignableFrom(cls)) 645 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY); 646 else if (PROFILE_LEVEL > 0) 647 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ); 648 } 649 if (writeBack != null) { 650 mv.visitInsn(Opcodes.DUP); 651 emitAstoreInsn(writeBack.index()); 652 } 653 } 654 655 /** 656 * Emits an actual return instruction conforming to the given return type. 657 */ 658 private void emitReturnInsn(BasicType type) { 659 int opcode = switch (type) { 660 case I_TYPE -> Opcodes.IRETURN; 661 case J_TYPE -> Opcodes.LRETURN; 662 case F_TYPE -> Opcodes.FRETURN; 663 case D_TYPE -> Opcodes.DRETURN; 664 case L_TYPE -> Opcodes.ARETURN; 665 case V_TYPE -> Opcodes.RETURN; 666 default -> throw new InternalError("unknown return type: " + type); 667 }; 668 mv.visitInsn(opcode); 669 } 670 671 private String getInternalName(Class<?> c) { 672 if (c == Object.class) return OBJ; 673 else if (c == Object[].class) return OBJARY; 674 else if (c == Class.class) return CLS; 675 else if (c == MethodHandle.class) return MH; 676 assert(VerifyAccess.isTypeVisible(c, Object.class)) : c.getName(); 677 678 if (c == lastClass) { 679 return lastInternalName; 680 } 681 lastClass = c; 682 return lastInternalName = c.getName().replace('.', '/'); 683 } 684 685 private static MemberName resolveFrom(String name, MethodType type, Class<?> holder) { 686 assert(!UNSAFE.shouldBeInitialized(holder)) : holder + "not initialized"; 687 MemberName member = new MemberName(holder, name, type, REF_invokeStatic); 688 MemberName resolvedMember = MemberName.getFactory().resolveOrNull(REF_invokeStatic, member, holder, LM_TRUSTED); 689 traceLambdaForm(name, type, holder, resolvedMember); 690 return resolvedMember; 691 } 692 693 private static MemberName lookupPregenerated(LambdaForm form, MethodType invokerType) { 694 if (form.customized != null) { 695 // No pre-generated version for customized LF 696 return null; 697 } 698 String name = form.kind.methodName; 699 switch (form.kind) { 700 case BOUND_REINVOKER: { 701 name = name + "_" + BoundMethodHandle.speciesDataFor(form).key(); 702 return resolveFrom(name, invokerType, DelegatingMethodHandle.Holder.class); 703 } 704 case DELEGATE: return resolveFrom(name, invokerType, DelegatingMethodHandle.Holder.class); 705 case ZERO: // fall-through 706 case IDENTITY: { 707 name = name + "_" + form.returnType().basicTypeChar(); 708 return resolveFrom(name, invokerType, LambdaForm.Holder.class); 709 } 710 case EXACT_INVOKER: // fall-through 711 case EXACT_LINKER: // fall-through 712 case LINK_TO_CALL_SITE: // fall-through 713 case LINK_TO_TARGET_METHOD: // fall-through 714 case GENERIC_INVOKER: // fall-through 715 case GENERIC_LINKER: return resolveFrom(name, invokerType, Invokers.Holder.class); 716 case GET_REFERENCE: // fall-through 717 case GET_BOOLEAN: // fall-through 718 case GET_BYTE: // fall-through 719 case GET_CHAR: // fall-through 720 case GET_SHORT: // fall-through 721 case GET_INT: // fall-through 722 case GET_LONG: // fall-through 723 case GET_FLOAT: // fall-through 724 case GET_DOUBLE: // fall-through 725 case PUT_REFERENCE: // fall-through 726 case PUT_BOOLEAN: // fall-through 727 case PUT_BYTE: // fall-through 728 case PUT_CHAR: // fall-through 729 case PUT_SHORT: // fall-through 730 case PUT_INT: // fall-through 731 case PUT_LONG: // fall-through 732 case PUT_FLOAT: // fall-through 733 case PUT_DOUBLE: // fall-through 734 case DIRECT_NEW_INVOKE_SPECIAL: // fall-through 735 case DIRECT_INVOKE_INTERFACE: // fall-through 736 case DIRECT_INVOKE_SPECIAL: // fall-through 737 case DIRECT_INVOKE_SPECIAL_IFC: // fall-through 738 case DIRECT_INVOKE_STATIC: // fall-through 739 case DIRECT_INVOKE_STATIC_INIT: // fall-through 740 case DIRECT_INVOKE_VIRTUAL: return resolveFrom(name, invokerType, DirectMethodHandle.Holder.class); 741 } 742 return null; 743 } 744 745 /** 746 * Generate customized bytecode for a given LambdaForm. 747 */ 748 static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) { 749 MemberName pregenerated = lookupPregenerated(form, invokerType); 750 if (pregenerated != null) return pregenerated; // pre-generated bytecode 751 752 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType); 753 return g.loadMethod(g.generateCustomizedCodeBytes()); 754 } 755 756 /** Generates code to check that actual receiver and LambdaForm matches */ 757 private boolean checkActualReceiver() { 758 // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0 759 mv.visitInsn(Opcodes.DUP); 760 mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]); 761 mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false); 762 return true; 763 } 764 765 static String className(String cn) { 766 assert checkClassName(cn): "Class not found: " + cn; 767 return cn; 768 } 769 770 static boolean checkClassName(String cn) { 771 Type tp = Type.getType(cn); 772 // additional sanity so only valid "L;" descriptors work 773 if (tp.getSort() != Type.OBJECT) { 774 return false; 775 } 776 try { 777 Class<?> c = Class.forName(tp.getClassName(), false, null); 778 return true; 779 } catch (ClassNotFoundException e) { 780 return false; 781 } 782 } 783 784 static final String DONTINLINE_SIG = className("Ljdk/internal/vm/annotation/DontInline;"); 785 static final String FORCEINLINE_SIG = className("Ljdk/internal/vm/annotation/ForceInline;"); 786 static final String HIDDEN_SIG = className("Ljdk/internal/vm/annotation/Hidden;"); 787 static final String INJECTEDPROFILE_SIG = className("Ljava/lang/invoke/InjectedProfile;"); 788 static final String LF_COMPILED_SIG = className("Ljava/lang/invoke/LambdaForm$Compiled;"); 789 790 /** 791 * Generate an invoker method for the passed {@link LambdaForm}. 792 */ 793 private byte[] generateCustomizedCodeBytes() { 794 classFilePrologue(); 795 addMethod(); 796 clinit(cw, className, classData); 797 bogusMethod(lambdaForm); 798 799 final byte[] classFile = toByteArray(); 800 maybeDump(classFile); 801 return classFile; 802 } 803 804 void setClassWriter(ClassWriter cw) { 805 this.cw = cw; 806 } 807 808 void addMethod() { 809 methodPrologue(); 810 811 // Suppress this method in backtraces displayed to the user. 812 mv.visitAnnotation(HIDDEN_SIG, true); 813 814 // Mark this method as a compiled LambdaForm 815 mv.visitAnnotation(LF_COMPILED_SIG, true); 816 817 if (lambdaForm.forceInline) { 818 // Force inlining of this invoker method. 819 mv.visitAnnotation(FORCEINLINE_SIG, true); 820 } else { 821 mv.visitAnnotation(DONTINLINE_SIG, true); 822 } 823 824 classData(lambdaForm); // keep LambdaForm instance & its compiled form lifetime tightly coupled. 825 826 if (lambdaForm.customized != null) { 827 // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute 828 // receiver MethodHandle (at slot #0) with an embedded constant and use it instead. 829 // It enables more efficient code generation in some situations, since embedded constants 830 // are compile-time constants for JIT compiler. 831 mv.visitFieldInsn(Opcodes.GETSTATIC, className, classData(lambdaForm.customized), MH_SIG); 832 mv.visitTypeInsn(Opcodes.CHECKCAST, MH); 833 assert(checkActualReceiver()); // expects MethodHandle on top of the stack 834 mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]); 835 } 836 837 // iterate over the form's names, generating bytecode instructions for each 838 // start iterating at the first name following the arguments 839 Name onStack = null; 840 for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) { 841 Name name = lambdaForm.names[i]; 842 843 emitStoreResult(onStack); 844 onStack = name; // unless otherwise modified below 845 MethodHandleImpl.Intrinsic intr = name.function.intrinsicName(); 846 switch (intr) { 847 case SELECT_ALTERNATIVE: 848 assert lambdaForm.isSelectAlternative(i); 849 if (PROFILE_GWT) { 850 assert(name.arguments[0] instanceof Name && 851 ((Name)name.arguments[0]).refersTo(MethodHandleImpl.class, "profileBoolean")); 852 mv.visitAnnotation(INJECTEDPROFILE_SIG, true); 853 } 854 onStack = emitSelectAlternative(name, lambdaForm.names[i+1]); 855 i++; // skip MH.invokeBasic of the selectAlternative result 856 continue; 857 case GUARD_WITH_CATCH: 858 assert lambdaForm.isGuardWithCatch(i); 859 onStack = emitGuardWithCatch(i); 860 i += 2; // jump to the end of GWC idiom 861 continue; 862 case TRY_FINALLY: 863 assert lambdaForm.isTryFinally(i); 864 onStack = emitTryFinally(i); 865 i += 2; // jump to the end of the TF idiom 866 continue; 867 case TABLE_SWITCH: 868 assert lambdaForm.isTableSwitch(i); 869 int numCases = (Integer) name.function.intrinsicData(); 870 onStack = emitTableSwitch(i, numCases); 871 i += 2; // jump to the end of the TS idiom 872 continue; 873 case LOOP: 874 assert lambdaForm.isLoop(i); 875 onStack = emitLoop(i); 876 i += 2; // jump to the end of the LOOP idiom 877 continue; 878 case ARRAY_LOAD: 879 emitArrayLoad(name); 880 continue; 881 case ARRAY_STORE: 882 emitArrayStore(name); 883 continue; 884 case ARRAY_LENGTH: 885 emitArrayLength(name); 886 continue; 887 case IDENTITY: 888 assert(name.arguments.length == 1); 889 emitPushArguments(name, 0); 890 continue; 891 case ZERO: 892 assert(name.arguments.length == 0); 893 emitConst(name.type.basicTypeWrapper().zero()); 894 continue; 895 case NONE: 896 // no intrinsic associated 897 break; 898 default: 899 throw newInternalError("Unknown intrinsic: "+intr); 900 } 901 902 MemberName member = name.function.member(); 903 if (isStaticallyInvocable(member)) { 904 emitStaticInvoke(member, name); 905 } else { 906 emitInvoke(name); 907 } 908 } 909 910 // return statement 911 emitReturn(onStack); 912 913 methodEpilogue(); 914 } 915 916 /* 917 * @throws BytecodeGenerationException if something goes wrong when 918 * generating the byte code 919 */ 920 private byte[] toByteArray() { 921 try { 922 return cw.toByteArray(); 923 } catch (RuntimeException e) { 924 throw new BytecodeGenerationException(e); 925 } 926 } 927 928 /** 929 * The BytecodeGenerationException. 930 */ 931 @SuppressWarnings("serial") 932 static final class BytecodeGenerationException extends RuntimeException { 933 BytecodeGenerationException(Exception cause) { 934 super(cause); 935 } 936 } 937 938 void emitArrayLoad(Name name) { emitArrayOp(name, Opcodes.AALOAD); } 939 void emitArrayStore(Name name) { emitArrayOp(name, Opcodes.AASTORE); } 940 void emitArrayLength(Name name) { emitArrayOp(name, Opcodes.ARRAYLENGTH); } 941 942 void emitArrayOp(Name name, int arrayOpcode) { 943 assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH; 944 Class<?> elementType = name.function.methodType().parameterType(0).getComponentType(); 945 assert elementType != null; 946 emitPushArguments(name, 0); 947 if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) { 948 Wrapper w = Wrapper.forPrimitiveType(elementType); 949 arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode); 950 } 951 mv.visitInsn(arrayOpcode); 952 } 953 954 /** 955 * Emit an invoke for the given name. 956 */ 957 void emitInvoke(Name name) { 958 assert(!name.isLinkerMethodInvoke()); // should use the static path for these 959 if (true) { 960 // push receiver 961 MethodHandle target = name.function.resolvedHandle(); 962 assert(target != null) : name.exprString(); 963 mv.visitFieldInsn(Opcodes.GETSTATIC, className, classData(target), MH_SIG); 964 emitReferenceCast(MethodHandle.class, target); 965 } else { 966 // load receiver 967 emitAloadInsn(0); 968 emitReferenceCast(MethodHandle.class, null); 969 mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG); 970 mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG); 971 // TODO more to come 972 } 973 974 // push arguments 975 emitPushArguments(name, 0); 976 977 // invocation 978 MethodType type = name.function.methodType(); 979 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); 980 } 981 982 private static final Class<?>[] STATICALLY_INVOCABLE_PACKAGES = { 983 // Sample classes from each package we are willing to bind to statically: 984 java.lang.Object.class, 985 java.util.Arrays.class, 986 jdk.internal.misc.Unsafe.class 987 //MethodHandle.class already covered 988 }; 989 990 static boolean isStaticallyInvocable(NamedFunction ... functions) { 991 for (NamedFunction nf : functions) { 992 if (!isStaticallyInvocable(nf.member())) { 993 return false; 994 } 995 } 996 return true; 997 } 998 999 static boolean isStaticallyInvocable(Name name) { 1000 return isStaticallyInvocable(name.function.member()); 1001 } 1002 1003 static boolean isStaticallyInvocable(MemberName member) { 1004 if (member == null) return false; 1005 if (member.isConstructor()) return false; 1006 Class<?> cls = member.getDeclaringClass(); 1007 // Fast-path non-private members declared by MethodHandles, which is a common 1008 // case 1009 if (MethodHandle.class.isAssignableFrom(cls) && !member.isPrivate()) { 1010 assert(isStaticallyInvocableType(member.getMethodOrFieldType())); 1011 return true; 1012 } 1013 if (cls.isArray() || cls.isPrimitive()) 1014 return false; // FIXME 1015 if (cls.isAnonymousClass() || cls.isLocalClass()) 1016 return false; // inner class of some sort 1017 if (cls.getClassLoader() != MethodHandle.class.getClassLoader()) 1018 return false; // not on BCP 1019 if (cls.isHidden()) 1020 return false; 1021 if (!isStaticallyInvocableType(member.getMethodOrFieldType())) 1022 return false; 1023 if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls)) 1024 return true; // in java.lang.invoke package 1025 if (member.isPublic() && isStaticallyNameable(cls)) 1026 return true; 1027 return false; 1028 } 1029 1030 private static boolean isStaticallyInvocableType(MethodType mtype) { 1031 if (!isStaticallyNameable(mtype.returnType())) 1032 return false; 1033 for (Class<?> ptype : mtype.parameterArray()) 1034 if (!isStaticallyNameable(ptype)) 1035 return false; 1036 return true; 1037 } 1038 1039 static boolean isStaticallyNameable(Class<?> cls) { 1040 if (cls == Object.class) 1041 return true; 1042 if (MethodHandle.class.isAssignableFrom(cls)) { 1043 assert(!cls.isHidden()); 1044 return true; 1045 } 1046 while (cls.isArray()) 1047 cls = cls.getComponentType(); 1048 if (cls.isPrimitive()) 1049 return true; // int[].class, for example 1050 if (cls.isHidden()) 1051 return false; 1052 // could use VerifyAccess.isClassAccessible but the following is a safe approximation 1053 if (cls.getClassLoader() != Object.class.getClassLoader()) 1054 return false; 1055 if (VerifyAccess.isSamePackage(MethodHandle.class, cls)) 1056 return true; 1057 if (!Modifier.isPublic(cls.getModifiers())) 1058 return false; 1059 for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) { 1060 if (VerifyAccess.isSamePackage(pkgcls, cls)) 1061 return true; 1062 } 1063 return false; 1064 } 1065 1066 void emitStaticInvoke(Name name) { 1067 emitStaticInvoke(name.function.member(), name); 1068 } 1069 1070 /** 1071 * Emit an invoke for the given name, using the MemberName directly. 1072 */ 1073 void emitStaticInvoke(MemberName member, Name name) { 1074 assert(member.equals(name.function.member())); 1075 Class<?> defc = member.getDeclaringClass(); 1076 String cname = getInternalName(defc); 1077 String mname = member.getName(); 1078 String mtype; 1079 byte refKind = member.getReferenceKind(); 1080 if (refKind == REF_invokeSpecial) { 1081 // in order to pass the verifier, we need to convert this to invokevirtual in all cases 1082 assert(member.canBeStaticallyBound()) : member; 1083 refKind = REF_invokeVirtual; 1084 } 1085 1086 assert(!(member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual)); 1087 1088 // push arguments 1089 emitPushArguments(name, 0); 1090 1091 // invocation 1092 if (member.isMethod()) { 1093 mtype = member.getMethodType().toMethodDescriptorString(); 1094 mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype, 1095 member.getDeclaringClass().isInterface()); 1096 } else { 1097 mtype = MethodType.toFieldDescriptorString(member.getFieldType()); 1098 mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype); 1099 } 1100 // Issue a type assertion for the result, so we can avoid casts later. 1101 if (name.type == L_TYPE) { 1102 Class<?> rtype = member.getInvocationType().returnType(); 1103 assert(!rtype.isPrimitive()); 1104 if (rtype != Object.class && !rtype.isInterface()) { 1105 assertStaticType(rtype, name); 1106 } 1107 } 1108 } 1109 1110 int refKindOpcode(byte refKind) { 1111 switch (refKind) { 1112 case REF_invokeVirtual: return Opcodes.INVOKEVIRTUAL; 1113 case REF_invokeStatic: return Opcodes.INVOKESTATIC; 1114 case REF_invokeSpecial: return Opcodes.INVOKESPECIAL; 1115 case REF_invokeInterface: return Opcodes.INVOKEINTERFACE; 1116 case REF_getField: return Opcodes.GETFIELD; 1117 case REF_putField: return Opcodes.PUTFIELD; 1118 case REF_getStatic: return Opcodes.GETSTATIC; 1119 case REF_putStatic: return Opcodes.PUTSTATIC; 1120 } 1121 throw new InternalError("refKind="+refKind); 1122 } 1123 1124 /** 1125 * Emit bytecode for the selectAlternative idiom. 1126 * 1127 * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest): 1128 * <blockquote><pre>{@code 1129 * Lambda(a0:L,a1:I)=>{ 1130 * t2:I=foo.test(a1:I); 1131 * t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int)); 1132 * t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I} 1133 * }</pre></blockquote> 1134 */ 1135 private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) { 1136 assert isStaticallyInvocable(invokeBasicName); 1137 1138 Name receiver = (Name) invokeBasicName.arguments[0]; 1139 1140 Label L_fallback = new Label(); 1141 Label L_done = new Label(); 1142 1143 // load test result 1144 emitPushArgument(selectAlternativeName, 0); 1145 1146 // if_icmpne L_fallback 1147 mv.visitJumpInsn(Opcodes.IFEQ, L_fallback); 1148 1149 // invoke selectAlternativeName.arguments[1] 1150 Class<?>[] preForkClasses = localClasses.clone(); 1151 emitPushArgument(selectAlternativeName, 1); // get 2nd argument of selectAlternative 1152 emitAstoreInsn(receiver.index()); // store the MH in the receiver slot 1153 emitStaticInvoke(invokeBasicName); 1154 1155 // goto L_done 1156 mv.visitJumpInsn(Opcodes.GOTO, L_done); 1157 1158 // L_fallback: 1159 mv.visitLabel(L_fallback); 1160 1161 // invoke selectAlternativeName.arguments[2] 1162 System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length); 1163 emitPushArgument(selectAlternativeName, 2); // get 3rd argument of selectAlternative 1164 emitAstoreInsn(receiver.index()); // store the MH in the receiver slot 1165 emitStaticInvoke(invokeBasicName); 1166 1167 // L_done: 1168 mv.visitLabel(L_done); 1169 // for now do not bother to merge typestate; just reset to the dominator state 1170 System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length); 1171 1172 return invokeBasicName; // return what's on stack 1173 } 1174 1175 /** 1176 * Emit bytecode for the guardWithCatch idiom. 1177 * 1178 * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch): 1179 * <blockquote><pre>{@code 1180 * guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{ 1181 * t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L); 1182 * t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L); 1183 * t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I} 1184 * }</pre></blockquote> 1185 * 1186 * It is compiled into bytecode equivalent of the following code: 1187 * <blockquote><pre>{@code 1188 * try { 1189 * return a1.invokeBasic(a6, a7); 1190 * } catch (Throwable e) { 1191 * if (!a2.isInstance(e)) throw e; 1192 * return a3.invokeBasic(ex, a6, a7); 1193 * }}</pre></blockquote> 1194 */ 1195 private Name emitGuardWithCatch(int pos) { 1196 Name args = lambdaForm.names[pos]; 1197 Name invoker = lambdaForm.names[pos+1]; 1198 Name result = lambdaForm.names[pos+2]; 1199 1200 Label L_startBlock = new Label(); 1201 Label L_endBlock = new Label(); 1202 Label L_handler = new Label(); 1203 Label L_done = new Label(); 1204 1205 Class<?> returnType = result.function.resolvedHandle().type().returnType(); 1206 MethodType type = args.function.resolvedHandle().type() 1207 .dropParameterTypes(0,1) 1208 .changeReturnType(returnType); 1209 1210 mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable"); 1211 1212 // Normal case 1213 mv.visitLabel(L_startBlock); 1214 // load target 1215 emitPushArgument(invoker, 0); 1216 emitPushArguments(args, 1); // skip 1st argument: method handle 1217 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); 1218 mv.visitLabel(L_endBlock); 1219 mv.visitJumpInsn(Opcodes.GOTO, L_done); 1220 1221 // Exceptional case 1222 mv.visitLabel(L_handler); 1223 1224 // Check exception's type 1225 mv.visitInsn(Opcodes.DUP); 1226 // load exception class 1227 emitPushArgument(invoker, 1); 1228 mv.visitInsn(Opcodes.SWAP); 1229 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false); 1230 Label L_rethrow = new Label(); 1231 mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow); 1232 1233 // Invoke catcher 1234 // load catcher 1235 emitPushArgument(invoker, 2); 1236 mv.visitInsn(Opcodes.SWAP); 1237 emitPushArguments(args, 1); // skip 1st argument: method handle 1238 MethodType catcherType = type.insertParameterTypes(0, Throwable.class); 1239 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false); 1240 mv.visitJumpInsn(Opcodes.GOTO, L_done); 1241 1242 mv.visitLabel(L_rethrow); 1243 mv.visitInsn(Opcodes.ATHROW); 1244 1245 mv.visitLabel(L_done); 1246 1247 return result; 1248 } 1249 1250 /** 1251 * Emit bytecode for the tryFinally idiom. 1252 * <p> 1253 * The pattern looks like (Cf. MethodHandleImpl.makeTryFinally): 1254 * <blockquote><pre>{@code 1255 * // a0: BMH 1256 * // a1: target, a2: cleanup 1257 * // a3: box, a4: unbox 1258 * // a5 (and following): arguments 1259 * tryFinally=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L)=>{ 1260 * t6:L=MethodHandle.invokeBasic(a3:L,a5:L); // box the arguments into an Object[] 1261 * t7:L=MethodHandleImpl.tryFinally(a1:L,a2:L,t6:L); // call the tryFinally executor 1262 * t8:L=MethodHandle.invokeBasic(a4:L,t7:L);t8:L} // unbox the result; return the result 1263 * }</pre></blockquote> 1264 * <p> 1265 * It is compiled into bytecode equivalent to the following code: 1266 * <blockquote><pre>{@code 1267 * Throwable t; 1268 * Object r; 1269 * try { 1270 * r = a1.invokeBasic(a5); 1271 * } catch (Throwable thrown) { 1272 * t = thrown; 1273 * throw t; 1274 * } finally { 1275 * r = a2.invokeBasic(t, r, a5); 1276 * } 1277 * return r; 1278 * }</pre></blockquote> 1279 * <p> 1280 * Specifically, the bytecode will have the following form (the stack effects are given for the beginnings of 1281 * blocks, and for the situations after executing the given instruction - the code will have a slightly different 1282 * shape if the return type is {@code void}): 1283 * <blockquote><pre>{@code 1284 * TRY: (--) 1285 * load target (-- target) 1286 * load args (-- args... target) 1287 * INVOKEVIRTUAL MethodHandle.invokeBasic (depends) 1288 * FINALLY_NORMAL: (-- r_2nd* r) 1289 * store returned value (--) 1290 * load cleanup (-- cleanup) 1291 * ACONST_NULL (-- t cleanup) 1292 * load returned value (-- r_2nd* r t cleanup) 1293 * load args (-- args... r_2nd* r t cleanup) 1294 * INVOKEVIRTUAL MethodHandle.invokeBasic (-- r_2nd* r) 1295 * GOTO DONE 1296 * CATCH: (-- t) 1297 * DUP (-- t t) 1298 * FINALLY_EXCEPTIONAL: (-- t t) 1299 * load cleanup (-- cleanup t t) 1300 * SWAP (-- t cleanup t) 1301 * load default for r (-- r_2nd* r t cleanup t) 1302 * load args (-- args... r_2nd* r t cleanup t) 1303 * INVOKEVIRTUAL MethodHandle.invokeBasic (-- r_2nd* r t) 1304 * POP/POP2* (-- t) 1305 * ATHROW 1306 * DONE: (-- r) 1307 * }</pre></blockquote> 1308 * * = depends on whether the return type takes up 2 stack slots. 1309 */ 1310 private Name emitTryFinally(int pos) { 1311 Name args = lambdaForm.names[pos]; 1312 Name invoker = lambdaForm.names[pos+1]; 1313 Name result = lambdaForm.names[pos+2]; 1314 1315 Label lFrom = new Label(); 1316 Label lTo = new Label(); 1317 Label lCatch = new Label(); 1318 Label lDone = new Label(); 1319 1320 Class<?> returnType = result.function.resolvedHandle().type().returnType(); 1321 BasicType basicReturnType = BasicType.basicType(returnType); 1322 boolean isNonVoid = returnType != void.class; 1323 1324 MethodType type = args.function.resolvedHandle().type() 1325 .dropParameterTypes(0,1) 1326 .changeReturnType(returnType); 1327 MethodType cleanupType = type.insertParameterTypes(0, Throwable.class); 1328 if (isNonVoid) { 1329 cleanupType = cleanupType.insertParameterTypes(1, returnType); 1330 } 1331 String cleanupDesc = cleanupType.basicType().toMethodDescriptorString(); 1332 1333 // exception handler table 1334 mv.visitTryCatchBlock(lFrom, lTo, lCatch, "java/lang/Throwable"); 1335 1336 // TRY: 1337 mv.visitLabel(lFrom); 1338 emitPushArgument(invoker, 0); // load target 1339 emitPushArguments(args, 1); // load args (skip 0: method handle) 1340 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); 1341 mv.visitLabel(lTo); 1342 1343 // FINALLY_NORMAL: 1344 int index = extendLocalsMap(new Class<?>[]{ returnType }); 1345 if (isNonVoid) { 1346 emitStoreInsn(basicReturnType, index); 1347 } 1348 emitPushArgument(invoker, 1); // load cleanup 1349 mv.visitInsn(Opcodes.ACONST_NULL); 1350 if (isNonVoid) { 1351 emitLoadInsn(basicReturnType, index); 1352 } 1353 emitPushArguments(args, 1); // load args (skip 0: method handle) 1354 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", cleanupDesc, false); 1355 mv.visitJumpInsn(Opcodes.GOTO, lDone); 1356 1357 // CATCH: 1358 mv.visitLabel(lCatch); 1359 mv.visitInsn(Opcodes.DUP); 1360 1361 // FINALLY_EXCEPTIONAL: 1362 emitPushArgument(invoker, 1); // load cleanup 1363 mv.visitInsn(Opcodes.SWAP); 1364 if (isNonVoid) { 1365 emitZero(BasicType.basicType(returnType)); // load default for result 1366 } 1367 emitPushArguments(args, 1); // load args (skip 0: method handle) 1368 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", cleanupDesc, false); 1369 if (isNonVoid) { 1370 emitPopInsn(basicReturnType); 1371 } 1372 mv.visitInsn(Opcodes.ATHROW); 1373 1374 // DONE: 1375 mv.visitLabel(lDone); 1376 1377 return result; 1378 } 1379 1380 private void emitPopInsn(BasicType type) { 1381 mv.visitInsn(popInsnOpcode(type)); 1382 } 1383 1384 private static int popInsnOpcode(BasicType type) { 1385 return switch (type) { 1386 case I_TYPE, F_TYPE, L_TYPE -> Opcodes.POP; 1387 case J_TYPE, D_TYPE -> Opcodes.POP2; 1388 default -> throw new InternalError("unknown type: " + type); 1389 }; 1390 } 1391 1392 private Name emitTableSwitch(int pos, int numCases) { 1393 Name args = lambdaForm.names[pos]; 1394 Name invoker = lambdaForm.names[pos + 1]; 1395 Name result = lambdaForm.names[pos + 2]; 1396 1397 Class<?> returnType = result.function.resolvedHandle().type().returnType(); 1398 MethodType caseType = args.function.resolvedHandle().type() 1399 .dropParameterTypes(0, 1) // drop collector 1400 .changeReturnType(returnType); 1401 String caseDescriptor = caseType.basicType().toMethodDescriptorString(); 1402 1403 emitPushArgument(invoker, 2); // push cases 1404 mv.visitFieldInsn(Opcodes.GETFIELD, "java/lang/invoke/MethodHandleImpl$CasesHolder", "cases", 1405 "[Ljava/lang/invoke/MethodHandle;"); 1406 int casesLocal = extendLocalsMap(new Class<?>[] { MethodHandle[].class }); 1407 emitStoreInsn(L_TYPE, casesLocal); 1408 1409 Label endLabel = new Label(); 1410 Label defaultLabel = new Label(); 1411 Label[] caseLabels = new Label[numCases]; 1412 for (int i = 0; i < caseLabels.length; i++) { 1413 caseLabels[i] = new Label(); 1414 } 1415 1416 emitPushArgument(invoker, 0); // push switch input 1417 mv.visitTableSwitchInsn(0, numCases - 1, defaultLabel, caseLabels); 1418 1419 mv.visitLabel(defaultLabel); 1420 emitPushArgument(invoker, 1); // push default handle 1421 emitPushArguments(args, 1); // again, skip collector 1422 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", caseDescriptor, false); 1423 mv.visitJumpInsn(Opcodes.GOTO, endLabel); 1424 1425 for (int i = 0; i < numCases; i++) { 1426 mv.visitLabel(caseLabels[i]); 1427 // Load the particular case: 1428 emitLoadInsn(L_TYPE, casesLocal); 1429 emitIconstInsn(i); 1430 mv.visitInsn(Opcodes.AALOAD); 1431 1432 // invoke it: 1433 emitPushArguments(args, 1); // again, skip collector 1434 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", caseDescriptor, false); 1435 1436 mv.visitJumpInsn(Opcodes.GOTO, endLabel); 1437 } 1438 1439 mv.visitLabel(endLabel); 1440 1441 return result; 1442 } 1443 1444 /** 1445 * Emit bytecode for the loop idiom. 1446 * <p> 1447 * The pattern looks like (Cf. MethodHandleImpl.loop): 1448 * <blockquote><pre>{@code 1449 * // a0: BMH 1450 * // a1: LoopClauses (containing an array of arrays: inits, steps, preds, finis) 1451 * // a2: box, a3: unbox 1452 * // a4 (and following): arguments 1453 * loop=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L)=>{ 1454 * t5:L=MethodHandle.invokeBasic(a2:L,a4:L); // box the arguments into an Object[] 1455 * t6:L=MethodHandleImpl.loop(bt:L,a1:L,t5:L); // call the loop executor (with supplied types in bt) 1456 * t7:L=MethodHandle.invokeBasic(a3:L,t6:L);t7:L} // unbox the result; return the result 1457 * }</pre></blockquote> 1458 * <p> 1459 * It is compiled into bytecode equivalent to the code seen in {@link MethodHandleImpl#loop(BasicType[], 1460 * MethodHandleImpl.LoopClauses, Object...)}, with the difference that no arrays 1461 * will be used for local state storage. Instead, the local state will be mapped to actual stack slots. 1462 * <p> 1463 * Bytecode generation applies an unrolling scheme to enable better bytecode generation regarding local state type 1464 * handling. The generated bytecode will have the following form ({@code void} types are ignored for convenience). 1465 * Assume there are {@code C} clauses in the loop. 1466 * <blockquote><pre>{@code 1467 * PREINIT: ALOAD_1 1468 * CHECKCAST LoopClauses 1469 * GETFIELD LoopClauses.clauses 1470 * ASTORE clauseDataIndex // place the clauses 2-dimensional array on the stack 1471 * INIT: (INIT_SEQ for clause 1) 1472 * ... 1473 * (INIT_SEQ for clause C) 1474 * LOOP: (LOOP_SEQ for clause 1) 1475 * ... 1476 * (LOOP_SEQ for clause C) 1477 * GOTO LOOP 1478 * DONE: ... 1479 * }</pre></blockquote> 1480 * <p> 1481 * The {@code INIT_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has 1482 * the following shape. Assume slot {@code vx} is used to hold the state for clause {@code x}. 1483 * <blockquote><pre>{@code 1484 * INIT_SEQ_x: ALOAD clauseDataIndex 1485 * ICONST_0 1486 * AALOAD // load the inits array 1487 * ICONST x 1488 * AALOAD // load the init handle for clause x 1489 * load args 1490 * INVOKEVIRTUAL MethodHandle.invokeBasic 1491 * store vx 1492 * }</pre></blockquote> 1493 * <p> 1494 * The {@code LOOP_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has 1495 * the following shape. Again, assume slot {@code vx} is used to hold the state for clause {@code x}. 1496 * <blockquote><pre>{@code 1497 * LOOP_SEQ_x: ALOAD clauseDataIndex 1498 * ICONST_1 1499 * AALOAD // load the steps array 1500 * ICONST x 1501 * AALOAD // load the step handle for clause x 1502 * load locals 1503 * load args 1504 * INVOKEVIRTUAL MethodHandle.invokeBasic 1505 * store vx 1506 * ALOAD clauseDataIndex 1507 * ICONST_2 1508 * AALOAD // load the preds array 1509 * ICONST x 1510 * AALOAD // load the pred handle for clause x 1511 * load locals 1512 * load args 1513 * INVOKEVIRTUAL MethodHandle.invokeBasic 1514 * IFNE LOOP_SEQ_x+1 // predicate returned false -> jump to next clause 1515 * ALOAD clauseDataIndex 1516 * ICONST_3 1517 * AALOAD // load the finis array 1518 * ICONST x 1519 * AALOAD // load the fini handle for clause x 1520 * load locals 1521 * load args 1522 * INVOKEVIRTUAL MethodHandle.invokeBasic 1523 * GOTO DONE // jump beyond end of clauses to return from loop 1524 * }</pre></blockquote> 1525 */ 1526 private Name emitLoop(int pos) { 1527 Name args = lambdaForm.names[pos]; 1528 Name invoker = lambdaForm.names[pos+1]; 1529 Name result = lambdaForm.names[pos+2]; 1530 1531 // extract clause and loop-local state types 1532 // find the type info in the loop invocation 1533 BasicType[] loopClauseTypes = (BasicType[]) invoker.arguments[0]; 1534 Class<?>[] loopLocalStateTypes = Stream.of(loopClauseTypes). 1535 filter(bt -> bt != BasicType.V_TYPE).map(BasicType::basicTypeClass).toArray(Class<?>[]::new); 1536 Class<?>[] localTypes = new Class<?>[loopLocalStateTypes.length + 1]; 1537 localTypes[0] = MethodHandleImpl.LoopClauses.class; 1538 System.arraycopy(loopLocalStateTypes, 0, localTypes, 1, loopLocalStateTypes.length); 1539 1540 final int clauseDataIndex = extendLocalsMap(localTypes); 1541 final int firstLoopStateIndex = clauseDataIndex + 1; 1542 1543 Class<?> returnType = result.function.resolvedHandle().type().returnType(); 1544 MethodType loopType = args.function.resolvedHandle().type() 1545 .dropParameterTypes(0,1) 1546 .changeReturnType(returnType); 1547 MethodType loopHandleType = loopType.insertParameterTypes(0, loopLocalStateTypes); 1548 MethodType predType = loopHandleType.changeReturnType(boolean.class); 1549 MethodType finiType = loopHandleType; 1550 1551 final int nClauses = loopClauseTypes.length; 1552 1553 // indices to invoker arguments to load method handle arrays 1554 final int inits = 1; 1555 final int steps = 2; 1556 final int preds = 3; 1557 final int finis = 4; 1558 1559 Label lLoop = new Label(); 1560 Label lDone = new Label(); 1561 Label lNext; 1562 1563 // PREINIT: 1564 emitPushArgument(MethodHandleImpl.LoopClauses.class, invoker.arguments[1]); 1565 mv.visitFieldInsn(Opcodes.GETFIELD, LOOP_CLAUSES, "clauses", MHARY2); 1566 emitAstoreInsn(clauseDataIndex); 1567 1568 // INIT: 1569 for (int c = 0, state = 0; c < nClauses; ++c) { 1570 MethodType cInitType = loopType.changeReturnType(loopClauseTypes[c].basicTypeClass()); 1571 emitLoopHandleInvoke(invoker, inits, c, args, false, cInitType, loopLocalStateTypes, clauseDataIndex, 1572 firstLoopStateIndex); 1573 if (cInitType.returnType() != void.class) { 1574 emitStoreInsn(BasicType.basicType(cInitType.returnType()), firstLoopStateIndex + state); 1575 ++state; 1576 } 1577 } 1578 1579 // LOOP: 1580 mv.visitLabel(lLoop); 1581 1582 for (int c = 0, state = 0; c < nClauses; ++c) { 1583 lNext = new Label(); 1584 1585 MethodType stepType = loopHandleType.changeReturnType(loopClauseTypes[c].basicTypeClass()); 1586 boolean isVoid = stepType.returnType() == void.class; 1587 1588 // invoke loop step 1589 emitLoopHandleInvoke(invoker, steps, c, args, true, stepType, loopLocalStateTypes, clauseDataIndex, 1590 firstLoopStateIndex); 1591 if (!isVoid) { 1592 emitStoreInsn(BasicType.basicType(stepType.returnType()), firstLoopStateIndex + state); 1593 ++state; 1594 } 1595 1596 // invoke loop predicate 1597 emitLoopHandleInvoke(invoker, preds, c, args, true, predType, loopLocalStateTypes, clauseDataIndex, 1598 firstLoopStateIndex); 1599 mv.visitJumpInsn(Opcodes.IFNE, lNext); 1600 1601 // invoke fini 1602 emitLoopHandleInvoke(invoker, finis, c, args, true, finiType, loopLocalStateTypes, clauseDataIndex, 1603 firstLoopStateIndex); 1604 mv.visitJumpInsn(Opcodes.GOTO, lDone); 1605 1606 // this is the beginning of the next loop clause 1607 mv.visitLabel(lNext); 1608 } 1609 1610 mv.visitJumpInsn(Opcodes.GOTO, lLoop); 1611 1612 // DONE: 1613 mv.visitLabel(lDone); 1614 1615 return result; 1616 } 1617 1618 private int extendLocalsMap(Class<?>[] types) { 1619 int firstSlot = localsMap.length - 1; 1620 localsMap = Arrays.copyOf(localsMap, localsMap.length + types.length); 1621 localClasses = Arrays.copyOf(localClasses, localClasses.length + types.length); 1622 System.arraycopy(types, 0, localClasses, firstSlot, types.length); 1623 int index = localsMap[firstSlot - 1] + 1; 1624 int lastSlots = 0; 1625 for (int i = 0; i < types.length; ++i) { 1626 localsMap[firstSlot + i] = index; 1627 lastSlots = BasicType.basicType(localClasses[firstSlot + i]).basicTypeSlots(); 1628 index += lastSlots; 1629 } 1630 localsMap[localsMap.length - 1] = index - lastSlots; 1631 return firstSlot; 1632 } 1633 1634 private void emitLoopHandleInvoke(Name holder, int handles, int clause, Name args, boolean pushLocalState, 1635 MethodType type, Class<?>[] loopLocalStateTypes, int clauseDataSlot, 1636 int firstLoopStateSlot) { 1637 // load handle for clause 1638 emitPushClauseArray(clauseDataSlot, handles); 1639 emitIconstInsn(clause); 1640 mv.visitInsn(Opcodes.AALOAD); 1641 // load loop state (preceding the other arguments) 1642 if (pushLocalState) { 1643 for (int s = 0; s < loopLocalStateTypes.length; ++s) { 1644 emitLoadInsn(BasicType.basicType(loopLocalStateTypes[s]), firstLoopStateSlot + s); 1645 } 1646 } 1647 // load loop args (skip 0: method handle) 1648 emitPushArguments(args, 1); 1649 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.toMethodDescriptorString(), false); 1650 } 1651 1652 private void emitPushClauseArray(int clauseDataSlot, int which) { 1653 emitAloadInsn(clauseDataSlot); 1654 emitIconstInsn(which - 1); 1655 mv.visitInsn(Opcodes.AALOAD); 1656 } 1657 1658 private void emitZero(BasicType type) { 1659 mv.visitInsn(switch (type) { 1660 case I_TYPE -> Opcodes.ICONST_0; 1661 case J_TYPE -> Opcodes.LCONST_0; 1662 case F_TYPE -> Opcodes.FCONST_0; 1663 case D_TYPE -> Opcodes.DCONST_0; 1664 case L_TYPE -> Opcodes.ACONST_NULL; 1665 default -> throw new InternalError("unknown type: " + type); 1666 }); 1667 } 1668 1669 private void emitPushArguments(Name args, int start) { 1670 MethodType type = args.function.methodType(); 1671 for (int i = start; i < args.arguments.length; i++) { 1672 emitPushArgument(type.parameterType(i), args.arguments[i]); 1673 } 1674 } 1675 1676 private void emitPushArgument(Name name, int paramIndex) { 1677 Object arg = name.arguments[paramIndex]; 1678 Class<?> ptype = name.function.methodType().parameterType(paramIndex); 1679 emitPushArgument(ptype, arg); 1680 } 1681 1682 private void emitPushArgument(Class<?> ptype, Object arg) { 1683 BasicType bptype = basicType(ptype); 1684 if (arg instanceof Name n) { 1685 emitLoadInsn(n.type, n.index()); 1686 emitImplicitConversion(n.type, ptype, n); 1687 } else if (arg == null && bptype == L_TYPE) { 1688 mv.visitInsn(Opcodes.ACONST_NULL); 1689 } else if (arg instanceof String && bptype == L_TYPE) { 1690 mv.visitLdcInsn(arg); 1691 } else { 1692 if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) { 1693 emitConst(arg); 1694 } else { 1695 mv.visitFieldInsn(Opcodes.GETSTATIC, className, classData(arg), "Ljava/lang/Object;"); 1696 emitImplicitConversion(L_TYPE, ptype, arg); 1697 } 1698 } 1699 } 1700 1701 /** 1702 * Store the name to its local, if necessary. 1703 */ 1704 private void emitStoreResult(Name name) { 1705 if (name != null && name.type != V_TYPE) { 1706 // non-void: actually assign 1707 emitStoreInsn(name.type, name.index()); 1708 } 1709 } 1710 1711 /** 1712 * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type. 1713 */ 1714 private void emitReturn(Name onStack) { 1715 // return statement 1716 Class<?> rclass = invokerType.returnType(); 1717 BasicType rtype = lambdaForm.returnType(); 1718 assert(rtype == basicType(rclass)); // must agree 1719 if (rtype == V_TYPE) { 1720 // void 1721 mv.visitInsn(Opcodes.RETURN); 1722 // it doesn't matter what rclass is; the JVM will discard any value 1723 } else { 1724 LambdaForm.Name rn = lambdaForm.names[lambdaForm.result]; 1725 1726 // put return value on the stack if it is not already there 1727 if (rn != onStack) { 1728 emitLoadInsn(rtype, lambdaForm.result); 1729 } 1730 1731 emitImplicitConversion(rtype, rclass, rn); 1732 1733 // generate actual return statement 1734 emitReturnInsn(rtype); 1735 } 1736 } 1737 1738 /** 1739 * Emit a type conversion bytecode casting from "from" to "to". 1740 */ 1741 private void emitPrimCast(Wrapper from, Wrapper to) { 1742 // Here's how. 1743 // - indicates forbidden 1744 // <-> indicates implicit 1745 // to ----> boolean byte short char int long float double 1746 // from boolean <-> - - - - - - - 1747 // byte - <-> i2s i2c <-> i2l i2f i2d 1748 // short - i2b <-> i2c <-> i2l i2f i2d 1749 // char - i2b i2s <-> <-> i2l i2f i2d 1750 // int - i2b i2s i2c <-> i2l i2f i2d 1751 // long - l2i,i2b l2i,i2s l2i,i2c l2i <-> l2f l2d 1752 // float - f2i,i2b f2i,i2s f2i,i2c f2i f2l <-> f2d 1753 // double - d2i,i2b d2i,i2s d2i,i2c d2i d2l d2f <-> 1754 if (from == to) { 1755 // no cast required, should be dead code anyway 1756 return; 1757 } 1758 if (from.isSubwordOrInt()) { 1759 // cast from {byte,short,char,int} to anything 1760 emitI2X(to); 1761 } else { 1762 // cast from {long,float,double} to anything 1763 if (to.isSubwordOrInt()) { 1764 // cast to {byte,short,char,int} 1765 emitX2I(from); 1766 if (to.bitWidth() < 32) { 1767 // targets other than int require another conversion 1768 emitI2X(to); 1769 } 1770 } else { 1771 // cast to {long,float,double} - this is verbose 1772 boolean error = false; 1773 switch (from) { 1774 case LONG -> { 1775 switch (to) { 1776 case FLOAT -> mv.visitInsn(Opcodes.L2F); 1777 case DOUBLE -> mv.visitInsn(Opcodes.L2D); 1778 default -> error = true; 1779 } 1780 } 1781 case FLOAT -> { 1782 switch (to) { 1783 case LONG -> mv.visitInsn(Opcodes.F2L); 1784 case DOUBLE -> mv.visitInsn(Opcodes.F2D); 1785 default -> error = true; 1786 } 1787 } 1788 case DOUBLE -> { 1789 switch (to) { 1790 case LONG -> mv.visitInsn(Opcodes.D2L); 1791 case FLOAT -> mv.visitInsn(Opcodes.D2F); 1792 default -> error = true; 1793 } 1794 } 1795 default -> error = true; 1796 } 1797 if (error) { 1798 throw new IllegalStateException("unhandled prim cast: " + from + "2" + to); 1799 } 1800 } 1801 } 1802 } 1803 1804 private void emitI2X(Wrapper type) { 1805 switch (type) { 1806 case BYTE: mv.visitInsn(Opcodes.I2B); break; 1807 case SHORT: mv.visitInsn(Opcodes.I2S); break; 1808 case CHAR: mv.visitInsn(Opcodes.I2C); break; 1809 case INT: /* naught */ break; 1810 case LONG: mv.visitInsn(Opcodes.I2L); break; 1811 case FLOAT: mv.visitInsn(Opcodes.I2F); break; 1812 case DOUBLE: mv.visitInsn(Opcodes.I2D); break; 1813 case BOOLEAN: 1814 // For compatibility with ValueConversions and explicitCastArguments: 1815 mv.visitInsn(Opcodes.ICONST_1); 1816 mv.visitInsn(Opcodes.IAND); 1817 break; 1818 default: throw new InternalError("unknown type: " + type); 1819 } 1820 } 1821 1822 private void emitX2I(Wrapper type) { 1823 switch (type) { 1824 case LONG -> mv.visitInsn(Opcodes.L2I); 1825 case FLOAT -> mv.visitInsn(Opcodes.F2I); 1826 case DOUBLE -> mv.visitInsn(Opcodes.D2I); 1827 default -> throw new InternalError("unknown type: " + type); 1828 } 1829 } 1830 1831 /** 1832 * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments. 1833 */ 1834 static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) { 1835 assert(isValidSignature(basicTypeSignature(mt))); 1836 String name = "interpret_"+basicTypeChar(mt.returnType()); 1837 MethodType type = mt; // includes leading argument 1838 type = type.changeParameterType(0, MethodHandle.class); 1839 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type); 1840 return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes()); 1841 } 1842 1843 private byte[] generateLambdaFormInterpreterEntryPointBytes() { 1844 classFilePrologue(); 1845 methodPrologue(); 1846 1847 // Suppress this method in backtraces displayed to the user. 1848 mv.visitAnnotation(HIDDEN_SIG, true); 1849 1850 // Don't inline the interpreter entry. 1851 mv.visitAnnotation(DONTINLINE_SIG, true); 1852 1853 // create parameter array 1854 emitIconstInsn(invokerType.parameterCount()); 1855 mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); 1856 1857 // fill parameter array 1858 for (int i = 0; i < invokerType.parameterCount(); i++) { 1859 Class<?> ptype = invokerType.parameterType(i); 1860 mv.visitInsn(Opcodes.DUP); 1861 emitIconstInsn(i); 1862 emitLoadInsn(basicType(ptype), i); 1863 // box if primitive type 1864 if (ptype.isPrimitive()) { 1865 emitBoxing(Wrapper.forPrimitiveType(ptype)); 1866 } 1867 mv.visitInsn(Opcodes.AASTORE); 1868 } 1869 // invoke 1870 emitAloadInsn(0); 1871 mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;"); 1872 mv.visitInsn(Opcodes.SWAP); // swap form and array; avoid local variable 1873 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false); 1874 1875 // maybe unbox 1876 Class<?> rtype = invokerType.returnType(); 1877 if (rtype.isPrimitive() && rtype != void.class) { 1878 emitUnboxing(Wrapper.forPrimitiveType(rtype)); 1879 } 1880 1881 // return statement 1882 emitReturnInsn(basicType(rtype)); 1883 1884 methodEpilogue(); 1885 clinit(cw, className, classData); 1886 bogusMethod(invokerType); 1887 1888 final byte[] classFile = cw.toByteArray(); 1889 maybeDump(classFile); 1890 return classFile; 1891 } 1892 1893 /** 1894 * Generate bytecode for a NamedFunction invoker. 1895 */ 1896 static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) { 1897 MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE; 1898 String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType())); 1899 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType); 1900 return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm)); 1901 } 1902 1903 private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) { 1904 MethodType dstType = typeForm.erasedType(); 1905 classFilePrologue(); 1906 methodPrologue(); 1907 1908 // Suppress this method in backtraces displayed to the user. 1909 mv.visitAnnotation(HIDDEN_SIG, true); 1910 1911 // Force inlining of this invoker method. 1912 mv.visitAnnotation(FORCEINLINE_SIG, true); 1913 1914 // Load receiver 1915 emitAloadInsn(0); 1916 1917 // Load arguments from array 1918 for (int i = 0; i < dstType.parameterCount(); i++) { 1919 emitAloadInsn(1); 1920 emitIconstInsn(i); 1921 mv.visitInsn(Opcodes.AALOAD); 1922 1923 // Maybe unbox 1924 Class<?> dptype = dstType.parameterType(i); 1925 if (dptype.isPrimitive()) { 1926 Wrapper dstWrapper = Wrapper.forBasicType(dptype); 1927 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper; // narrow subword from int 1928 emitUnboxing(srcWrapper); 1929 emitPrimCast(srcWrapper, dstWrapper); 1930 } 1931 } 1932 1933 // Invoke 1934 String targetDesc = dstType.basicType().toMethodDescriptorString(); 1935 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false); 1936 1937 // Box primitive types 1938 Class<?> rtype = dstType.returnType(); 1939 if (rtype != void.class && rtype.isPrimitive()) { 1940 Wrapper srcWrapper = Wrapper.forBasicType(rtype); 1941 Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper; // widen subword to int 1942 // boolean casts not allowed 1943 emitPrimCast(srcWrapper, dstWrapper); 1944 emitBoxing(dstWrapper); 1945 } 1946 1947 // If the return type is void we return a null reference. 1948 if (rtype == void.class) { 1949 mv.visitInsn(Opcodes.ACONST_NULL); 1950 } 1951 emitReturnInsn(L_TYPE); // NOTE: NamedFunction invokers always return a reference value. 1952 1953 methodEpilogue(); 1954 clinit(cw, className, classData); 1955 bogusMethod(dstType); 1956 1957 final byte[] classFile = cw.toByteArray(); 1958 maybeDump(classFile); 1959 return classFile; 1960 } 1961 1962 /** 1963 * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool 1964 * for debugging purposes. 1965 */ 1966 private void bogusMethod(Object os) { 1967 if (DUMP_CLASS_FILES) { 1968 mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null); 1969 mv.visitLdcInsn(os.toString()); 1970 mv.visitInsn(Opcodes.POP); 1971 mv.visitInsn(Opcodes.RETURN); 1972 mv.visitMaxs(0, 0); 1973 mv.visitEnd(); 1974 } 1975 } 1976 }