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