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 java.lang.invoke.LambdaForm.Name; 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 sun.invoke.util.VerifyType; 42 43 /** 44 * Code generation backend for LambdaForm. 45 * <p> 46 * @author John Rose, JSR 292 EG 47 */ 48 class InvokerBytecodeGenerator { 49 /** Define class names for convenience. */ 50 private static final String MH = "java/lang/invoke/MethodHandle"; 51 private static final String MHI = "java/lang/invoke/MethodHandleImpl"; 52 private static final String LF = "java/lang/invoke/LambdaForm"; 53 private static final String LFN = "java/lang/invoke/LambdaForm$Name"; 54 private static final String CLS = "java/lang/Class"; 55 private static final String OBJ = "java/lang/Object"; 56 private static final String OBJARY = "[Ljava/lang/Object;"; 57 58 private static final String LF_SIG = "L" + LF + ";"; 59 private static final String LFN_SIG = "L" + LFN + ";"; 60 private static final String LL_SIG = "(L" + OBJ + ";)L" + OBJ + ";"; 61 private static final String CLL_SIG = "(L" + CLS + ";L" + OBJ + ";)L" + OBJ + ";"; 62 63 /** Name of its super class*/ 64 private static final String superName = LF; 65 66 /** Name of new class */ 67 private final String className; 68 69 /** Name of the source file (for stack trace printing). */ 70 private final String sourceFile; 71 72 private final LambdaForm lambdaForm; 73 private final String invokerName; 74 private final MethodType invokerType; 75 private final int[] localsMap; 76 77 /** ASM bytecode generation. */ 78 private ClassWriter cw; 79 private MethodVisitor mv; 80 81 private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory(); 82 private static final Class<?> HOST_CLASS = LambdaForm.class; 83 84 private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize, 85 String className, String invokerName, MethodType invokerType) { 86 if (invokerName.contains(".")) { 87 int p = invokerName.indexOf("."); 88 className = invokerName.substring(0, p); 89 invokerName = invokerName.substring(p+1); 90 } 91 if (DUMP_CLASS_FILES) { 92 className = makeDumpableClassName(className); 93 } 94 this.className = superName + "$" + className; 95 this.sourceFile = "LambdaForm$" + className; 96 this.lambdaForm = lambdaForm; 97 this.invokerName = invokerName; 98 this.invokerType = invokerType; 99 this.localsMap = new int[localsMapSize]; 100 } 101 102 private InvokerBytecodeGenerator(String className, String invokerName, MethodType invokerType) { 103 this(null, invokerType.parameterCount(), 104 className, invokerName, invokerType); 105 // Create an array to map name indexes to locals indexes. 106 for (int i = 0; i < localsMap.length; i++) { 107 localsMap[i] = invokerType.parameterSlotCount() - invokerType.parameterSlotDepth(i); 108 } 109 } 110 111 private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) { 112 this(form, form.names.length, 113 className, form.debugName, invokerType); 114 // Create an array to map name indexes to locals indexes. 115 Name[] names = form.names; 116 for (int i = 0, index = 0; i < localsMap.length; i++) { 117 localsMap[i] = index; 118 index += Wrapper.forBasicType(names[i].type).stackSlots(); 119 } 120 } 121 122 123 /** instance counters for dumped classes */ 124 private final static HashMap<String,Integer> DUMP_CLASS_FILES_COUNTERS; 125 /** debugging flag for saving generated class files */ 126 private final static File DUMP_CLASS_FILES_DIR; 127 128 static { 129 if (DUMP_CLASS_FILES) { 130 DUMP_CLASS_FILES_COUNTERS = new HashMap<>(); 131 try { 132 File dumpDir = new File("DUMP_CLASS_FILES"); 133 if (!dumpDir.exists()) { 134 dumpDir.mkdirs(); 135 } 136 DUMP_CLASS_FILES_DIR = dumpDir; 137 System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/..."); 138 } catch (Exception e) { 139 throw newInternalError(e); 140 } 141 } else { 142 DUMP_CLASS_FILES_COUNTERS = null; 143 DUMP_CLASS_FILES_DIR = null; 144 } 145 } 146 147 static void maybeDump(final String className, final byte[] classFile) { 148 if (DUMP_CLASS_FILES) { 149 System.out.println("dump: " + className); 150 java.security.AccessController.doPrivileged( 151 new java.security.PrivilegedAction<Void>() { 152 public Void run() { 153 try { 154 String dumpName = className; 155 //dumpName = dumpName.replace('/', '-'); 156 File dumpFile = new File(DUMP_CLASS_FILES_DIR, dumpName+".class"); 157 dumpFile.getParentFile().mkdirs(); 158 FileOutputStream file = new FileOutputStream(dumpFile); 159 file.write(classFile); 160 file.close(); 161 return null; 162 } catch (IOException ex) { 163 throw newInternalError(ex); 164 } 165 } 166 }); 167 } 168 169 } 170 171 private static String makeDumpableClassName(String className) { 172 Integer ctr; 173 synchronized (DUMP_CLASS_FILES_COUNTERS) { 174 ctr = DUMP_CLASS_FILES_COUNTERS.get(className); 175 if (ctr == null) ctr = 0; 176 DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1); 177 } 178 String sfx = ctr.toString(); 179 while (sfx.length() < 3) 180 sfx = "0"+sfx; 181 className += sfx; 182 return className; 183 } 184 185 class CpPatch { 186 final int index; 187 final String placeholder; 188 final Object value; 189 CpPatch(int index, String placeholder, Object value) { 190 this.index = index; 191 this.placeholder = placeholder; 192 this.value = value; 193 } 194 public String toString() { 195 return "CpPatch/index="+index+",placeholder="+placeholder+",value="+value; 196 } 197 } 198 199 Map<Object, CpPatch> cpPatches = new HashMap<>(); 200 201 int cph = 0; // for counting constant placeholders 202 203 String constantPlaceholder(Object arg) { 204 String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++; 205 if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + arg.toString() + ">>"; // debugging aid 206 if (cpPatches.containsKey(cpPlaceholder)) { 207 throw new InternalError("observed CP placeholder twice: " + cpPlaceholder); 208 } 209 // insert placeholder in CP and remember the patch 210 int index = cw.newConst((Object) cpPlaceholder); // TODO check if aready in the constant pool 211 cpPatches.put(cpPlaceholder, new CpPatch(index, cpPlaceholder, arg)); 212 return cpPlaceholder; 213 } 214 215 Object[] cpPatches(byte[] classFile) { 216 int size = getConstantPoolSize(classFile); 217 Object[] res = new Object[size]; 218 for (CpPatch p : cpPatches.values()) { 219 if (p.index >= size) 220 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20))); 221 res[p.index] = p.value; 222 } 223 return res; 224 } 225 226 /** 227 * Extract the number of constant pool entries from a given class file. 228 * 229 * @param classFile the bytes of the class file in question. 230 * @return the number of entries in the constant pool. 231 */ 232 private static int getConstantPoolSize(byte[] classFile) { 233 // The first few bytes: 234 // u4 magic; 235 // u2 minor_version; 236 // u2 major_version; 237 // u2 constant_pool_count; 238 return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF); 239 } 240 241 /** 242 * Extract the MemberName of a newly-defined method. 243 */ 244 private MemberName loadMethod(byte[] classFile) { 245 Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, cpPatches(classFile)); 246 return resolveInvokerMember(invokerClass, invokerName, invokerType); 247 } 248 249 /** 250 * Define a given class as anonymous class in the runtime system. 251 */ 252 private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, Object[] patches) { 253 Class<?> invokerClass = UNSAFE.defineAnonymousClass(HOST_CLASS, classBytes, patches); 254 UNSAFE.ensureClassInitialized(invokerClass); // Make sure the class is initialized; VM might complain. 255 return invokerClass; 256 } 257 258 private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) { 259 MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic); 260 //System.out.println("resolveInvokerMember => "+member); 261 //for (Method m : invokerClass.getDeclaredMethods()) System.out.println(" "+m); 262 try { 263 member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class); 264 } catch (ReflectiveOperationException e) { 265 throw newInternalError(e); 266 } 267 //System.out.println("resolveInvokerMember => "+member); 268 return member; 269 } 270 271 /** 272 * Set up class file generation. 273 */ 274 private void classFilePrologue() { 275 cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); 276 cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, className, null, superName, null); 277 cw.visitSource(sourceFile, null); 278 279 String invokerDesc = invokerType.toMethodDescriptorString(); 280 mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null); 281 } 282 283 /** 284 * Tear down class file generation. 285 */ 286 private void classFileEpilogue() { 287 mv.visitMaxs(0, 0); 288 mv.visitEnd(); 289 } 290 291 /* 292 * Low-level emit helpers. 293 */ 294 private void emitConst(Object con) { 295 if (con == null) { 296 mv.visitInsn(Opcodes.ACONST_NULL); 297 return; 298 } 299 if (con instanceof Integer) { 300 emitIconstInsn((int) con); 301 return; 302 } 303 if (con instanceof Long) { 304 long x = (long) con; 305 if (x == (short) x) { 306 emitIconstInsn((int) x); 307 mv.visitInsn(Opcodes.I2L); 308 return; 309 } 310 } 311 if (con instanceof Float) { 312 float x = (float) con; 313 if (x == (short) x) { 314 emitIconstInsn((int) x); 315 mv.visitInsn(Opcodes.I2F); 316 return; 317 } 318 } 319 if (con instanceof Double) { 320 double x = (double) con; 321 if (x == (short) x) { 322 emitIconstInsn((int) x); 323 mv.visitInsn(Opcodes.I2D); 324 return; 325 } 326 } 327 if (con instanceof Boolean) { 328 emitIconstInsn((boolean) con ? 1 : 0); 329 return; 330 } 331 // fall through: 332 mv.visitLdcInsn(con); 333 } 334 335 private void emitIconstInsn(int i) { 336 int opcode; 337 switch (i) { 338 case 0: opcode = Opcodes.ICONST_0; break; 339 case 1: opcode = Opcodes.ICONST_1; break; 340 case 2: opcode = Opcodes.ICONST_2; break; 341 case 3: opcode = Opcodes.ICONST_3; break; 342 case 4: opcode = Opcodes.ICONST_4; break; 343 case 5: opcode = Opcodes.ICONST_5; break; 344 default: 345 if (i == (byte) i) { 346 mv.visitIntInsn(Opcodes.BIPUSH, i & 0xFF); 347 } else if (i == (short) i) { 348 mv.visitIntInsn(Opcodes.SIPUSH, (char) i); 349 } else { 350 mv.visitLdcInsn(i); 351 } 352 return; 353 } 354 mv.visitInsn(opcode); 355 } 356 357 /* 358 * NOTE: These load/store methods use the localsMap to find the correct index! 359 */ 360 private void emitLoadInsn(char type, int index) { 361 int opcode; 362 switch (type) { 363 case 'I': opcode = Opcodes.ILOAD; break; 364 case 'J': opcode = Opcodes.LLOAD; break; 365 case 'F': opcode = Opcodes.FLOAD; break; 366 case 'D': opcode = Opcodes.DLOAD; break; 367 case 'L': opcode = Opcodes.ALOAD; break; 368 default: 369 throw new InternalError("unknown type: " + type); 370 } 371 mv.visitVarInsn(opcode, localsMap[index]); 372 } 373 private void emitAloadInsn(int index) { 374 emitLoadInsn('L', index); 375 } 376 377 private void emitStoreInsn(char type, int index) { 378 int opcode; 379 switch (type) { 380 case 'I': opcode = Opcodes.ISTORE; break; 381 case 'J': opcode = Opcodes.LSTORE; break; 382 case 'F': opcode = Opcodes.FSTORE; break; 383 case 'D': opcode = Opcodes.DSTORE; break; 384 case 'L': opcode = Opcodes.ASTORE; break; 385 default: 386 throw new InternalError("unknown type: " + type); 387 } 388 mv.visitVarInsn(opcode, localsMap[index]); 389 } 390 private void emitAstoreInsn(int index) { 391 emitStoreInsn('L', index); 392 } 393 394 /** 395 * Emit a boxing call. 396 * 397 * @param type primitive type class to box. 398 */ 399 private void emitBoxing(Class<?> type) { 400 Wrapper wrapper = Wrapper.forPrimitiveType(type); 401 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 402 String name = "valueOf"; 403 String desc = "(" + wrapper.basicTypeChar() + ")L" + owner + ";"; 404 mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false); 405 } 406 407 /** 408 * Emit an unboxing call (plus preceding checkcast). 409 * 410 * @param type wrapper type class to unbox. 411 */ 412 private void emitUnboxing(Class<?> type) { 413 Wrapper wrapper = Wrapper.forWrapperType(type); 414 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 415 String name = wrapper.primitiveSimpleName() + "Value"; 416 String desc = "()" + wrapper.basicTypeChar(); 417 mv.visitTypeInsn(Opcodes.CHECKCAST, owner); 418 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false); 419 } 420 421 /** 422 * Emit an implicit conversion. 423 * 424 * @param ptype type of value present on stack 425 * @param pclass type of value required on stack 426 */ 427 private void emitImplicitConversion(char ptype, Class<?> pclass) { 428 switch (ptype) { 429 case 'L': 430 if (VerifyType.isNullConversion(Object.class, pclass)) 431 return; 432 if (isStaticallyNameable(pclass)) { 433 mv.visitTypeInsn(Opcodes.CHECKCAST, getInternalName(pclass)); 434 } else { 435 mv.visitLdcInsn(constantPlaceholder(pclass)); 436 mv.visitTypeInsn(Opcodes.CHECKCAST, CLS); 437 mv.visitInsn(Opcodes.SWAP); 438 mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "castReference", CLL_SIG, false); 439 if (pclass.isArray()) 440 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY); 441 } 442 return; 443 case 'I': 444 if (!VerifyType.isNullConversion(int.class, pclass)) 445 emitPrimCast(ptype, Wrapper.basicTypeChar(pclass)); 446 return; 447 case 'J': 448 assert(pclass == long.class); 449 return; 450 case 'F': 451 assert(pclass == float.class); 452 return; 453 case 'D': 454 assert(pclass == double.class); 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(Class<?> type) { 464 int opcode; 465 switch (Wrapper.basicTypeChar(type)) { 466 case 'I': opcode = Opcodes.IRETURN; break; 467 case 'J': opcode = Opcodes.LRETURN; break; 468 case 'F': opcode = Opcodes.FRETURN; break; 469 case 'D': opcode = Opcodes.DRETURN; break; 470 case 'L': opcode = Opcodes.ARETURN; break; 471 case 'V': 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') { 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 char ptype = name.function.parameterType(paramIndex); 868 MethodType mtype = name.function.methodType(); 869 if (arg instanceof Name) { 870 Name n = (Name) arg; 871 emitLoadInsn(n.type, n.index()); 872 emitImplicitConversion(n.type, mtype.parameterType(paramIndex)); 873 } else if ((arg == null || arg instanceof String) && ptype == 'L') { 874 emitConst(arg); 875 } else { 876 if (Wrapper.isWrapperType(arg.getClass()) && ptype != 'L') { 877 emitConst(arg); 878 } else { 879 mv.visitLdcInsn(constantPlaceholder(arg)); 880 emitImplicitConversion('L', mtype.parameterType(paramIndex)); 881 } 882 } 883 } 884 885 /** 886 * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type. 887 */ 888 private void emitReturn() { 889 // return statement 890 if (lambdaForm.result == -1) { 891 // void 892 mv.visitInsn(Opcodes.RETURN); 893 } else { 894 LambdaForm.Name rn = lambdaForm.names[lambdaForm.result]; 895 char rtype = Wrapper.basicTypeChar(invokerType.returnType()); 896 897 // put return value on the stack if it is not already there 898 if (lambdaForm.result != lambdaForm.names.length - 1) { 899 emitLoadInsn(rn.type, lambdaForm.result); 900 } 901 902 // potentially generate cast 903 // rtype is the return type of the invoker - generated code must conform to this 904 // rn.type is the type of the result Name in the LF 905 if (rtype != rn.type) { 906 // need cast 907 if (rtype == 'L') { 908 // possibly cast the primitive to the correct type for boxing 909 char boxedType = Wrapper.forWrapperType(invokerType.returnType()).basicTypeChar(); 910 if (boxedType != rn.type) { 911 emitPrimCast(rn.type, boxedType); 912 } 913 // cast primitive to reference ("boxing") 914 emitBoxing(invokerType.returnType()); 915 } else { 916 // to-primitive cast 917 if (rn.type != 'L') { 918 // prim-to-prim cast 919 emitPrimCast(rn.type, rtype); 920 } else { 921 // ref-to-prim cast ("unboxing") 922 throw new InternalError("no ref-to-prim (unboxing) casts supported right now"); 923 } 924 } 925 } 926 927 // generate actual return statement 928 emitReturnInsn(invokerType.returnType()); 929 } 930 } 931 932 /** 933 * Emit a type conversion bytecode casting from "from" to "to". 934 */ 935 private void emitPrimCast(char from, char to) { 936 // Here's how. 937 // - indicates forbidden 938 // <-> indicates implicit 939 // to ----> boolean byte short char int long float double 940 // from boolean <-> - - - - - - - 941 // byte - <-> i2s i2c <-> i2l i2f i2d 942 // short - i2b <-> i2c <-> i2l i2f i2d 943 // char - i2b i2s <-> <-> i2l i2f i2d 944 // int - i2b i2s i2c <-> i2l i2f i2d 945 // long - l2i,i2b l2i,i2s l2i,i2c l2i <-> l2f l2d 946 // float - f2i,i2b f2i,i2s f2i,i2c f2i f2l <-> f2d 947 // double - d2i,i2b d2i,i2s d2i,i2c d2i d2l d2f <-> 948 if (from == to) { 949 // no cast required, should be dead code anyway 950 return; 951 } 952 Wrapper wfrom = Wrapper.forBasicType(from); 953 Wrapper wto = Wrapper.forBasicType(to); 954 if (wfrom.isSubwordOrInt()) { 955 // cast from {byte,short,char,int} to anything 956 emitI2X(to); 957 } else { 958 // cast from {long,float,double} to anything 959 if (wto.isSubwordOrInt()) { 960 // cast to {byte,short,char,int} 961 emitX2I(from); 962 if (wto.bitWidth() < 32) { 963 // targets other than int require another conversion 964 emitI2X(to); 965 } 966 } else { 967 // cast to {long,float,double} - this is verbose 968 boolean error = false; 969 switch (from) { 970 case 'J': 971 if (to == 'F') { mv.visitInsn(Opcodes.L2F); } 972 else if (to == 'D') { mv.visitInsn(Opcodes.L2D); } 973 else error = true; 974 break; 975 case 'F': 976 if (to == 'J') { mv.visitInsn(Opcodes.F2L); } 977 else if (to == 'D') { mv.visitInsn(Opcodes.F2D); } 978 else error = true; 979 break; 980 case 'D': 981 if (to == 'J') { mv.visitInsn(Opcodes.D2L); } 982 else if (to == 'F') { mv.visitInsn(Opcodes.D2F); } 983 else error = true; 984 break; 985 default: 986 error = true; 987 break; 988 } 989 if (error) { 990 throw new IllegalStateException("unhandled prim cast: " + from + "2" + to); 991 } 992 } 993 } 994 } 995 996 private void emitI2X(char type) { 997 switch (type) { 998 case 'B': mv.visitInsn(Opcodes.I2B); break; 999 case 'S': mv.visitInsn(Opcodes.I2S); break; 1000 case 'C': mv.visitInsn(Opcodes.I2C); break; 1001 case 'I': /* naught */ break; 1002 case 'J': mv.visitInsn(Opcodes.I2L); break; 1003 case 'F': mv.visitInsn(Opcodes.I2F); break; 1004 case 'D': mv.visitInsn(Opcodes.I2D); break; 1005 case 'Z': 1006 // For compatibility with ValueConversions and explicitCastArguments: 1007 mv.visitInsn(Opcodes.ICONST_1); 1008 mv.visitInsn(Opcodes.IAND); 1009 break; 1010 default: throw new InternalError("unknown type: " + type); 1011 } 1012 } 1013 1014 private void emitX2I(char type) { 1015 switch (type) { 1016 case 'J': mv.visitInsn(Opcodes.L2I); break; 1017 case 'F': mv.visitInsn(Opcodes.F2I); break; 1018 case 'D': mv.visitInsn(Opcodes.D2I); break; 1019 default: throw new InternalError("unknown type: " + type); 1020 } 1021 } 1022 1023 private static String basicTypeCharSignature(String prefix, MethodType type) { 1024 StringBuilder buf = new StringBuilder(prefix); 1025 for (Class<?> ptype : type.parameterList()) 1026 buf.append(Wrapper.forBasicType(ptype).basicTypeChar()); 1027 buf.append('_').append(Wrapper.forBasicType(type.returnType()).basicTypeChar()); 1028 return buf.toString(); 1029 } 1030 1031 /** 1032 * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments. 1033 */ 1034 static MemberName generateLambdaFormInterpreterEntryPoint(String sig) { 1035 assert(LambdaForm.isValidSignature(sig)); 1036 //System.out.println("generateExactInvoker "+sig); 1037 // compute method type 1038 // first parameter and return type 1039 char tret = LambdaForm.signatureReturn(sig); 1040 MethodType type = MethodType.methodType(LambdaForm.typeClass(tret), MethodHandle.class); 1041 // other parameter types 1042 int arity = LambdaForm.signatureArity(sig); 1043 for (int i = 1; i < arity; i++) { 1044 type = type.appendParameterTypes(LambdaForm.typeClass(sig.charAt(i))); 1045 } 1046 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", "interpret_"+tret, type); 1047 return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes()); 1048 } 1049 1050 private byte[] generateLambdaFormInterpreterEntryPointBytes() { 1051 classFilePrologue(); 1052 1053 // Suppress this method in backtraces displayed to the user. 1054 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 1055 1056 // Don't inline the interpreter entry. 1057 mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true); 1058 1059 // create parameter array 1060 emitIconstInsn(invokerType.parameterCount()); 1061 mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); 1062 1063 // fill parameter array 1064 for (int i = 0; i < invokerType.parameterCount(); i++) { 1065 Class<?> ptype = invokerType.parameterType(i); 1066 mv.visitInsn(Opcodes.DUP); 1067 emitIconstInsn(i); 1068 emitLoadInsn(Wrapper.basicTypeChar(ptype), i); 1069 // box if primitive type 1070 if (ptype.isPrimitive()) { 1071 emitBoxing(ptype); 1072 } 1073 mv.visitInsn(Opcodes.AASTORE); 1074 } 1075 // invoke 1076 emitAloadInsn(0); 1077 mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;"); 1078 mv.visitInsn(Opcodes.SWAP); // swap form and array; avoid local variable 1079 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false); 1080 1081 // maybe unbox 1082 Class<?> rtype = invokerType.returnType(); 1083 if (rtype.isPrimitive() && rtype != void.class) { 1084 emitUnboxing(Wrapper.asWrapperType(rtype)); 1085 } 1086 1087 // return statement 1088 emitReturnInsn(rtype); 1089 1090 classFileEpilogue(); 1091 bogusMethod(invokerType); 1092 1093 final byte[] classFile = cw.toByteArray(); 1094 maybeDump(className, classFile); 1095 return classFile; 1096 } 1097 1098 /** 1099 * Generate bytecode for a NamedFunction invoker. 1100 */ 1101 static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) { 1102 MethodType invokerType = LambdaForm.NamedFunction.INVOKER_METHOD_TYPE; 1103 String invokerName = basicTypeCharSignature("invoke_", typeForm.erasedType()); 1104 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType); 1105 return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm)); 1106 } 1107 1108 static int nfi = 0; 1109 1110 private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) { 1111 MethodType dstType = typeForm.erasedType(); 1112 classFilePrologue(); 1113 1114 // Suppress this method in backtraces displayed to the user. 1115 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 1116 1117 // Force inlining of this invoker method. 1118 mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true); 1119 1120 // Load receiver 1121 emitAloadInsn(0); 1122 1123 // Load arguments from array 1124 for (int i = 0; i < dstType.parameterCount(); i++) { 1125 emitAloadInsn(1); 1126 emitIconstInsn(i); 1127 mv.visitInsn(Opcodes.AALOAD); 1128 1129 // Maybe unbox 1130 Class<?> dptype = dstType.parameterType(i); 1131 if (dptype.isPrimitive()) { 1132 Class<?> sptype = dstType.basicType().wrap().parameterType(i); 1133 Wrapper dstWrapper = Wrapper.forBasicType(dptype); 1134 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper; // narrow subword from int 1135 emitUnboxing(srcWrapper.wrapperType()); 1136 emitPrimCast(srcWrapper.basicTypeChar(), dstWrapper.basicTypeChar()); 1137 } 1138 } 1139 1140 // Invoke 1141 String targetDesc = dstType.basicType().toMethodDescriptorString(); 1142 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false); 1143 1144 // Box primitive types 1145 Class<?> rtype = dstType.returnType(); 1146 if (rtype != void.class && rtype.isPrimitive()) { 1147 Wrapper srcWrapper = Wrapper.forBasicType(rtype); 1148 Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper; // widen subword to int 1149 // boolean casts not allowed 1150 emitPrimCast(srcWrapper.basicTypeChar(), dstWrapper.basicTypeChar()); 1151 emitBoxing(dstWrapper.primitiveType()); 1152 } 1153 1154 // If the return type is void we return a null reference. 1155 if (rtype == void.class) { 1156 mv.visitInsn(Opcodes.ACONST_NULL); 1157 } 1158 emitReturnInsn(Object.class); // NOTE: NamedFunction invokers always return a reference value. 1159 1160 classFileEpilogue(); 1161 bogusMethod(dstType); 1162 1163 final byte[] classFile = cw.toByteArray(); 1164 maybeDump(className, classFile); 1165 return classFile; 1166 } 1167 1168 /** 1169 * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool 1170 * for debugging purposes. 1171 */ 1172 private void bogusMethod(Object... os) { 1173 if (DUMP_CLASS_FILES) { 1174 mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null); 1175 for (Object o : os) { 1176 mv.visitLdcInsn(o.toString()); 1177 mv.visitInsn(Opcodes.POP); 1178 } 1179 mv.visitInsn(Opcodes.RETURN); 1180 mv.visitMaxs(0, 0); 1181 mv.visitEnd(); 1182 } 1183 } 1184 }