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