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