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