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