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