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 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 += basicTypeWrapper(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(byte type, int index) { 361 int opcode = loadInsnOpcode(type); 362 mv.visitVarInsn(opcode, localsMap[index]); 363 } 364 365 private int loadInsnOpcode(byte type) throws InternalError { 366 int opcode; 367 switch (type) { 368 case I_TYPE: opcode = Opcodes.ILOAD; break; 369 case J_TYPE: opcode = Opcodes.LLOAD; break; 370 case F_TYPE: opcode = Opcodes.FLOAD; break; 371 case D_TYPE: opcode = Opcodes.DLOAD; break; 372 case L_TYPE: opcode = Opcodes.ALOAD; break; 373 default: 374 throw new InternalError("unknown type: " + type); 375 } 376 return opcode; 377 } 378 private void emitAloadInsn(int index) { 379 emitLoadInsn(L_TYPE, index); 380 } 381 382 private void emitStoreInsn(byte type, int index) { 383 int opcode = storeInsnOpcode(type); 384 mv.visitVarInsn(opcode, localsMap[index]); 385 } 386 387 private int storeInsnOpcode(byte type) throws InternalError { 388 int opcode; 389 switch (type) { 390 case I_TYPE: opcode = Opcodes.ISTORE; break; 391 case J_TYPE: opcode = Opcodes.LSTORE; break; 392 case F_TYPE: opcode = Opcodes.FSTORE; break; 393 case D_TYPE: opcode = Opcodes.DSTORE; break; 394 case L_TYPE: opcode = Opcodes.ASTORE; break; 395 default: 396 throw new InternalError("unknown type: " + type); 397 } 398 return opcode; 399 } 400 private void emitAstoreInsn(int index) { 401 emitStoreInsn(L_TYPE, index); 402 } 403 404 /** 405 * Emit a boxing call. 406 * 407 * @param wrapper primitive type class to box. 408 */ 409 private void emitBoxing(Wrapper wrapper) { 410 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 411 String name = "valueOf"; 412 String desc = "(" + wrapper.basicTypeChar() + ")L" + owner + ";"; 413 mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false); 414 } 415 416 /** 417 * Emit an unboxing call (plus preceding checkcast). 418 * 419 * @param wrapper wrapper type class to unbox. 420 */ 421 private void emitUnboxing(Wrapper wrapper) { 422 String owner = "java/lang/" + wrapper.wrapperType().getSimpleName(); 423 String name = wrapper.primitiveSimpleName() + "Value"; 424 String desc = "()" + wrapper.basicTypeChar(); 425 mv.visitTypeInsn(Opcodes.CHECKCAST, owner); 426 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false); 427 } 428 429 /** 430 * Emit an implicit conversion. 431 * 432 * @param ptype type of value present on stack 433 * @param pclass type of value required on stack 434 */ 435 private void emitImplicitConversion(byte ptype, Class<?> pclass) { 436 assert(basicType(pclass) == ptype); // boxing/unboxing handled by caller 437 if (pclass == basicTypeClass(ptype) && ptype != L_TYPE) 438 return; // nothing to do 439 switch (ptype) { 440 case L_TYPE: 441 if (VerifyType.isNullConversion(Object.class, pclass)) 442 return; 443 if (isStaticallyNameable(pclass)) { 444 mv.visitTypeInsn(Opcodes.CHECKCAST, getInternalName(pclass)); 445 } else { 446 mv.visitLdcInsn(constantPlaceholder(pclass)); 447 mv.visitTypeInsn(Opcodes.CHECKCAST, CLS); 448 mv.visitInsn(Opcodes.SWAP); 449 mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "castReference", CLL_SIG, false); 450 if (pclass.isArray()) 451 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY); 452 } 453 return; 454 case I_TYPE: 455 if (!VerifyType.isNullConversion(int.class, pclass)) 456 emitPrimCast(basicTypeWrapper(ptype), Wrapper.forPrimitiveType(pclass)); 457 return; 458 } 459 throw new InternalError("bad implicit conversion: tc="+ptype+": "+pclass); 460 } 461 462 /** 463 * Emits an actual return instruction conforming to the given return type. 464 */ 465 private void emitReturnInsn(byte type) { 466 int opcode; 467 switch (type) { 468 case I_TYPE: opcode = Opcodes.IRETURN; break; 469 case J_TYPE: opcode = Opcodes.LRETURN; break; 470 case F_TYPE: opcode = Opcodes.FRETURN; break; 471 case D_TYPE: opcode = Opcodes.DRETURN; break; 472 case L_TYPE: opcode = Opcodes.ARETURN; break; 473 case V_TYPE: opcode = Opcodes.RETURN; break; 474 default: 475 throw new InternalError("unknown return type: " + type); 476 } 477 mv.visitInsn(opcode); 478 } 479 480 private static String getInternalName(Class<?> c) { 481 assert(VerifyAccess.isTypeVisible(c, Object.class)); 482 return c.getName().replace('.', '/'); 483 } 484 485 /** 486 * Generate customized bytecode for a given LambdaForm. 487 */ 488 static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) { 489 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType); 490 return g.loadMethod(g.generateCustomizedCodeBytes()); 491 } 492 493 /** 494 * Generate an invoker method for the passed {@link LambdaForm}. 495 */ 496 private byte[] generateCustomizedCodeBytes() { 497 classFilePrologue(); 498 499 // Suppress this method in backtraces displayed to the user. 500 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 501 502 // Mark this method as a compiled LambdaForm 503 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Compiled;", true); 504 505 // Force inlining of this invoker method. 506 mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true); 507 508 // iterate over the form's names, generating bytecode instructions for each 509 // start iterating at the first name following the arguments 510 for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) { 511 Name name = lambdaForm.names[i]; 512 MemberName member = name.function.member(); 513 514 if (isSelectAlternative(i)) { 515 emitSelectAlternative(name, lambdaForm.names[i + 1]); 516 i++; // skip MH.invokeBasic of the selectAlternative result 517 } else if (isGuardWithCatch(i)) { 518 emitGuardWithCatch(i); 519 i = i+2; // Jump to the end of GWC idiom 520 } else if (isStaticallyInvocable(member)) { 521 emitStaticInvoke(member, name); 522 } else { 523 emitInvoke(name); 524 } 525 526 // Update cached form name's info in case an intrinsic spanning multiple names was encountered. 527 name = lambdaForm.names[i]; 528 member = name.function.member(); 529 530 // store the result from evaluating to the target name in a local if required 531 // (if this is the last value, i.e., the one that is going to be returned, 532 // avoid store/load/return and just return) 533 if (i == lambdaForm.names.length - 1 && i == lambdaForm.result) { 534 // return value - do nothing 535 } else if (name.type != V_TYPE) { 536 // non-void: actually assign 537 emitStoreInsn(name.type, name.index()); 538 } 539 } 540 541 // return statement 542 emitReturn(); 543 544 classFileEpilogue(); 545 bogusMethod(lambdaForm); 546 547 final byte[] classFile = cw.toByteArray(); 548 maybeDump(className, classFile); 549 return classFile; 550 } 551 552 /** 553 * Emit an invoke for the given name. 554 */ 555 void emitInvoke(Name name) { 556 if (true) { 557 // push receiver 558 MethodHandle target = name.function.resolvedHandle; 559 assert(target != null) : name.exprString(); 560 mv.visitLdcInsn(constantPlaceholder(target)); 561 mv.visitTypeInsn(Opcodes.CHECKCAST, MH); 562 } else { 563 // load receiver 564 emitAloadInsn(0); 565 mv.visitTypeInsn(Opcodes.CHECKCAST, MH); 566 mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG); 567 mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG); 568 // TODO more to come 569 } 570 571 // push arguments 572 for (int i = 0; i < name.arguments.length; i++) { 573 emitPushArgument(name, i); 574 } 575 576 // invocation 577 MethodType type = name.function.methodType(); 578 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); 579 } 580 581 static private Class<?>[] STATICALLY_INVOCABLE_PACKAGES = { 582 // Sample classes from each package we are willing to bind to statically: 583 java.lang.Object.class, 584 java.util.Arrays.class, 585 sun.misc.Unsafe.class 586 //MethodHandle.class already covered 587 }; 588 589 static boolean isStaticallyInvocable(MemberName member) { 590 if (member == null) return false; 591 if (member.isConstructor()) return false; 592 Class<?> cls = member.getDeclaringClass(); 593 if (cls.isArray() || cls.isPrimitive()) 594 return false; // FIXME 595 if (cls.isAnonymousClass() || cls.isLocalClass()) 596 return false; // inner class of some sort 597 if (cls.getClassLoader() != MethodHandle.class.getClassLoader()) 598 return false; // not on BCP 599 MethodType mtype = member.getMethodOrFieldType(); 600 if (!isStaticallyNameable(mtype.returnType())) 601 return false; 602 for (Class<?> ptype : mtype.parameterArray()) 603 if (!isStaticallyNameable(ptype)) 604 return false; 605 if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls)) 606 return true; // in java.lang.invoke package 607 if (member.isPublic() && isStaticallyNameable(cls)) 608 return true; 609 return false; 610 } 611 612 static boolean isStaticallyNameable(Class<?> cls) { 613 while (cls.isArray()) 614 cls = cls.getComponentType(); 615 if (cls.isPrimitive()) 616 return true; // int[].class, for example 617 // could use VerifyAccess.isClassAccessible but the following is a safe approximation 618 if (cls.getClassLoader() != Object.class.getClassLoader()) 619 return false; 620 if (VerifyAccess.isSamePackage(MethodHandle.class, cls)) 621 return true; 622 if (!Modifier.isPublic(cls.getModifiers())) 623 return false; 624 for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) { 625 if (VerifyAccess.isSamePackage(pkgcls, cls)) 626 return true; 627 } 628 return false; 629 } 630 631 /** 632 * Emit an invoke for the given name, using the MemberName directly. 633 */ 634 void emitStaticInvoke(MemberName member, Name name) { 635 assert(member.equals(name.function.member())); 636 String cname = getInternalName(member.getDeclaringClass()); 637 String mname = member.getName(); 638 String mtype; 639 byte refKind = member.getReferenceKind(); 640 if (refKind == REF_invokeSpecial) { 641 // in order to pass the verifier, we need to convert this to invokevirtual in all cases 642 assert(member.canBeStaticallyBound()) : member; 643 refKind = REF_invokeVirtual; 644 } 645 646 if (member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual) { 647 // Methods from Object declared in an interface can be resolved by JVM to invokevirtual kind. 648 // Need to convert it back to invokeinterface to pass verification and make the invocation works as expected. 649 refKind = REF_invokeInterface; 650 } 651 652 // push arguments 653 for (int i = 0; i < name.arguments.length; i++) { 654 emitPushArgument(name, i); 655 } 656 657 // invocation 658 if (member.isMethod()) { 659 mtype = member.getMethodType().toMethodDescriptorString(); 660 mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype, 661 member.getDeclaringClass().isInterface()); 662 } else { 663 mtype = MethodType.toFieldDescriptorString(member.getFieldType()); 664 mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype); 665 } 666 } 667 int refKindOpcode(byte refKind) { 668 switch (refKind) { 669 case REF_invokeVirtual: return Opcodes.INVOKEVIRTUAL; 670 case REF_invokeStatic: return Opcodes.INVOKESTATIC; 671 case REF_invokeSpecial: return Opcodes.INVOKESPECIAL; 672 case REF_invokeInterface: return Opcodes.INVOKEINTERFACE; 673 case REF_getField: return Opcodes.GETFIELD; 674 case REF_putField: return Opcodes.PUTFIELD; 675 case REF_getStatic: return Opcodes.GETSTATIC; 676 case REF_putStatic: return Opcodes.PUTSTATIC; 677 } 678 throw new InternalError("refKind="+refKind); 679 } 680 681 /** 682 * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}. 683 */ 684 private boolean memberRefersTo(MemberName member, Class<?> declaringClass, String name) { 685 return member != null && 686 member.getDeclaringClass() == declaringClass && 687 member.getName().equals(name); 688 } 689 private boolean nameRefersTo(Name name, Class<?> declaringClass, String methodName) { 690 return name.function != null && 691 memberRefersTo(name.function.member(), declaringClass, methodName); 692 } 693 694 /** 695 * Check if MemberName is a call to MethodHandle.invokeBasic. 696 */ 697 private boolean isInvokeBasic(Name name) { 698 if (name.function == null) 699 return false; 700 if (name.arguments.length < 1) 701 return false; // must have MH argument 702 MemberName member = name.function.member(); 703 return memberRefersTo(member, MethodHandle.class, "invokeBasic") && 704 !member.isPublic() && !member.isStatic(); 705 } 706 707 /** 708 * Check if i-th name is a call to MethodHandleImpl.selectAlternative. 709 */ 710 private boolean isSelectAlternative(int pos) { 711 // selectAlternative idiom: 712 // t_{n}:L=MethodHandleImpl.selectAlternative(...) 713 // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 714 if (pos+1 >= lambdaForm.names.length) return false; 715 Name name0 = lambdaForm.names[pos]; 716 Name name1 = lambdaForm.names[pos+1]; 717 return nameRefersTo(name0, MethodHandleImpl.class, "selectAlternative") && 718 isInvokeBasic(name1) && 719 name1.lastUseIndex(name0) == 0 && // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 720 lambdaForm.lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1} 721 } 722 723 /** 724 * Check if i-th name is a start of GuardWithCatch idiom. 725 */ 726 private boolean isGuardWithCatch(int pos) { 727 // GuardWithCatch idiom: 728 // t_{n}:L=MethodHandle.invokeBasic(...) 729 // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n}); 730 // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1}) 731 if (pos+2 >= lambdaForm.names.length) return false; 732 Name name0 = lambdaForm.names[pos]; 733 Name name1 = lambdaForm.names[pos+1]; 734 Name name2 = lambdaForm.names[pos+2]; 735 return nameRefersTo(name1, MethodHandleImpl.class, "guardWithCatch") && 736 isInvokeBasic(name0) && 737 isInvokeBasic(name2) && 738 name1.lastUseIndex(name0) == 3 && // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n}); 739 lambdaForm.lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1} 740 name2.lastUseIndex(name1) == 1 && // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1}) 741 lambdaForm.lastUseIndex(name1) == pos+2; // t_{n+1} is local: used only in t_{n+2} 742 } 743 744 /** 745 * Emit bytecode for the selectAlternative idiom. 746 * 747 * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest): 748 * <blockquote><pre>{@code 749 * Lambda(a0:L,a1:I)=>{ 750 * t2:I=foo.test(a1:I); 751 * t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int)); 752 * t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I} 753 * }</pre></blockquote> 754 */ 755 private void emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) { 756 Name receiver = (Name) invokeBasicName.arguments[0]; 757 758 Label L_fallback = new Label(); 759 Label L_done = new Label(); 760 761 // load test result 762 emitPushArgument(selectAlternativeName, 0); 763 mv.visitInsn(Opcodes.ICONST_1); 764 765 // if_icmpne L_fallback 766 mv.visitJumpInsn(Opcodes.IF_ICMPNE, L_fallback); 767 768 // invoke selectAlternativeName.arguments[1] 769 emitPushArgument(selectAlternativeName, 1); // get 2nd argument of selectAlternative 770 emitAstoreInsn(receiver.index()); // store the MH in the receiver slot 771 emitInvoke(invokeBasicName); 772 773 // goto L_done 774 mv.visitJumpInsn(Opcodes.GOTO, L_done); 775 776 // L_fallback: 777 mv.visitLabel(L_fallback); 778 779 // invoke selectAlternativeName.arguments[2] 780 emitPushArgument(selectAlternativeName, 2); // get 3rd argument of selectAlternative 781 emitAstoreInsn(receiver.index()); // store the MH in the receiver slot 782 emitInvoke(invokeBasicName); 783 784 // L_done: 785 mv.visitLabel(L_done); 786 } 787 788 /** 789 * Emit bytecode for the guardWithCatch idiom. 790 * 791 * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch): 792 * <blockquote><pre>{@code 793 * guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{ 794 * t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L); 795 * t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L); 796 * t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I} 797 * }</pre></blockquote> 798 * 799 * It is compiled into bytecode equivalent of the following code: 800 * <blockquote><pre>{@code 801 * try { 802 * return a1.invokeBasic(a6, a7); 803 * } catch (Throwable e) { 804 * if (!a2.isInstance(e)) throw e; 805 * return a3.invokeBasic(ex, a6, a7); 806 * }} 807 */ 808 private void emitGuardWithCatch(int pos) { 809 Name args = lambdaForm.names[pos]; 810 Name invoker = lambdaForm.names[pos+1]; 811 Name result = lambdaForm.names[pos+2]; 812 813 Label L_startBlock = new Label(); 814 Label L_endBlock = new Label(); 815 Label L_handler = new Label(); 816 Label L_done = new Label(); 817 818 Class<?> returnType = result.function.resolvedHandle.type().returnType(); 819 MethodType type = args.function.resolvedHandle.type() 820 .dropParameterTypes(0,1) 821 .changeReturnType(returnType); 822 823 mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable"); 824 825 // Normal case 826 mv.visitLabel(L_startBlock); 827 // load target 828 emitPushArgument(invoker, 0); 829 emitPushArguments(args, 1); // skip 1st argument: method handle 830 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); 831 mv.visitLabel(L_endBlock); 832 mv.visitJumpInsn(Opcodes.GOTO, L_done); 833 834 // Exceptional case 835 mv.visitLabel(L_handler); 836 837 // Check exception's type 838 mv.visitInsn(Opcodes.DUP); 839 // load exception class 840 emitPushArgument(invoker, 1); 841 mv.visitInsn(Opcodes.SWAP); 842 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false); 843 Label L_rethrow = new Label(); 844 mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow); 845 846 // Invoke catcher 847 // load catcher 848 emitPushArgument(invoker, 2); 849 mv.visitInsn(Opcodes.SWAP); 850 emitPushArguments(args, 1); // skip 1st argument: method handle 851 MethodType catcherType = type.insertParameterTypes(0, Throwable.class); 852 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false); 853 mv.visitJumpInsn(Opcodes.GOTO, L_done); 854 855 mv.visitLabel(L_rethrow); 856 mv.visitInsn(Opcodes.ATHROW); 857 858 mv.visitLabel(L_done); 859 } 860 861 private void emitPushArguments(Name args, int start) { 862 for (int i = start; i < args.arguments.length; i++) { 863 emitPushArgument(args, i); 864 } 865 } 866 867 private void emitPushArgument(Name name, int paramIndex) { 868 Object arg = name.arguments[paramIndex]; 869 Class<?> ptype = name.function.methodType().parameterType(paramIndex); 870 emitPushArgument(ptype, arg); 871 } 872 873 private void emitPushArgument(Class<?> ptype, Object arg) { 874 byte bptype = basicType(ptype); 875 if (arg instanceof Name) { 876 Name n = (Name) arg; 877 emitLoadInsn(n.type, n.index()); 878 emitImplicitConversion(n.type, ptype); 879 } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) { 880 emitConst(arg); 881 } else { 882 if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) { 883 emitConst(arg); 884 } else { 885 mv.visitLdcInsn(constantPlaceholder(arg)); 886 emitImplicitConversion(L_TYPE, ptype); 887 } 888 } 889 } 890 891 /** 892 * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type. 893 */ 894 private void emitReturn() { 895 // return statement 896 Class<?> rclass = invokerType.returnType(); 897 byte rtype = lambdaForm.returnType(); 898 assert(rtype == basicType(rclass)); // must agree 899 if (rtype == V_TYPE) { 900 // void 901 mv.visitInsn(Opcodes.RETURN); 902 // it doesn't matter what rclass is; the JVM will discard any value 903 } else { 904 LambdaForm.Name rn = lambdaForm.names[lambdaForm.result]; 905 906 // put return value on the stack if it is not already there 907 if (lambdaForm.result != lambdaForm.names.length - 1) { 908 emitLoadInsn(rn.type, lambdaForm.result); 909 } 910 911 emitImplicitConversion(rtype, rclass); 912 913 // generate actual return statement 914 emitReturnInsn(rtype); 915 } 916 } 917 918 /** 919 * Emit a type conversion bytecode casting from "from" to "to". 920 */ 921 private void emitPrimCast(Wrapper from, Wrapper to) { 922 // Here's how. 923 // - indicates forbidden 924 // <-> indicates implicit 925 // to ----> boolean byte short char int long float double 926 // from boolean <-> - - - - - - - 927 // byte - <-> i2s i2c <-> i2l i2f i2d 928 // short - i2b <-> i2c <-> i2l i2f i2d 929 // char - i2b i2s <-> <-> i2l i2f i2d 930 // int - i2b i2s i2c <-> i2l i2f i2d 931 // long - l2i,i2b l2i,i2s l2i,i2c l2i <-> l2f l2d 932 // float - f2i,i2b f2i,i2s f2i,i2c f2i f2l <-> f2d 933 // double - d2i,i2b d2i,i2s d2i,i2c d2i d2l d2f <-> 934 if (from == to) { 935 // no cast required, should be dead code anyway 936 return; 937 } 938 if (from.isSubwordOrInt()) { 939 // cast from {byte,short,char,int} to anything 940 emitI2X(to); 941 } else { 942 // cast from {long,float,double} to anything 943 if (to.isSubwordOrInt()) { 944 // cast to {byte,short,char,int} 945 emitX2I(from); 946 if (to.bitWidth() < 32) { 947 // targets other than int require another conversion 948 emitI2X(to); 949 } 950 } else { 951 // cast to {long,float,double} - this is verbose 952 boolean error = false; 953 switch (from) { 954 case LONG: 955 switch (to) { 956 case FLOAT: mv.visitInsn(Opcodes.L2F); break; 957 case DOUBLE: mv.visitInsn(Opcodes.L2D); break; 958 default: error = true; break; 959 } 960 break; 961 case FLOAT: 962 switch (to) { 963 case LONG : mv.visitInsn(Opcodes.F2L); break; 964 case DOUBLE: mv.visitInsn(Opcodes.F2D); break; 965 default: error = true; break; 966 } 967 break; 968 case DOUBLE: 969 switch (to) { 970 case LONG : mv.visitInsn(Opcodes.D2L); break; 971 case FLOAT: mv.visitInsn(Opcodes.D2F); break; 972 default: error = true; break; 973 } 974 break; 975 default: 976 error = true; 977 break; 978 } 979 if (error) { 980 throw new IllegalStateException("unhandled prim cast: " + from + "2" + to); 981 } 982 } 983 } 984 } 985 986 private void emitI2X(Wrapper type) { 987 switch (type) { 988 case BYTE: mv.visitInsn(Opcodes.I2B); break; 989 case SHORT: mv.visitInsn(Opcodes.I2S); break; 990 case CHAR: mv.visitInsn(Opcodes.I2C); break; 991 case INT: /* naught */ break; 992 case LONG: mv.visitInsn(Opcodes.I2L); break; 993 case FLOAT: mv.visitInsn(Opcodes.I2F); break; 994 case DOUBLE: mv.visitInsn(Opcodes.I2D); break; 995 case BOOLEAN: 996 // For compatibility with ValueConversions and explicitCastArguments: 997 mv.visitInsn(Opcodes.ICONST_1); 998 mv.visitInsn(Opcodes.IAND); 999 break; 1000 default: throw new InternalError("unknown type: " + type); 1001 } 1002 } 1003 1004 private void emitX2I(Wrapper type) { 1005 switch (type) { 1006 case LONG: mv.visitInsn(Opcodes.L2I); break; 1007 case FLOAT: mv.visitInsn(Opcodes.F2I); break; 1008 case DOUBLE: mv.visitInsn(Opcodes.D2I); break; 1009 default: throw new InternalError("unknown type: " + type); 1010 } 1011 } 1012 1013 /** 1014 * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments. 1015 */ 1016 static MemberName generateLambdaFormInterpreterEntryPoint(String sig) { 1017 assert(isValidSignature(sig)); 1018 String name = "interpret_"+basicTypeChar(signatureReturn(sig)); 1019 MethodType type = signatureType(sig); // sig includes leading argument 1020 type = type.changeParameterType(0, MethodHandle.class); 1021 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type); 1022 return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes()); 1023 } 1024 1025 private byte[] generateLambdaFormInterpreterEntryPointBytes() { 1026 classFilePrologue(); 1027 1028 // Suppress this method in backtraces displayed to the user. 1029 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 1030 1031 // Don't inline the interpreter entry. 1032 mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true); 1033 1034 // create parameter array 1035 emitIconstInsn(invokerType.parameterCount()); 1036 mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); 1037 1038 // fill parameter array 1039 for (int i = 0; i < invokerType.parameterCount(); i++) { 1040 Class<?> ptype = invokerType.parameterType(i); 1041 mv.visitInsn(Opcodes.DUP); 1042 emitIconstInsn(i); 1043 emitLoadInsn(basicType(ptype), i); 1044 // box if primitive type 1045 if (ptype.isPrimitive()) { 1046 emitBoxing(Wrapper.forPrimitiveType(ptype)); 1047 } 1048 mv.visitInsn(Opcodes.AASTORE); 1049 } 1050 // invoke 1051 emitAloadInsn(0); 1052 mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;"); 1053 mv.visitInsn(Opcodes.SWAP); // swap form and array; avoid local variable 1054 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false); 1055 1056 // maybe unbox 1057 Class<?> rtype = invokerType.returnType(); 1058 if (rtype.isPrimitive() && rtype != void.class) { 1059 emitUnboxing(Wrapper.forPrimitiveType(rtype)); 1060 } 1061 1062 // return statement 1063 emitReturnInsn(basicType(rtype)); 1064 1065 classFileEpilogue(); 1066 bogusMethod(invokerType); 1067 1068 final byte[] classFile = cw.toByteArray(); 1069 maybeDump(className, classFile); 1070 return classFile; 1071 } 1072 1073 /** 1074 * Generate bytecode for a NamedFunction invoker. 1075 */ 1076 static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) { 1077 MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE; 1078 String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType())); 1079 InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType); 1080 return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm)); 1081 } 1082 1083 static int nfi = 0; 1084 1085 private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) { 1086 MethodType dstType = typeForm.erasedType(); 1087 classFilePrologue(); 1088 1089 // Suppress this method in backtraces displayed to the user. 1090 mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true); 1091 1092 // Force inlining of this invoker method. 1093 mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true); 1094 1095 // Load receiver 1096 emitAloadInsn(0); 1097 1098 // Load arguments from array 1099 for (int i = 0; i < dstType.parameterCount(); i++) { 1100 emitAloadInsn(1); 1101 emitIconstInsn(i); 1102 mv.visitInsn(Opcodes.AALOAD); 1103 1104 // Maybe unbox 1105 Class<?> dptype = dstType.parameterType(i); 1106 if (dptype.isPrimitive()) { 1107 Class<?> sptype = dstType.basicType().wrap().parameterType(i); 1108 Wrapper dstWrapper = Wrapper.forBasicType(dptype); 1109 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper; // narrow subword from int 1110 emitUnboxing(srcWrapper); 1111 emitPrimCast(srcWrapper, dstWrapper); 1112 } 1113 } 1114 1115 // Invoke 1116 String targetDesc = dstType.basicType().toMethodDescriptorString(); 1117 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false); 1118 1119 // Box primitive types 1120 Class<?> rtype = dstType.returnType(); 1121 if (rtype != void.class && rtype.isPrimitive()) { 1122 Wrapper srcWrapper = Wrapper.forBasicType(rtype); 1123 Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper; // widen subword to int 1124 // boolean casts not allowed 1125 emitPrimCast(srcWrapper, dstWrapper); 1126 emitBoxing(dstWrapper); 1127 } 1128 1129 // If the return type is void we return a null reference. 1130 if (rtype == void.class) { 1131 mv.visitInsn(Opcodes.ACONST_NULL); 1132 } 1133 emitReturnInsn(L_TYPE); // NOTE: NamedFunction invokers always return a reference value. 1134 1135 classFileEpilogue(); 1136 bogusMethod(dstType); 1137 1138 final byte[] classFile = cw.toByteArray(); 1139 maybeDump(className, classFile); 1140 return classFile; 1141 } 1142 1143 /** 1144 * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool 1145 * for debugging purposes. 1146 */ 1147 private void bogusMethod(Object... os) { 1148 if (DUMP_CLASS_FILES) { 1149 mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null); 1150 for (Object o : os) { 1151 mv.visitLdcInsn(o.toString()); 1152 mv.visitInsn(Opcodes.POP); 1153 } 1154 mv.visitInsn(Opcodes.RETURN); 1155 mv.visitMaxs(0, 0); 1156 mv.visitEnd(); 1157 } 1158 } 1159 }