1 /* 2 * Copyright (c) 2012, 2015, 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 java.io.*; 29 import java.util.*; 30 import java.lang.reflect.Modifier; 31 32 import jdk.internal.org.objectweb.asm.*; 33 34 import static java.lang.invoke.LambdaForm.*; 35 import static java.lang.invoke.LambdaForm.BasicType.*; 36 import static java.lang.invoke.MethodHandleStatics.*; 37 import static java.lang.invoke.MethodHandleNatives.Constants.*; 38 39 import sun.invoke.util.VerifyAccess; 40 import sun.invoke.util.VerifyType; 41 import sun.invoke.util.Wrapper; 42 import sun.reflect.misc.ReflectUtil; 43 44 /** 45 * Code generation backend for LambdaForm. 46 * <p> 47 * @author John Rose, JSR 292 EG 48 */ 49 class InvokerBytecodeGenerator { 50 /** Define class names for convenience. */ 51 private static final String MH = "java/lang/invoke/MethodHandle"; 52 private static final String MHI = "java/lang/invoke/MethodHandleImpl"; 53 private static final String LF = "java/lang/invoke/LambdaForm"; 54 private static final String LFN = "java/lang/invoke/LambdaForm$Name"; 55 private static final String CLS = "java/lang/Class"; 56 private static final String OBJ = "java/lang/Object"; 57 private static final String OBJARY = "[Ljava/lang/Object;"; 58 59 private static final String LF_SIG = "L" + LF + ";"; 60 private static final String LFN_SIG = "L" + LFN + ";"; 61 private static final String LL_SIG = "(L" + OBJ + ";)L" + OBJ + ";"; 62 private static final String LLV_SIG = "(L" + OBJ + ";L" + OBJ + ";)V"; 63 64 /** Name of its super class*/ 65 private static final String superName = OBJ; 66 67 /** Name of new class */ 68 private final String className; 69 70 /** Name of the source file (for stack trace printing). */ 71 private final String sourceFile; 72 73 private final LambdaForm lambdaForm; 74 private final String invokerName; 75 private final MethodType invokerType; 76 77 /** Info about local variables in compiled lambda form */ 78 private final int[] localsMap; // index 79 private final Class<?>[] localClasses; // type 80 81 /** ASM bytecode generation. */ 82 private ClassWriter cw; 83 private MethodVisitor mv; 84 85 private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory(); 86 private static final Class<?> HOST_CLASS = LambdaForm.class; 87 88 /** Main constructor; other constructors delegate to this one. */ 89 private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize, 90 String className, String invokerName, MethodType invokerType) { 91 if (invokerName.contains(".")) { 92 int p = invokerName.indexOf('.'); 93 className = invokerName.substring(0, p); 94 invokerName = invokerName.substring(p+1); 95 } 96 if (DUMP_CLASS_FILES) { 97 className = makeDumpableClassName(className); 98 } 99 this.className = LF + "$" + className; 100 this.sourceFile = "LambdaForm$" + className; 101 this.lambdaForm = lambdaForm; 102 this.invokerName = invokerName; 103 this.invokerType = invokerType; 104 this.localsMap = new int[localsMapSize+1]; 105 // last entry of localsMap is count of allocated local slots 106 this.localClasses = new Class<?>[localsMapSize+1]; 107 } 108 109 /** For generating LambdaForm interpreter entry points. */ 110 private InvokerBytecodeGenerator(String className, String invokerName, MethodType invokerType) { 111 this(null, invokerType.parameterCount(), 112 className, invokerName, invokerType); 113 // Create an array to map name indexes to locals indexes. 114 for (int i = 0; i < localsMap.length; i++) { 115 localsMap[i] = invokerType.parameterSlotCount() - invokerType.parameterSlotDepth(i); 116 } 117 } 118 119 /** For generating customized code for a single LambdaForm. */ 120 private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) { 121 this(form, form.names.length, 122 className, form.debugName, invokerType); 123 // Create an array to map name indexes to locals indexes. 124 Name[] names = form.names; 125 for (int i = 0, index = 0; i < localsMap.length; i++) { 126 localsMap[i] = index; 127 if (i < names.length) { 128 BasicType type = names[i].type(); 129 index += type.basicTypeSlots(); 130 } 131 } 132 } 133 134 135 /** instance counters for dumped classes */ 136 private static final HashMap<String,Integer> DUMP_CLASS_FILES_COUNTERS; 137 /** debugging flag for saving generated class files */ 138 private static final File DUMP_CLASS_FILES_DIR; 139 140 static { 141 if (DUMP_CLASS_FILES) { 142 DUMP_CLASS_FILES_COUNTERS = new HashMap<>(); 143 try { 144 File dumpDir = new File("DUMP_CLASS_FILES"); 145 if (!dumpDir.exists()) { 146 dumpDir.mkdirs(); 147 } 148 DUMP_CLASS_FILES_DIR = dumpDir; 149 System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/..."); 150 } catch (Exception e) { 151 throw newInternalError(e); 152 } 153 } else { 154 DUMP_CLASS_FILES_COUNTERS = null; 155 DUMP_CLASS_FILES_DIR = null; 156 } 157 } 158 159 static void maybeDump(final String className, final byte[] classFile) { 160 if (DUMP_CLASS_FILES) { 161 java.security.AccessController.doPrivileged( 162 new java.security.PrivilegedAction<>() { 163 public Void run() { 164 try { 165 String dumpName = className; 166 //dumpName = dumpName.replace('/', '-'); 167 File dumpFile = new File(DUMP_CLASS_FILES_DIR, dumpName+".class"); 168 System.out.println("dump: " + dumpFile); 169 dumpFile.getParentFile().mkdirs(); 170 FileOutputStream file = new FileOutputStream(dumpFile); 171 file.write(classFile); 172 file.close(); 173 return null; 174 } catch (IOException ex) { 175 throw newInternalError(ex); 176 } 177 } 178 }); 179 } 180 181 } 182 183 private static String makeDumpableClassName(String className) { 184 Integer ctr; 185 synchronized (DUMP_CLASS_FILES_COUNTERS) { 186 ctr = DUMP_CLASS_FILES_COUNTERS.get(className); 187 if (ctr == null) ctr = 0; 188 DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1); 189 } 190 String sfx = ctr.toString(); 191 while (sfx.length() < 3) 192 sfx = "0"+sfx; 193 className += sfx; 194 return className; 195 } 196 197 class CpPatch { 198 final int index; 199 final String placeholder; 200 final Object value; 201 CpPatch(int index, String placeholder, Object value) { 202 this.index = index; 203 this.placeholder = placeholder; 204 this.value = value; 205 } 206 public String toString() { 207 return "CpPatch/index="+index+",placeholder="+placeholder+",value="+value; 208 } 209 } 210 211 Map<Object, CpPatch> cpPatches = new HashMap<>(); 212 213 int cph = 0; // for counting constant placeholders 214 215 String constantPlaceholder(Object arg) { 216 String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++; 217 if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + debugString(arg) + ">>"; // debugging aid 218 if (cpPatches.containsKey(cpPlaceholder)) { 219 throw new InternalError("observed CP placeholder twice: " + cpPlaceholder); 220 } 221 // insert placeholder in CP and remember the patch 222 int index = cw.newConst((Object) cpPlaceholder); // TODO check if already in the constant pool 223 cpPatches.put(cpPlaceholder, new CpPatch(index, cpPlaceholder, arg)); 224 return cpPlaceholder; 225 } 226 227 Object[] cpPatches(byte[] classFile) { 228 int size = getConstantPoolSize(classFile); 229 Object[] res = new Object[size]; 230 for (CpPatch p : cpPatches.values()) { 231 if (p.index >= size) 232 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20))); 233 res[p.index] = p.value; 234 } 235 return res; 236 } 237 238 private static String debugString(Object arg) { 239 if (arg instanceof MethodHandle) { 240 MethodHandle mh = (MethodHandle) arg; 241 MemberName member = mh.internalMemberName(); 242 if (member != null) 243 return member.toString(); 244 return mh.debugString(); 245 } 246 return arg.toString(); 247 } 248 249 /** 250 * Extract the number of constant pool entries from a given class file. 251 * 252 * @param classFile the bytes of the class file in question. 253 * @return the number of entries in the constant pool. 254 */ 255 private static int getConstantPoolSize(byte[] classFile) { 256 // The first few bytes: 257 // u4 magic; 258 // u2 minor_version; 259 // u2 major_version; 260 // u2 constant_pool_count; 261 return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF); 262 } 263 264 /** 265 * Extract the MemberName of a newly-defined method. 266 */ 267 private MemberName loadMethod(byte[] classFile) { 268 Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, cpPatches(classFile)); 269 return resolveInvokerMember(invokerClass, invokerName, invokerType); 270 } 271 272 /** 273 * Define a given class as anonymous class in the runtime system. 274 */ 275 private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, Object[] patches) { 276 Class<?> invokerClass = UNSAFE.defineAnonymousClass(HOST_CLASS, classBytes, patches); 277 UNSAFE.ensureClassInitialized(invokerClass); // Make sure the class is initialized; VM might complain. 278 return invokerClass; 279 } 280 281 private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) { 282 MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic); 283 //System.out.println("resolveInvokerMember => "+member); 284 //for (Method m : invokerClass.getDeclaredMethods()) System.out.println(" "+m); 285 try { 286 member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class); 287 } catch (ReflectiveOperationException e) { 288 throw newInternalError(e); 289 } 290 //System.out.println("resolveInvokerMember => "+member); 291 return member; 292 } 293 294 /** 295 * Set up class file generation. 296 */ 297 private void classFilePrologue() { 298 final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC 299 cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); 300 cw.visit(Opcodes.V1_8, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, className, null, superName, null); 301 cw.visitSource(sourceFile, null); 302 303 String invokerDesc = invokerType.toMethodDescriptorString(); 304 mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null); 305 } 306 307 /** 308 * Tear down class file generation. 309 */ 310 private void classFileEpilogue() { 311 mv.visitMaxs(0, 0); 312 mv.visitEnd(); 313 } 314 315 /* 316 * Low-level emit helpers. 317 */ 318 private void emitConst(Object con) { 319 if (con == null) { 320 mv.visitInsn(Opcodes.ACONST_NULL); 321 return; 322 } 323 if (con instanceof Integer) { 324 emitIconstInsn((int) con); 325 return; 326 } 327 if (con instanceof Byte) { 328 emitIconstInsn((byte)con); 329 return; 330 } 331 if (con instanceof Short) { 332 emitIconstInsn((short)con); 333 return; 334 } 335 if (con instanceof Character) { 336 emitIconstInsn((char)con); 337 return; 338 } 339 if (con instanceof Long) { 340 long x = (long) con; 341 short sx = (short)x; 342 if (x == sx) { 343 if (sx >= 0 && sx <= 1) { 344 mv.visitInsn(Opcodes.LCONST_0 + (int) sx); 345 } else { 346 emitIconstInsn((int) x); 347 mv.visitInsn(Opcodes.I2L); 348 } 349 return; 350 } 351 } 352 if (con instanceof Float) { 353 float x = (float) con; 354 short sx = (short)x; 355 if (x == sx) { 356 if (sx >= 0 && sx <= 2) { 357 mv.visitInsn(Opcodes.FCONST_0 + (int) sx); 358 } else { 359 emitIconstInsn((int) x); 360 mv.visitInsn(Opcodes.I2F); 361 } 362 return; 363 } 364 } 365 if (con instanceof Double) { 366 double x = (double) con; 367 short sx = (short)x; 368 if (x == sx) { 369 if (sx >= 0 && sx <= 1) { 370 mv.visitInsn(Opcodes.DCONST_0 + (int) sx); 371 } else { 372 emitIconstInsn((int) x); 373 mv.visitInsn(Opcodes.I2D); 374 } 375 return; 376 } 377 } 378 if (con instanceof Boolean) { 379 emitIconstInsn((boolean) con ? 1 : 0); 380 return; 381 } 382 // fall through: 383 mv.visitLdcInsn(con); 384 } 385 386 private void emitIconstInsn(final int cst) { 387 if (cst >= -1 && cst <= 5) { 388 mv.visitInsn(Opcodes.ICONST_0 + cst); 389 } else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) { 390 mv.visitIntInsn(Opcodes.BIPUSH, cst); 391 } else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) { 392 mv.visitIntInsn(Opcodes.SIPUSH, cst); 393 } else { 394 mv.visitLdcInsn(cst); 395 } 396 } 397 398 /* 399 * NOTE: These load/store methods use the localsMap to find the correct index! 400 */ 401 private void emitLoadInsn(BasicType type, int index) { 402 int opcode = loadInsnOpcode(type); 403 mv.visitVarInsn(opcode, localsMap[index]); 404 } 405 406 private int loadInsnOpcode(BasicType type) throws InternalError { 407 switch (type) { 408 case I_TYPE: return Opcodes.ILOAD; 409 case J_TYPE: return Opcodes.LLOAD; 410 case F_TYPE: return Opcodes.FLOAD; 411 case D_TYPE: return Opcodes.DLOAD; 412 case L_TYPE: return Opcodes.ALOAD; 413 default: 414 throw new InternalError("unknown type: " + type); 415 } 416 } 417 private void emitAloadInsn(int index) { 418 emitLoadInsn(L_TYPE, index); 419 } 420 421 private void emitStoreInsn(BasicType type, int index) { 422 int opcode = storeInsnOpcode(type); 423 mv.visitVarInsn(opcode, localsMap[index]); 424 } 425 426 private int storeInsnOpcode(BasicType type) throws InternalError { 427 switch (type) { 428 case I_TYPE: return Opcodes.ISTORE; 429 case J_TYPE: return Opcodes.LSTORE; 430 case F_TYPE: return Opcodes.FSTORE; 431 case D_TYPE: return Opcodes.DSTORE; 432 case L_TYPE: return Opcodes.ASTORE; 433 default: 434 throw new InternalError("unknown type: " + type); 435 } 436 } 437 private void emitAstoreInsn(int index) { 438 emitStoreInsn(L_TYPE, index); 439 } 440 441 private byte arrayTypeCode(Wrapper elementType) { 442 switch (elementType) { 443 case BOOLEAN: return Opcodes.T_BOOLEAN; 444 case BYTE: return Opcodes.T_BYTE; 445 case CHAR: return Opcodes.T_CHAR; 446 case SHORT: return Opcodes.T_SHORT; 447 case INT: return Opcodes.T_INT; 448 case LONG: return Opcodes.T_LONG; 449 case FLOAT: return Opcodes.T_FLOAT; 450 case DOUBLE: return Opcodes.T_DOUBLE; 451 case OBJECT: return 0; // in place of Opcodes.T_OBJECT 452 default: throw new InternalError(); 453 } 454 } 455 456 private int arrayInsnOpcode(byte tcode, int aaop) throws InternalError { 457 assert(aaop == Opcodes.AASTORE || aaop == Opcodes.AALOAD); 458 int xas; 459 switch (tcode) { 460 case Opcodes.T_BOOLEAN: xas = Opcodes.BASTORE; break; 461 case Opcodes.T_BYTE: xas = Opcodes.BASTORE; break; 462 case Opcodes.T_CHAR: xas = Opcodes.CASTORE; break; 463 case Opcodes.T_SHORT: xas = Opcodes.SASTORE; break; 464 case Opcodes.T_INT: xas = Opcodes.IASTORE; break; 465 case Opcodes.T_LONG: xas = Opcodes.LASTORE; break; 466 case Opcodes.T_FLOAT: xas = Opcodes.FASTORE; break; 467 case Opcodes.T_DOUBLE: xas = Opcodes.DASTORE; break; 468 case 0: xas = Opcodes.AASTORE; break; 469 default: throw new InternalError(); 470 } 471 return xas - Opcodes.AASTORE + aaop; 472 } 473 474 /** 475 * Emit a boxing call. 476 * 477 * @param wrapper primitive type class to box. 478 */ 479 private void emitBoxing(Wrapper wrapper) { 480 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 481 String name = "valueOf"; 482 String desc = "(" + wrapper.basicTypeChar() + ")L" + owner + ";"; 483 mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false); 484 } 485 486 /** 487 * Emit an unboxing call (plus preceding checkcast). 488 * 489 * @param wrapper wrapper type class to unbox. 490 */ 491 private void emitUnboxing(Wrapper wrapper) { 492 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 493 String name = wrapper.primitiveSimpleName() + "Value"; 494 String desc = "()" + wrapper.basicTypeChar(); 495 emitReferenceCast(wrapper.wrapperType(), null); 496 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false); 497 } 498 499 /** 500 * Emit an implicit conversion for an argument which must be of the given pclass. 501 * This is usually a no-op, except when pclass is a subword type or a reference other than Object or an interface. 502 * 503 * @param ptype type of value present on stack 504 * @param pclass type of value required on stack 505 * @param arg compile-time representation of value on stack (Node, constant) or null if none 506 */ 507 private void emitImplicitConversion(BasicType ptype, Class<?> pclass, Object arg) { 508 assert(basicType(pclass) == ptype); // boxing/unboxing handled by caller 509 if (pclass == ptype.basicTypeClass() && ptype != L_TYPE) 510 return; // nothing to do 511 switch (ptype) { 512 case L_TYPE: 513 if (VerifyType.isNullConversion(Object.class, pclass, false)) { 514 if (PROFILE_LEVEL > 0) 515 emitReferenceCast(Object.class, arg); 516 return; 517 } 518 emitReferenceCast(pclass, arg); 519 return; 520 case I_TYPE: 521 if (!VerifyType.isNullConversion(int.class, pclass, false)) 522 emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass)); 523 return; 524 } 525 throw newInternalError("bad implicit conversion: tc="+ptype+": "+pclass); 526 } 527 528 /** Update localClasses type map. Return true if the information is already present. */ 529 private boolean assertStaticType(Class<?> cls, Name n) { 530 int local = n.index(); 531 Class<?> aclass = localClasses[local]; 532 if (aclass != null && (aclass == cls || cls.isAssignableFrom(aclass))) { 533 return true; // type info is already present 534 } else if (aclass == null || aclass.isAssignableFrom(cls)) { 535 localClasses[local] = cls; // type info can be improved 536 } 537 return false; 538 } 539 540 private void emitReferenceCast(Class<?> cls, Object arg) { 541 Name writeBack = null; // local to write back result 542 if (arg instanceof Name) { 543 Name n = (Name) arg; 544 if (assertStaticType(cls, n)) 545 return; // this cast was already performed 546 if (lambdaForm.useCount(n) > 1) { 547 // This guy gets used more than once. 548 writeBack = n; 549 } 550 } 551 if (isStaticallyNameable(cls)) { 552 String sig = getInternalName(cls); 553 mv.visitTypeInsn(Opcodes.CHECKCAST, sig); 554 } else { 555 mv.visitLdcInsn(constantPlaceholder(cls)); 556 mv.visitTypeInsn(Opcodes.CHECKCAST, CLS); 557 mv.visitInsn(Opcodes.SWAP); 558 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLS, "cast", LL_SIG, false); 559 if (Object[].class.isAssignableFrom(cls)) 560 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY); 561 else if (PROFILE_LEVEL > 0) 562 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ); 563 } 564 if (writeBack != null) { 565 mv.visitInsn(Opcodes.DUP); 566 emitAstoreInsn(writeBack.index()); 567 } 568 } 569 570 /** 571 * Emits an actual return instruction conforming to the given return type. 572 */ 573 private void emitReturnInsn(BasicType type) { 574 int opcode; 575 switch (type) { 576 case I_TYPE: opcode = Opcodes.IRETURN; break; 577 case J_TYPE: opcode = Opcodes.LRETURN; break; 578 case F_TYPE: opcode = Opcodes.FRETURN; break; 579 case D_TYPE: opcode = Opcodes.DRETURN; break; 580 case L_TYPE: opcode = Opcodes.ARETURN; break; 581 case V_TYPE: opcode = Opcodes.RETURN; break; 582 default: 583 throw new InternalError("unknown return type: " + type); 584 } 585 mv.visitInsn(opcode); 586 } 587 588 private static String getInternalName(Class<?> c) { 589 if (c == Object.class) return OBJ; 590 else if (c == Object[].class) return OBJARY; 591 else if (c == Class.class) return CLS; 592 else if (c == MethodHandle.class) return MH; 593 assert(VerifyAccess.isTypeVisible(c, Object.class)) : c.getName(); 594 return c.getName().replace('.', '/'); 595 } 596 597 /** 598 * Generate customized bytecode for a given LambdaForm. 599 */ 600 static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) { 601 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType); 602 return g.loadMethod(g.generateCustomizedCodeBytes()); 603 } 604 605 /** Generates code to check that actual receiver and LambdaForm matches */ 606 private boolean checkActualReceiver() { 607 // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0 608 mv.visitInsn(Opcodes.DUP); 609 mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]); 610 mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false); 611 return true; 612 } 613 614 /** 615 * Generate an invoker method for the passed {@link LambdaForm}. 616 */ 617 private byte[] generateCustomizedCodeBytes() { 618 classFilePrologue(); 619 620 // Suppress this method in backtraces displayed to the user. 621 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 622 623 // Mark this method as a compiled LambdaForm 624 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Compiled;", true); 625 626 if (lambdaForm.forceInline) { 627 // Force inlining of this invoker method. 628 mv.visitAnnotation("Ljdk/internal/vm/annotation/ForceInline;", true); 629 } else { 630 mv.visitAnnotation("Ljdk/internal/vm/annotation/DontInline;", true); 631 } 632 633 if (lambdaForm.customized != null) { 634 // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute 635 // receiver MethodHandle (at slot #0) with an embedded constant and use it instead. 636 // It enables more efficient code generation in some situations, since embedded constants 637 // are compile-time constants for JIT compiler. 638 mv.visitLdcInsn(constantPlaceholder(lambdaForm.customized)); 639 mv.visitTypeInsn(Opcodes.CHECKCAST, MH); 640 assert(checkActualReceiver()); // expects MethodHandle on top of the stack 641 mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]); 642 } 643 644 // iterate over the form's names, generating bytecode instructions for each 645 // start iterating at the first name following the arguments 646 Name onStack = null; 647 for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) { 648 Name name = lambdaForm.names[i]; 649 650 emitStoreResult(onStack); 651 onStack = name; // unless otherwise modified below 652 MethodHandleImpl.Intrinsic intr = name.function.intrinsicName(); 653 switch (intr) { 654 case SELECT_ALTERNATIVE: 655 assert isSelectAlternative(i); 656 if (PROFILE_GWT) { 657 assert(name.arguments[0] instanceof Name && 658 nameRefersTo((Name)name.arguments[0], MethodHandleImpl.class, "profileBoolean")); 659 mv.visitAnnotation("Ljava/lang/invoke/InjectedProfile;", true); 660 } 661 onStack = emitSelectAlternative(name, lambdaForm.names[i+1]); 662 i++; // skip MH.invokeBasic of the selectAlternative result 663 continue; 664 case GUARD_WITH_CATCH: 665 assert isGuardWithCatch(i); 666 onStack = emitGuardWithCatch(i); 667 i = i+2; // Jump to the end of GWC idiom 668 continue; 669 case NEW_ARRAY: 670 Class<?> rtype = name.function.methodType().returnType(); 671 if (isStaticallyNameable(rtype)) { 672 emitNewArray(name); 673 continue; 674 } 675 break; 676 case ARRAY_LOAD: 677 emitArrayLoad(name); 678 continue; 679 case ARRAY_STORE: 680 emitArrayStore(name); 681 continue; 682 case IDENTITY: 683 assert(name.arguments.length == 1); 684 emitPushArguments(name); 685 continue; 686 case ZERO: 687 assert(name.arguments.length == 0); 688 emitConst(name.type.basicTypeWrapper().zero()); 689 continue; 690 case NONE: 691 // no intrinsic associated 692 break; 693 default: 694 throw newInternalError("Unknown intrinsic: "+intr); 695 } 696 697 MemberName member = name.function.member(); 698 if (isStaticallyInvocable(member)) { 699 emitStaticInvoke(member, name); 700 } else { 701 emitInvoke(name); 702 } 703 } 704 705 // return statement 706 emitReturn(onStack); 707 708 classFileEpilogue(); 709 bogusMethod(lambdaForm); 710 711 final byte[] classFile = cw.toByteArray(); 712 maybeDump(className, classFile); 713 return classFile; 714 } 715 716 void emitArrayLoad(Name name) { emitArrayOp(name, Opcodes.AALOAD); } 717 void emitArrayStore(Name name) { emitArrayOp(name, Opcodes.AASTORE); } 718 719 void emitArrayOp(Name name, int arrayOpcode) { 720 assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE; 721 Class<?> elementType = name.function.methodType().parameterType(0).getComponentType(); 722 assert elementType != null; 723 emitPushArguments(name); 724 if (elementType.isPrimitive()) { 725 Wrapper w = Wrapper.forPrimitiveType(elementType); 726 arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode); 727 } 728 mv.visitInsn(arrayOpcode); 729 } 730 731 /** 732 * Emit an invoke for the given name. 733 */ 734 void emitInvoke(Name name) { 735 assert(!isLinkerMethodInvoke(name)); // should use the static path for these 736 if (true) { 737 // push receiver 738 MethodHandle target = name.function.resolvedHandle(); 739 assert(target != null) : name.exprString(); 740 mv.visitLdcInsn(constantPlaceholder(target)); 741 emitReferenceCast(MethodHandle.class, target); 742 } else { 743 // load receiver 744 emitAloadInsn(0); 745 emitReferenceCast(MethodHandle.class, null); 746 mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG); 747 mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG); 748 // TODO more to come 749 } 750 751 // push arguments 752 emitPushArguments(name); 753 754 // invocation 755 MethodType type = name.function.methodType(); 756 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); 757 } 758 759 private static Class<?>[] STATICALLY_INVOCABLE_PACKAGES = { 760 // Sample classes from each package we are willing to bind to statically: 761 java.lang.Object.class, 762 java.util.Arrays.class, 763 jdk.internal.misc.Unsafe.class 764 //MethodHandle.class already covered 765 }; 766 767 static boolean isStaticallyInvocable(NamedFunction[] functions) { 768 for (NamedFunction nf : functions) { 769 if (!isStaticallyInvocable(nf.member())) { 770 return false; 771 } 772 } 773 return true; 774 } 775 776 static boolean isStaticallyInvocable(Name name) { 777 return isStaticallyInvocable(name.function.member()); 778 } 779 780 static boolean isStaticallyInvocable(MemberName member) { 781 if (member == null) return false; 782 if (member.isConstructor()) return false; 783 Class<?> cls = member.getDeclaringClass(); 784 if (cls.isArray() || cls.isPrimitive()) 785 return false; // FIXME 786 if (cls.isAnonymousClass() || cls.isLocalClass()) 787 return false; // inner class of some sort 788 if (cls.getClassLoader() != MethodHandle.class.getClassLoader()) 789 return false; // not on BCP 790 if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added 791 return false; 792 MethodType mtype = member.getMethodOrFieldType(); 793 if (!isStaticallyNameable(mtype.returnType())) 794 return false; 795 for (Class<?> ptype : mtype.parameterArray()) 796 if (!isStaticallyNameable(ptype)) 797 return false; 798 if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls)) 799 return true; // in java.lang.invoke package 800 if (member.isPublic() && isStaticallyNameable(cls)) 801 return true; 802 return false; 803 } 804 805 static boolean isStaticallyNameable(Class<?> cls) { 806 if (cls == Object.class) 807 return true; 808 while (cls.isArray()) 809 cls = cls.getComponentType(); 810 if (cls.isPrimitive()) 811 return true; // int[].class, for example 812 if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added 813 return false; 814 // could use VerifyAccess.isClassAccessible but the following is a safe approximation 815 if (cls.getClassLoader() != Object.class.getClassLoader()) 816 return false; 817 if (VerifyAccess.isSamePackage(MethodHandle.class, cls)) 818 return true; 819 if (!Modifier.isPublic(cls.getModifiers())) 820 return false; 821 for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) { 822 if (VerifyAccess.isSamePackage(pkgcls, cls)) 823 return true; 824 } 825 return false; 826 } 827 828 void emitStaticInvoke(Name name) { 829 emitStaticInvoke(name.function.member(), name); 830 } 831 832 /** 833 * Emit an invoke for the given name, using the MemberName directly. 834 */ 835 void emitStaticInvoke(MemberName member, Name name) { 836 assert(member.equals(name.function.member())); 837 Class<?> defc = member.getDeclaringClass(); 838 String cname = getInternalName(defc); 839 String mname = member.getName(); 840 String mtype; 841 byte refKind = member.getReferenceKind(); 842 if (refKind == REF_invokeSpecial) { 843 // in order to pass the verifier, we need to convert this to invokevirtual in all cases 844 assert(member.canBeStaticallyBound()) : member; 845 refKind = REF_invokeVirtual; 846 } 847 848 assert(!(member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual)); 849 850 // push arguments 851 emitPushArguments(name); 852 853 // invocation 854 if (member.isMethod()) { 855 mtype = member.getMethodType().toMethodDescriptorString(); 856 mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype, 857 member.getDeclaringClass().isInterface()); 858 } else { 859 mtype = MethodType.toFieldDescriptorString(member.getFieldType()); 860 mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype); 861 } 862 // Issue a type assertion for the result, so we can avoid casts later. 863 if (name.type == L_TYPE) { 864 Class<?> rtype = member.getInvocationType().returnType(); 865 assert(!rtype.isPrimitive()); 866 if (rtype != Object.class && !rtype.isInterface()) { 867 assertStaticType(rtype, name); 868 } 869 } 870 } 871 872 void emitNewArray(Name name) throws InternalError { 873 Class<?> rtype = name.function.methodType().returnType(); 874 if (name.arguments.length == 0) { 875 // The array will be a constant. 876 Object emptyArray; 877 try { 878 emptyArray = name.function.resolvedHandle().invoke(); 879 } catch (Throwable ex) { 880 throw newInternalError(ex); 881 } 882 assert(java.lang.reflect.Array.getLength(emptyArray) == 0); 883 assert(emptyArray.getClass() == rtype); // exact typing 884 mv.visitLdcInsn(constantPlaceholder(emptyArray)); 885 emitReferenceCast(rtype, emptyArray); 886 return; 887 } 888 Class<?> arrayElementType = rtype.getComponentType(); 889 assert(arrayElementType != null); 890 emitIconstInsn(name.arguments.length); 891 int xas = Opcodes.AASTORE; 892 if (!arrayElementType.isPrimitive()) { 893 mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType)); 894 } else { 895 byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType)); 896 xas = arrayInsnOpcode(tc, xas); 897 mv.visitIntInsn(Opcodes.NEWARRAY, tc); 898 } 899 // store arguments 900 for (int i = 0; i < name.arguments.length; i++) { 901 mv.visitInsn(Opcodes.DUP); 902 emitIconstInsn(i); 903 emitPushArgument(name, i); 904 mv.visitInsn(xas); 905 } 906 // the array is left on the stack 907 assertStaticType(rtype, name); 908 } 909 int refKindOpcode(byte refKind) { 910 switch (refKind) { 911 case REF_invokeVirtual: return Opcodes.INVOKEVIRTUAL; 912 case REF_invokeStatic: return Opcodes.INVOKESTATIC; 913 case REF_invokeSpecial: return Opcodes.INVOKESPECIAL; 914 case REF_invokeInterface: return Opcodes.INVOKEINTERFACE; 915 case REF_getField: return Opcodes.GETFIELD; 916 case REF_putField: return Opcodes.PUTFIELD; 917 case REF_getStatic: return Opcodes.GETSTATIC; 918 case REF_putStatic: return Opcodes.PUTSTATIC; 919 } 920 throw new InternalError("refKind="+refKind); 921 } 922 923 /** 924 * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}. 925 */ 926 private boolean memberRefersTo(MemberName member, Class<?> declaringClass, String name) { 927 return member != null && 928 member.getDeclaringClass() == declaringClass && 929 member.getName().equals(name); 930 } 931 private boolean nameRefersTo(Name name, Class<?> declaringClass, String methodName) { 932 return name.function != null && 933 memberRefersTo(name.function.member(), declaringClass, methodName); 934 } 935 936 /** 937 * Check if MemberName is a call to MethodHandle.invokeBasic. 938 */ 939 private boolean isInvokeBasic(Name name) { 940 if (name.function == null) 941 return false; 942 if (name.arguments.length < 1) 943 return false; // must have MH argument 944 MemberName member = name.function.member(); 945 return memberRefersTo(member, MethodHandle.class, "invokeBasic") && 946 !member.isPublic() && !member.isStatic(); 947 } 948 949 /** 950 * Check if MemberName is a call to MethodHandle.linkToStatic, etc. 951 */ 952 private boolean isLinkerMethodInvoke(Name name) { 953 if (name.function == null) 954 return false; 955 if (name.arguments.length < 1) 956 return false; // must have MH argument 957 MemberName member = name.function.member(); 958 return member != null && 959 member.getDeclaringClass() == MethodHandle.class && 960 !member.isPublic() && member.isStatic() && 961 member.getName().startsWith("linkTo"); 962 } 963 964 /** 965 * Check if i-th name is a call to MethodHandleImpl.selectAlternative. 966 */ 967 private boolean isSelectAlternative(int pos) { 968 // selectAlternative idiom: 969 // t_{n}:L=MethodHandleImpl.selectAlternative(...) 970 // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 971 if (pos+1 >= lambdaForm.names.length) return false; 972 Name name0 = lambdaForm.names[pos]; 973 Name name1 = lambdaForm.names[pos+1]; 974 return nameRefersTo(name0, MethodHandleImpl.class, "selectAlternative") && 975 isInvokeBasic(name1) && 976 name1.lastUseIndex(name0) == 0 && // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 977 lambdaForm.lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1} 978 } 979 980 /** 981 * Check if i-th name is a start of GuardWithCatch idiom. 982 */ 983 private boolean isGuardWithCatch(int pos) { 984 // GuardWithCatch idiom: 985 // t_{n}:L=MethodHandle.invokeBasic(...) 986 // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n}); 987 // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1}) 988 if (pos+2 >= lambdaForm.names.length) return false; 989 Name name0 = lambdaForm.names[pos]; 990 Name name1 = lambdaForm.names[pos+1]; 991 Name name2 = lambdaForm.names[pos+2]; 992 return nameRefersTo(name1, MethodHandleImpl.class, "guardWithCatch") && 993 isInvokeBasic(name0) && 994 isInvokeBasic(name2) && 995 name1.lastUseIndex(name0) == 3 && // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n}); 996 lambdaForm.lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1} 997 name2.lastUseIndex(name1) == 1 && // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1}) 998 lambdaForm.lastUseIndex(name1) == pos+2; // t_{n+1} is local: used only in t_{n+2} 999 } 1000 1001 /** 1002 * Emit bytecode for the selectAlternative idiom. 1003 * 1004 * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest): 1005 * <blockquote><pre>{@code 1006 * Lambda(a0:L,a1:I)=>{ 1007 * t2:I=foo.test(a1:I); 1008 * t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int)); 1009 * t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I} 1010 * }</pre></blockquote> 1011 */ 1012 private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) { 1013 assert isStaticallyInvocable(invokeBasicName); 1014 1015 Name receiver = (Name) invokeBasicName.arguments[0]; 1016 1017 Label L_fallback = new Label(); 1018 Label L_done = new Label(); 1019 1020 // load test result 1021 emitPushArgument(selectAlternativeName, 0); 1022 1023 // if_icmpne L_fallback 1024 mv.visitJumpInsn(Opcodes.IFEQ, L_fallback); 1025 1026 // invoke selectAlternativeName.arguments[1] 1027 Class<?>[] preForkClasses = localClasses.clone(); 1028 emitPushArgument(selectAlternativeName, 1); // get 2nd argument of selectAlternative 1029 emitAstoreInsn(receiver.index()); // store the MH in the receiver slot 1030 emitStaticInvoke(invokeBasicName); 1031 1032 // goto L_done 1033 mv.visitJumpInsn(Opcodes.GOTO, L_done); 1034 1035 // L_fallback: 1036 mv.visitLabel(L_fallback); 1037 1038 // invoke selectAlternativeName.arguments[2] 1039 System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length); 1040 emitPushArgument(selectAlternativeName, 2); // get 3rd argument of selectAlternative 1041 emitAstoreInsn(receiver.index()); // store the MH in the receiver slot 1042 emitStaticInvoke(invokeBasicName); 1043 1044 // L_done: 1045 mv.visitLabel(L_done); 1046 // for now do not bother to merge typestate; just reset to the dominator state 1047 System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length); 1048 1049 return invokeBasicName; // return what's on stack 1050 } 1051 1052 /** 1053 * Emit bytecode for the guardWithCatch idiom. 1054 * 1055 * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch): 1056 * <blockquote><pre>{@code 1057 * guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{ 1058 * t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L); 1059 * t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L); 1060 * t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I} 1061 * }</pre></blockquote> 1062 * 1063 * It is compiled into bytecode equivalent of the following code: 1064 * <blockquote><pre>{@code 1065 * try { 1066 * return a1.invokeBasic(a6, a7); 1067 * } catch (Throwable e) { 1068 * if (!a2.isInstance(e)) throw e; 1069 * return a3.invokeBasic(ex, a6, a7); 1070 * }} 1071 */ 1072 private Name emitGuardWithCatch(int pos) { 1073 Name args = lambdaForm.names[pos]; 1074 Name invoker = lambdaForm.names[pos+1]; 1075 Name result = lambdaForm.names[pos+2]; 1076 1077 Label L_startBlock = new Label(); 1078 Label L_endBlock = new Label(); 1079 Label L_handler = new Label(); 1080 Label L_done = new Label(); 1081 1082 Class<?> returnType = result.function.resolvedHandle().type().returnType(); 1083 MethodType type = args.function.resolvedHandle().type() 1084 .dropParameterTypes(0,1) 1085 .changeReturnType(returnType); 1086 1087 mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable"); 1088 1089 // Normal case 1090 mv.visitLabel(L_startBlock); 1091 // load target 1092 emitPushArgument(invoker, 0); 1093 emitPushArguments(args, 1); // skip 1st argument: method handle 1094 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); 1095 mv.visitLabel(L_endBlock); 1096 mv.visitJumpInsn(Opcodes.GOTO, L_done); 1097 1098 // Exceptional case 1099 mv.visitLabel(L_handler); 1100 1101 // Check exception's type 1102 mv.visitInsn(Opcodes.DUP); 1103 // load exception class 1104 emitPushArgument(invoker, 1); 1105 mv.visitInsn(Opcodes.SWAP); 1106 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false); 1107 Label L_rethrow = new Label(); 1108 mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow); 1109 1110 // Invoke catcher 1111 // load catcher 1112 emitPushArgument(invoker, 2); 1113 mv.visitInsn(Opcodes.SWAP); 1114 emitPushArguments(args, 1); // skip 1st argument: method handle 1115 MethodType catcherType = type.insertParameterTypes(0, Throwable.class); 1116 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false); 1117 mv.visitJumpInsn(Opcodes.GOTO, L_done); 1118 1119 mv.visitLabel(L_rethrow); 1120 mv.visitInsn(Opcodes.ATHROW); 1121 1122 mv.visitLabel(L_done); 1123 1124 return result; 1125 } 1126 1127 private void emitPushArguments(Name args) { 1128 emitPushArguments(args, 0); 1129 } 1130 1131 private void emitPushArguments(Name args, int start) { 1132 for (int i = start; i < args.arguments.length; i++) { 1133 emitPushArgument(args, i); 1134 } 1135 } 1136 1137 private void emitPushArgument(Name name, int paramIndex) { 1138 Object arg = name.arguments[paramIndex]; 1139 Class<?> ptype = name.function.methodType().parameterType(paramIndex); 1140 emitPushArgument(ptype, arg); 1141 } 1142 1143 private void emitPushArgument(Class<?> ptype, Object arg) { 1144 BasicType bptype = basicType(ptype); 1145 if (arg instanceof Name) { 1146 Name n = (Name) arg; 1147 emitLoadInsn(n.type, n.index()); 1148 emitImplicitConversion(n.type, ptype, n); 1149 } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) { 1150 emitConst(arg); 1151 } else { 1152 if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) { 1153 emitConst(arg); 1154 } else { 1155 mv.visitLdcInsn(constantPlaceholder(arg)); 1156 emitImplicitConversion(L_TYPE, ptype, arg); 1157 } 1158 } 1159 } 1160 1161 /** 1162 * Store the name to its local, if necessary. 1163 */ 1164 private void emitStoreResult(Name name) { 1165 if (name != null && name.type != V_TYPE) { 1166 // non-void: actually assign 1167 emitStoreInsn(name.type, name.index()); 1168 } 1169 } 1170 1171 /** 1172 * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type. 1173 */ 1174 private void emitReturn(Name onStack) { 1175 // return statement 1176 Class<?> rclass = invokerType.returnType(); 1177 BasicType rtype = lambdaForm.returnType(); 1178 assert(rtype == basicType(rclass)); // must agree 1179 if (rtype == V_TYPE) { 1180 // void 1181 mv.visitInsn(Opcodes.RETURN); 1182 // it doesn't matter what rclass is; the JVM will discard any value 1183 } else { 1184 LambdaForm.Name rn = lambdaForm.names[lambdaForm.result]; 1185 1186 // put return value on the stack if it is not already there 1187 if (rn != onStack) { 1188 emitLoadInsn(rtype, lambdaForm.result); 1189 } 1190 1191 emitImplicitConversion(rtype, rclass, rn); 1192 1193 // generate actual return statement 1194 emitReturnInsn(rtype); 1195 } 1196 } 1197 1198 /** 1199 * Emit a type conversion bytecode casting from "from" to "to". 1200 */ 1201 private void emitPrimCast(Wrapper from, Wrapper to) { 1202 // Here's how. 1203 // - indicates forbidden 1204 // <-> indicates implicit 1205 // to ----> boolean byte short char int long float double 1206 // from boolean <-> - - - - - - - 1207 // byte - <-> i2s i2c <-> i2l i2f i2d 1208 // short - i2b <-> i2c <-> i2l i2f i2d 1209 // char - i2b i2s <-> <-> i2l i2f i2d 1210 // int - i2b i2s i2c <-> i2l i2f i2d 1211 // long - l2i,i2b l2i,i2s l2i,i2c l2i <-> l2f l2d 1212 // float - f2i,i2b f2i,i2s f2i,i2c f2i f2l <-> f2d 1213 // double - d2i,i2b d2i,i2s d2i,i2c d2i d2l d2f <-> 1214 if (from == to) { 1215 // no cast required, should be dead code anyway 1216 return; 1217 } 1218 if (from.isSubwordOrInt()) { 1219 // cast from {byte,short,char,int} to anything 1220 emitI2X(to); 1221 } else { 1222 // cast from {long,float,double} to anything 1223 if (to.isSubwordOrInt()) { 1224 // cast to {byte,short,char,int} 1225 emitX2I(from); 1226 if (to.bitWidth() < 32) { 1227 // targets other than int require another conversion 1228 emitI2X(to); 1229 } 1230 } else { 1231 // cast to {long,float,double} - this is verbose 1232 boolean error = false; 1233 switch (from) { 1234 case LONG: 1235 switch (to) { 1236 case FLOAT: mv.visitInsn(Opcodes.L2F); break; 1237 case DOUBLE: mv.visitInsn(Opcodes.L2D); break; 1238 default: error = true; break; 1239 } 1240 break; 1241 case FLOAT: 1242 switch (to) { 1243 case LONG : mv.visitInsn(Opcodes.F2L); break; 1244 case DOUBLE: mv.visitInsn(Opcodes.F2D); break; 1245 default: error = true; break; 1246 } 1247 break; 1248 case DOUBLE: 1249 switch (to) { 1250 case LONG : mv.visitInsn(Opcodes.D2L); break; 1251 case FLOAT: mv.visitInsn(Opcodes.D2F); break; 1252 default: error = true; break; 1253 } 1254 break; 1255 default: 1256 error = true; 1257 break; 1258 } 1259 if (error) { 1260 throw new IllegalStateException("unhandled prim cast: " + from + "2" + to); 1261 } 1262 } 1263 } 1264 } 1265 1266 private void emitI2X(Wrapper type) { 1267 switch (type) { 1268 case BYTE: mv.visitInsn(Opcodes.I2B); break; 1269 case SHORT: mv.visitInsn(Opcodes.I2S); break; 1270 case CHAR: mv.visitInsn(Opcodes.I2C); break; 1271 case INT: /* naught */ break; 1272 case LONG: mv.visitInsn(Opcodes.I2L); break; 1273 case FLOAT: mv.visitInsn(Opcodes.I2F); break; 1274 case DOUBLE: mv.visitInsn(Opcodes.I2D); break; 1275 case BOOLEAN: 1276 // For compatibility with ValueConversions and explicitCastArguments: 1277 mv.visitInsn(Opcodes.ICONST_1); 1278 mv.visitInsn(Opcodes.IAND); 1279 break; 1280 default: throw new InternalError("unknown type: " + type); 1281 } 1282 } 1283 1284 private void emitX2I(Wrapper type) { 1285 switch (type) { 1286 case LONG: mv.visitInsn(Opcodes.L2I); break; 1287 case FLOAT: mv.visitInsn(Opcodes.F2I); break; 1288 case DOUBLE: mv.visitInsn(Opcodes.D2I); break; 1289 default: throw new InternalError("unknown type: " + type); 1290 } 1291 } 1292 1293 /** 1294 * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments. 1295 */ 1296 static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) { 1297 assert(isValidSignature(basicTypeSignature(mt))); 1298 String name = "interpret_"+basicTypeChar(mt.returnType()); 1299 MethodType type = mt; // includes leading argument 1300 type = type.changeParameterType(0, MethodHandle.class); 1301 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type); 1302 return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes()); 1303 } 1304 1305 private byte[] generateLambdaFormInterpreterEntryPointBytes() { 1306 classFilePrologue(); 1307 1308 // Suppress this method in backtraces displayed to the user. 1309 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 1310 1311 // Don't inline the interpreter entry. 1312 mv.visitAnnotation("Ljdk/internal/vm/annotation/DontInline;", true); 1313 1314 // create parameter array 1315 emitIconstInsn(invokerType.parameterCount()); 1316 mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); 1317 1318 // fill parameter array 1319 for (int i = 0; i < invokerType.parameterCount(); i++) { 1320 Class<?> ptype = invokerType.parameterType(i); 1321 mv.visitInsn(Opcodes.DUP); 1322 emitIconstInsn(i); 1323 emitLoadInsn(basicType(ptype), i); 1324 // box if primitive type 1325 if (ptype.isPrimitive()) { 1326 emitBoxing(Wrapper.forPrimitiveType(ptype)); 1327 } 1328 mv.visitInsn(Opcodes.AASTORE); 1329 } 1330 // invoke 1331 emitAloadInsn(0); 1332 mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;"); 1333 mv.visitInsn(Opcodes.SWAP); // swap form and array; avoid local variable 1334 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false); 1335 1336 // maybe unbox 1337 Class<?> rtype = invokerType.returnType(); 1338 if (rtype.isPrimitive() && rtype != void.class) { 1339 emitUnboxing(Wrapper.forPrimitiveType(rtype)); 1340 } 1341 1342 // return statement 1343 emitReturnInsn(basicType(rtype)); 1344 1345 classFileEpilogue(); 1346 bogusMethod(invokerType); 1347 1348 final byte[] classFile = cw.toByteArray(); 1349 maybeDump(className, classFile); 1350 return classFile; 1351 } 1352 1353 /** 1354 * Generate bytecode for a NamedFunction invoker. 1355 */ 1356 static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) { 1357 MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE; 1358 String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType())); 1359 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType); 1360 return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm)); 1361 } 1362 1363 private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) { 1364 MethodType dstType = typeForm.erasedType(); 1365 classFilePrologue(); 1366 1367 // Suppress this method in backtraces displayed to the user. 1368 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 1369 1370 // Force inlining of this invoker method. 1371 mv.visitAnnotation("Ljdk/internal/vm/annotation/ForceInline;", true); 1372 1373 // Load receiver 1374 emitAloadInsn(0); 1375 1376 // Load arguments from array 1377 for (int i = 0; i < dstType.parameterCount(); i++) { 1378 emitAloadInsn(1); 1379 emitIconstInsn(i); 1380 mv.visitInsn(Opcodes.AALOAD); 1381 1382 // Maybe unbox 1383 Class<?> dptype = dstType.parameterType(i); 1384 if (dptype.isPrimitive()) { 1385 Class<?> sptype = dstType.basicType().wrap().parameterType(i); 1386 Wrapper dstWrapper = Wrapper.forBasicType(dptype); 1387 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper; // narrow subword from int 1388 emitUnboxing(srcWrapper); 1389 emitPrimCast(srcWrapper, dstWrapper); 1390 } 1391 } 1392 1393 // Invoke 1394 String targetDesc = dstType.basicType().toMethodDescriptorString(); 1395 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false); 1396 1397 // Box primitive types 1398 Class<?> rtype = dstType.returnType(); 1399 if (rtype != void.class && rtype.isPrimitive()) { 1400 Wrapper srcWrapper = Wrapper.forBasicType(rtype); 1401 Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper; // widen subword to int 1402 // boolean casts not allowed 1403 emitPrimCast(srcWrapper, dstWrapper); 1404 emitBoxing(dstWrapper); 1405 } 1406 1407 // If the return type is void we return a null reference. 1408 if (rtype == void.class) { 1409 mv.visitInsn(Opcodes.ACONST_NULL); 1410 } 1411 emitReturnInsn(L_TYPE); // NOTE: NamedFunction invokers always return a reference value. 1412 1413 classFileEpilogue(); 1414 bogusMethod(dstType); 1415 1416 final byte[] classFile = cw.toByteArray(); 1417 maybeDump(className, classFile); 1418 return classFile; 1419 } 1420 1421 /** 1422 * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool 1423 * for debugging purposes. 1424 */ 1425 private void bogusMethod(Object... os) { 1426 if (DUMP_CLASS_FILES) { 1427 mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null); 1428 for (Object o : os) { 1429 mv.visitLdcInsn(o.toString()); 1430 mv.visitInsn(Opcodes.POP); 1431 } 1432 mv.visitInsn(Opcodes.RETURN); 1433 mv.visitMaxs(0, 0); 1434 mv.visitEnd(); 1435 } 1436 } 1437 }