1 /*
   2  * Copyright (c) 2012, 2016, 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 java.io.*;
  29 import java.util.*;
  30 import java.lang.reflect.Modifier;
  31 
  32 import jdk.internal.org.objectweb.asm.*;
  33 
  34 import static java.lang.invoke.LambdaForm.*;
  35 import static java.lang.invoke.LambdaForm.BasicType.*;
  36 import static java.lang.invoke.MethodHandleStatics.*;
  37 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  38 
  39 import sun.invoke.util.VerifyAccess;
  40 import sun.invoke.util.VerifyType;
  41 import sun.invoke.util.Wrapper;
  42 import sun.reflect.misc.ReflectUtil;
  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 LLV_SIG = "(L" + OBJ + ";L" + OBJ + ";)V";
  63 
  64     /** Name of its super class*/
  65     private static final String superName = OBJ;
  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 
  77     /** Info about local variables in compiled lambda form */
  78     private final int[]       localsMap;    // index
  79     private final Class<?>[]  localClasses; // type
  80 
  81     /** ASM bytecode generation. */
  82     private ClassWriter cw;
  83     private MethodVisitor mv;
  84 
  85     private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory();
  86     private static final Class<?> HOST_CLASS = LambdaForm.class;
  87 
  88     /** Main constructor; other constructors delegate to this one. */
  89     private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize,
  90                                      String className, String invokerName, MethodType invokerType) {
  91         if (invokerName.contains(".")) {
  92             int p = invokerName.indexOf('.');
  93             className = invokerName.substring(0, p);
  94             invokerName = invokerName.substring(p+1);
  95         }
  96         if (DUMP_CLASS_FILES) {
  97             className = makeDumpableClassName(className);
  98         }
  99         this.className  = LF + "$" + className;
 100         this.sourceFile = "LambdaForm$" + className;
 101         this.lambdaForm = lambdaForm;
 102         this.invokerName = invokerName;
 103         this.invokerType = invokerType;
 104         this.localsMap = new int[localsMapSize+1];
 105         // last entry of localsMap is count of allocated local slots
 106         this.localClasses = new Class<?>[localsMapSize+1];
 107     }
 108 
 109     /** For generating LambdaForm interpreter entry points. */
 110     private InvokerBytecodeGenerator(String className, String invokerName, MethodType invokerType) {
 111         this(null, invokerType.parameterCount(),
 112              className, invokerName, invokerType);
 113         // Create an array to map name indexes to locals indexes.
 114         for (int i = 0; i < localsMap.length; i++) {
 115             localsMap[i] = invokerType.parameterSlotCount() - invokerType.parameterSlotDepth(i);
 116         }
 117     }
 118 
 119     /** For generating customized code for a single LambdaForm. */
 120     private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) {
 121         this(form, form.names.length,
 122              className, form.debugName, invokerType);
 123         // Create an array to map name indexes to locals indexes.
 124         Name[] names = form.names;
 125         for (int i = 0, index = 0; i < localsMap.length; i++) {
 126             localsMap[i] = index;
 127             if (i < names.length) {
 128                 BasicType type = names[i].type();
 129                 index += type.basicTypeSlots();
 130             }
 131         }
 132     }
 133 
 134 
 135     /** instance counters for dumped classes */
 136     private static final HashMap<String,Integer> DUMP_CLASS_FILES_COUNTERS;
 137     /** debugging flag for saving generated class files */
 138     private static final File DUMP_CLASS_FILES_DIR;
 139 
 140     static {
 141         if (DUMP_CLASS_FILES) {
 142             DUMP_CLASS_FILES_COUNTERS = new HashMap<>();
 143             try {
 144                 File dumpDir = new File("DUMP_CLASS_FILES");
 145                 if (!dumpDir.exists()) {
 146                     dumpDir.mkdirs();
 147                 }
 148                 DUMP_CLASS_FILES_DIR = dumpDir;
 149                 System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/...");
 150             } catch (Exception e) {
 151                 throw newInternalError(e);
 152             }
 153         } else {
 154             DUMP_CLASS_FILES_COUNTERS = null;
 155             DUMP_CLASS_FILES_DIR = null;
 156         }
 157     }
 158 
 159     static void maybeDump(final String className, final byte[] classFile) {
 160         if (DUMP_CLASS_FILES) {
 161             java.security.AccessController.doPrivileged(
 162             new java.security.PrivilegedAction<>() {
 163                 public Void run() {
 164                     try {
 165                         String dumpName = className;
 166                         //dumpName = dumpName.replace('/', '-');
 167                         File dumpFile = new File(DUMP_CLASS_FILES_DIR, dumpName+".class");
 168                         System.out.println("dump: " + dumpFile);
 169                         dumpFile.getParentFile().mkdirs();
 170                         FileOutputStream file = new FileOutputStream(dumpFile);
 171                         file.write(classFile);
 172                         file.close();
 173                         return null;
 174                     } catch (IOException ex) {
 175                         throw newInternalError(ex);
 176                     }
 177                 }
 178             });
 179         }
 180 
 181     }
 182 
 183     private static String makeDumpableClassName(String className) {
 184         Integer ctr;
 185         synchronized (DUMP_CLASS_FILES_COUNTERS) {
 186             ctr = DUMP_CLASS_FILES_COUNTERS.get(className);
 187             if (ctr == null)  ctr = 0;
 188             DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1);
 189         }
 190         String sfx = ctr.toString();
 191         while (sfx.length() < 3)
 192             sfx = "0"+sfx;
 193         className += sfx;
 194         return className;
 195     }
 196 
 197     class CpPatch {
 198         final int index;
 199         final String placeholder;
 200         final Object value;
 201         CpPatch(int index, String placeholder, Object value) {
 202             this.index = index;
 203             this.placeholder = placeholder;
 204             this.value = value;
 205         }
 206         public String toString() {
 207             return "CpPatch/index="+index+",placeholder="+placeholder+",value="+value;
 208         }
 209     }
 210 
 211     Map<Object, CpPatch> cpPatches = new HashMap<>();
 212 
 213     int cph = 0;  // for counting constant placeholders
 214 
 215     String constantPlaceholder(Object arg) {
 216         String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++;
 217         if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + debugString(arg) + ">>";  // debugging aid
 218         if (cpPatches.containsKey(cpPlaceholder)) {
 219             throw new InternalError("observed CP placeholder twice: " + cpPlaceholder);
 220         }
 221         // insert placeholder in CP and remember the patch
 222         int index = cw.newConst((Object) cpPlaceholder);  // TODO check if already in the constant pool
 223         cpPatches.put(cpPlaceholder, new CpPatch(index, cpPlaceholder, arg));
 224         return cpPlaceholder;
 225     }
 226 
 227     Object[] cpPatches(byte[] classFile) {
 228         int size = getConstantPoolSize(classFile);
 229         Object[] res = new Object[size];
 230         for (CpPatch p : cpPatches.values()) {
 231             if (p.index >= size)
 232                 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20)));
 233             res[p.index] = p.value;
 234         }
 235         return res;
 236     }
 237 
 238     private static String debugString(Object arg) {
 239         if (arg instanceof MethodHandle) {
 240             MethodHandle mh = (MethodHandle) arg;
 241             MemberName member = mh.internalMemberName();
 242             if (member != null)
 243                 return member.toString();
 244             return mh.debugString();
 245         }
 246         return arg.toString();
 247     }
 248 
 249     /**
 250      * Extract the number of constant pool entries from a given class file.
 251      *
 252      * @param classFile the bytes of the class file in question.
 253      * @return the number of entries in the constant pool.
 254      */
 255     private static int getConstantPoolSize(byte[] classFile) {
 256         // The first few bytes:
 257         // u4 magic;
 258         // u2 minor_version;
 259         // u2 major_version;
 260         // u2 constant_pool_count;
 261         return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF);
 262     }
 263 
 264     /**
 265      * Extract the MemberName of a newly-defined method.
 266      */
 267     private MemberName loadMethod(byte[] classFile) {
 268         Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, cpPatches(classFile));
 269         return resolveInvokerMember(invokerClass, invokerName, invokerType);
 270     }
 271 
 272     /**
 273      * Define a given class as anonymous class in the runtime system.
 274      */
 275     private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, Object[] patches) {
 276         Class<?> invokerClass = UNSAFE.defineAnonymousClass(HOST_CLASS, classBytes, patches);
 277         UNSAFE.ensureClassInitialized(invokerClass);  // Make sure the class is initialized; VM might complain.
 278         return invokerClass;
 279     }
 280 
 281     private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) {
 282         MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic);
 283         //System.out.println("resolveInvokerMember => "+member);
 284         //for (Method m : invokerClass.getDeclaredMethods())  System.out.println("  "+m);
 285         try {
 286             member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class);
 287         } catch (ReflectiveOperationException e) {
 288             throw newInternalError(e);
 289         }
 290         //System.out.println("resolveInvokerMember => "+member);
 291         return member;
 292     }
 293 
 294     /**
 295      * Set up class file generation.
 296      */
 297     private void classFilePrologue() {
 298         final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 299         cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 300         cw.visit(Opcodes.V1_8, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, className, null, superName, null);
 301         cw.visitSource(sourceFile, null);
 302 
 303         String invokerDesc = invokerType.toMethodDescriptorString();
 304         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
 305     }
 306 
 307     /**
 308      * Tear down class file generation.
 309      */
 310     private void classFileEpilogue() {
 311         mv.visitMaxs(0, 0);
 312         mv.visitEnd();
 313     }
 314 
 315     /*
 316      * Low-level emit helpers.
 317      */
 318     private void emitConst(Object con) {
 319         if (con == null) {
 320             mv.visitInsn(Opcodes.ACONST_NULL);
 321             return;
 322         }
 323         if (con instanceof Integer) {
 324             emitIconstInsn((int) con);
 325             return;
 326         }
 327         if (con instanceof Byte) {
 328             emitIconstInsn((byte)con);
 329             return;
 330         }
 331         if (con instanceof Short) {
 332             emitIconstInsn((short)con);
 333             return;
 334         }
 335         if (con instanceof Character) {
 336             emitIconstInsn((char)con);
 337             return;
 338         }
 339         if (con instanceof Long) {
 340             long x = (long) con;
 341             short sx = (short)x;
 342             if (x == sx) {
 343                 if (sx >= 0 && sx <= 1) {
 344                     mv.visitInsn(Opcodes.LCONST_0 + (int) sx);
 345                 } else {
 346                     emitIconstInsn((int) x);
 347                     mv.visitInsn(Opcodes.I2L);
 348                 }
 349                 return;
 350             }
 351         }
 352         if (con instanceof Float) {
 353             float x = (float) con;
 354             short sx = (short)x;
 355             if (x == sx) {
 356                 if (sx >= 0 && sx <= 2) {
 357                     mv.visitInsn(Opcodes.FCONST_0 + (int) sx);
 358                 } else {
 359                     emitIconstInsn((int) x);
 360                     mv.visitInsn(Opcodes.I2F);
 361                 }
 362                 return;
 363             }
 364         }
 365         if (con instanceof Double) {
 366             double x = (double) con;
 367             short sx = (short)x;
 368             if (x == sx) {
 369                 if (sx >= 0 && sx <= 1) {
 370                     mv.visitInsn(Opcodes.DCONST_0 + (int) sx);
 371                 } else {
 372                     emitIconstInsn((int) x);
 373                     mv.visitInsn(Opcodes.I2D);
 374                 }
 375                 return;
 376             }
 377         }
 378         if (con instanceof Boolean) {
 379             emitIconstInsn((boolean) con ? 1 : 0);
 380             return;
 381         }
 382         // fall through:
 383         mv.visitLdcInsn(con);
 384     }
 385 
 386     private void emitIconstInsn(final int cst) {
 387         if (cst >= -1 && cst <= 5) {
 388             mv.visitInsn(Opcodes.ICONST_0 + cst);
 389         } else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) {
 390             mv.visitIntInsn(Opcodes.BIPUSH, cst);
 391         } else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) {
 392             mv.visitIntInsn(Opcodes.SIPUSH, cst);
 393         } else {
 394             mv.visitLdcInsn(cst);
 395         }
 396     }
 397 
 398     /*
 399      * NOTE: These load/store methods use the localsMap to find the correct index!
 400      */
 401     private void emitLoadInsn(BasicType type, int index) {
 402         int opcode = loadInsnOpcode(type);
 403         mv.visitVarInsn(opcode, localsMap[index]);
 404     }
 405 
 406     private int loadInsnOpcode(BasicType type) throws InternalError {
 407         switch (type) {
 408             case I_TYPE: return Opcodes.ILOAD;
 409             case J_TYPE: return Opcodes.LLOAD;
 410             case F_TYPE: return Opcodes.FLOAD;
 411             case D_TYPE: return Opcodes.DLOAD;
 412             case L_TYPE: return Opcodes.ALOAD;
 413             default:
 414                 throw new InternalError("unknown type: " + type);
 415         }
 416     }
 417     private void emitAloadInsn(int index) {
 418         emitLoadInsn(L_TYPE, index);
 419     }
 420 
 421     private void emitStoreInsn(BasicType type, int index) {
 422         int opcode = storeInsnOpcode(type);
 423         mv.visitVarInsn(opcode, localsMap[index]);
 424     }
 425 
 426     private int storeInsnOpcode(BasicType type) throws InternalError {
 427         switch (type) {
 428             case I_TYPE: return Opcodes.ISTORE;
 429             case J_TYPE: return Opcodes.LSTORE;
 430             case F_TYPE: return Opcodes.FSTORE;
 431             case D_TYPE: return Opcodes.DSTORE;
 432             case L_TYPE: return Opcodes.ASTORE;
 433             default:
 434                 throw new InternalError("unknown type: " + type);
 435         }
 436     }
 437     private void emitAstoreInsn(int index) {
 438         emitStoreInsn(L_TYPE, index);
 439     }
 440 
 441     private byte arrayTypeCode(Wrapper elementType) {
 442         switch (elementType) {
 443             case BOOLEAN: return Opcodes.T_BOOLEAN;
 444             case BYTE:    return Opcodes.T_BYTE;
 445             case CHAR:    return Opcodes.T_CHAR;
 446             case SHORT:   return Opcodes.T_SHORT;
 447             case INT:     return Opcodes.T_INT;
 448             case LONG:    return Opcodes.T_LONG;
 449             case FLOAT:   return Opcodes.T_FLOAT;
 450             case DOUBLE:  return Opcodes.T_DOUBLE;
 451             case OBJECT:  return 0; // in place of Opcodes.T_OBJECT
 452             default:      throw new InternalError();
 453         }
 454     }
 455 
 456     private int arrayInsnOpcode(byte tcode, int aaop) throws InternalError {
 457         assert(aaop == Opcodes.AASTORE || aaop == Opcodes.AALOAD);
 458         int xas;
 459         switch (tcode) {
 460             case Opcodes.T_BOOLEAN: xas = Opcodes.BASTORE; break;
 461             case Opcodes.T_BYTE:    xas = Opcodes.BASTORE; break;
 462             case Opcodes.T_CHAR:    xas = Opcodes.CASTORE; break;
 463             case Opcodes.T_SHORT:   xas = Opcodes.SASTORE; break;
 464             case Opcodes.T_INT:     xas = Opcodes.IASTORE; break;
 465             case Opcodes.T_LONG:    xas = Opcodes.LASTORE; break;
 466             case Opcodes.T_FLOAT:   xas = Opcodes.FASTORE; break;
 467             case Opcodes.T_DOUBLE:  xas = Opcodes.DASTORE; break;
 468             case 0:                 xas = Opcodes.AASTORE; break;
 469             default:      throw new InternalError();
 470         }
 471         return xas - Opcodes.AASTORE + aaop;
 472     }
 473 
 474     /**
 475      * Emit a boxing call.
 476      *
 477      * @param wrapper primitive type class to box.
 478      */
 479     private void emitBoxing(Wrapper wrapper) {
 480         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 481         String name  = "valueOf";
 482         String desc  = "(" + wrapper.basicTypeChar() + ")L" + owner + ";";
 483         mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false);
 484     }
 485 
 486     /**
 487      * Emit an unboxing call (plus preceding checkcast).
 488      *
 489      * @param wrapper wrapper type class to unbox.
 490      */
 491     private void emitUnboxing(Wrapper wrapper) {
 492         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 493         String name  = wrapper.primitiveSimpleName() + "Value";
 494         String desc  = "()" + wrapper.basicTypeChar();
 495         emitReferenceCast(wrapper.wrapperType(), null);
 496         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false);
 497     }
 498 
 499     /**
 500      * Emit an implicit conversion for an argument which must be of the given pclass.
 501      * This is usually a no-op, except when pclass is a subword type or a reference other than Object or an interface.
 502      *
 503      * @param ptype type of value present on stack
 504      * @param pclass type of value required on stack
 505      * @param arg compile-time representation of value on stack (Node, constant) or null if none
 506      */
 507     private void emitImplicitConversion(BasicType ptype, Class<?> pclass, Object arg) {
 508         assert(basicType(pclass) == ptype);  // boxing/unboxing handled by caller
 509         if (pclass == ptype.basicTypeClass() && ptype != L_TYPE)
 510             return;   // nothing to do
 511         switch (ptype) {
 512             case L_TYPE:
 513                 if (VerifyType.isNullConversion(Object.class, pclass, false)) {
 514                     if (PROFILE_LEVEL > 0)
 515                         emitReferenceCast(Object.class, arg);
 516                     return;
 517                 }
 518                 emitReferenceCast(pclass, arg);
 519                 return;
 520             case I_TYPE:
 521                 if (!VerifyType.isNullConversion(int.class, pclass, false))
 522                     emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass));
 523                 return;
 524         }
 525         throw newInternalError("bad implicit conversion: tc="+ptype+": "+pclass);
 526     }
 527 
 528     /** Update localClasses type map.  Return true if the information is already present. */
 529     private boolean assertStaticType(Class<?> cls, Name n) {
 530         int local = n.index();
 531         Class<?> aclass = localClasses[local];
 532         if (aclass != null && (aclass == cls || cls.isAssignableFrom(aclass))) {
 533             return true;  // type info is already present
 534         } else if (aclass == null || aclass.isAssignableFrom(cls)) {
 535             localClasses[local] = cls;  // type info can be improved
 536         }
 537         return false;
 538     }
 539 
 540     private void emitReferenceCast(Class<?> cls, Object arg) {
 541         Name writeBack = null;  // local to write back result
 542         if (arg instanceof Name) {
 543             Name n = (Name) arg;
 544             if (assertStaticType(cls, n))
 545                 return;  // this cast was already performed
 546             if (lambdaForm.useCount(n) > 1) {
 547                 // This guy gets used more than once.
 548                 writeBack = n;
 549             }
 550         }
 551         if (isStaticallyNameable(cls)) {
 552             String sig = getInternalName(cls);
 553             mv.visitTypeInsn(Opcodes.CHECKCAST, sig);
 554         } else {
 555             mv.visitLdcInsn(constantPlaceholder(cls));
 556             mv.visitTypeInsn(Opcodes.CHECKCAST, CLS);
 557             mv.visitInsn(Opcodes.SWAP);
 558             mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLS, "cast", LL_SIG, false);
 559             if (Object[].class.isAssignableFrom(cls))
 560                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY);
 561             else if (PROFILE_LEVEL > 0)
 562                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ);
 563         }
 564         if (writeBack != null) {
 565             mv.visitInsn(Opcodes.DUP);
 566             emitAstoreInsn(writeBack.index());
 567         }
 568     }
 569 
 570     /**
 571      * Emits an actual return instruction conforming to the given return type.
 572      */
 573     private void emitReturnInsn(BasicType type) {
 574         int opcode;
 575         switch (type) {
 576         case I_TYPE:  opcode = Opcodes.IRETURN;  break;
 577         case J_TYPE:  opcode = Opcodes.LRETURN;  break;
 578         case F_TYPE:  opcode = Opcodes.FRETURN;  break;
 579         case D_TYPE:  opcode = Opcodes.DRETURN;  break;
 580         case L_TYPE:  opcode = Opcodes.ARETURN;  break;
 581         case V_TYPE:  opcode = Opcodes.RETURN;   break;
 582         default:
 583             throw new InternalError("unknown return type: " + type);
 584         }
 585         mv.visitInsn(opcode);
 586     }
 587 
 588     private static String getInternalName(Class<?> c) {
 589         if (c == Object.class)             return OBJ;
 590         else if (c == Object[].class)      return OBJARY;
 591         else if (c == Class.class)         return CLS;
 592         else if (c == MethodHandle.class)  return MH;
 593         assert(VerifyAccess.isTypeVisible(c, Object.class)) : c.getName();
 594         return c.getName().replace('.', '/');
 595     }
 596 
 597     /**
 598      * Generate customized bytecode for a given LambdaForm.
 599      */
 600     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 601         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 602         return g.loadMethod(g.generateCustomizedCodeBytes());
 603     }
 604 
 605     /** Generates code to check that actual receiver and LambdaForm matches */
 606     private boolean checkActualReceiver() {
 607         // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0
 608         mv.visitInsn(Opcodes.DUP);
 609         mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]);
 610         mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false);
 611         return true;
 612     }
 613 
 614     static String className(String cn) {
 615         assert checkClassName(cn): "Class not found: " + cn;
 616         return cn;
 617     }
 618 
 619     static boolean checkClassName(String cn) {
 620         Type tp = Type.getType(cn);
 621         // additional sanity so only valid "L;" descriptors work
 622         if (tp.getSort() != Type.OBJECT) {
 623             return false;
 624         }
 625         try {
 626             Class<?> c = Class.forName(tp.getClassName(), false, null);
 627             return true;
 628         } catch (ClassNotFoundException e) {
 629             return false;
 630         }
 631     }
 632 
 633     static final String  LF_HIDDEN_SIG = className("Ljava/lang/invoke/LambdaForm$Hidden;");
 634     static final String  LF_COMPILED_SIG = className("Ljava/lang/invoke/LambdaForm$Compiled;");
 635     static final String  FORCEINLINE_SIG = className("Ljdk/internal/vm/annotation/ForceInline;");
 636     static final String  DONTINLINE_SIG = className("Ljdk/internal/vm/annotation/DontInline;");
 637     static final String  INJECTEDPROFILE_SIG = className("Ljava/lang/invoke/InjectedProfile;");
 638 
 639     /**
 640      * Generate an invoker method for the passed {@link LambdaForm}.
 641      */
 642     private byte[] generateCustomizedCodeBytes() {
 643         classFilePrologue();
 644 
 645         // Suppress this method in backtraces displayed to the user.
 646         mv.visitAnnotation(LF_HIDDEN_SIG, true);
 647 
 648         // Mark this method as a compiled LambdaForm
 649         mv.visitAnnotation(LF_COMPILED_SIG, true);
 650 
 651         if (lambdaForm.forceInline) {
 652             // Force inlining of this invoker method.
 653             mv.visitAnnotation(FORCEINLINE_SIG, true);
 654         } else {
 655             mv.visitAnnotation(DONTINLINE_SIG, true);
 656         }
 657 
 658         constantPlaceholder(lambdaForm); // keep LambdaForm instance & its compiled form lifetime tightly coupled.
 659 
 660         if (lambdaForm.customized != null) {
 661             // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute
 662             // receiver MethodHandle (at slot #0) with an embedded constant and use it instead.
 663             // It enables more efficient code generation in some situations, since embedded constants
 664             // are compile-time constants for JIT compiler.
 665             mv.visitLdcInsn(constantPlaceholder(lambdaForm.customized));
 666             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 667             assert(checkActualReceiver()); // expects MethodHandle on top of the stack
 668             mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]);
 669         }
 670 
 671         // iterate over the form's names, generating bytecode instructions for each
 672         // start iterating at the first name following the arguments
 673         Name onStack = null;
 674         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 675             Name name = lambdaForm.names[i];
 676 
 677             emitStoreResult(onStack);
 678             onStack = name;  // unless otherwise modified below
 679             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 680             switch (intr) {
 681                 case SELECT_ALTERNATIVE:
 682                     assert isSelectAlternative(i);
 683                     if (PROFILE_GWT) {
 684                         assert(name.arguments[0] instanceof Name &&
 685                                nameRefersTo((Name)name.arguments[0], MethodHandleImpl.class, "profileBoolean"));
 686                         mv.visitAnnotation(INJECTEDPROFILE_SIG, true);
 687                     }
 688                     onStack = emitSelectAlternative(name, lambdaForm.names[i+1]);
 689                     i++;  // skip MH.invokeBasic of the selectAlternative result
 690                     continue;
 691                 case GUARD_WITH_CATCH:
 692                     assert isGuardWithCatch(i);
 693                     onStack = emitGuardWithCatch(i);
 694                     i = i+2; // Jump to the end of GWC idiom
 695                     continue;
 696                 case NEW_ARRAY:
 697                     Class<?> rtype = name.function.methodType().returnType();
 698                     if (isStaticallyNameable(rtype)) {
 699                         emitNewArray(name);
 700                         continue;
 701                     }
 702                     break;
 703                 case ARRAY_LOAD:
 704                     emitArrayLoad(name);
 705                     continue;
 706                 case ARRAY_STORE:
 707                     emitArrayStore(name);
 708                     continue;
 709                 case ARRAY_LENGTH:
 710                     emitArrayLength(name);
 711                     continue;
 712                 case IDENTITY:
 713                     assert(name.arguments.length == 1);
 714                     emitPushArguments(name);
 715                     continue;
 716                 case ZERO:
 717                     assert(name.arguments.length == 0);
 718                     emitConst(name.type.basicTypeWrapper().zero());
 719                     continue;
 720                 case NONE:
 721                     // no intrinsic associated
 722                     break;
 723                 default:
 724                     throw newInternalError("Unknown intrinsic: "+intr);
 725             }
 726 
 727             MemberName member = name.function.member();
 728             if (isStaticallyInvocable(member)) {
 729                 emitStaticInvoke(member, name);
 730             } else {
 731                 emitInvoke(name);
 732             }
 733         }
 734 
 735         // return statement
 736         emitReturn(onStack);
 737 
 738         classFileEpilogue();
 739         bogusMethod(lambdaForm);
 740 
 741         final byte[] classFile = cw.toByteArray();
 742         maybeDump(className, classFile);
 743         return classFile;
 744     }
 745 
 746     void emitArrayLoad(Name name)   { emitArrayOp(name, Opcodes.AALOAD);      }
 747     void emitArrayStore(Name name)  { emitArrayOp(name, Opcodes.AASTORE);     }
 748     void emitArrayLength(Name name) { emitArrayOp(name, Opcodes.ARRAYLENGTH); }
 749 
 750     void emitArrayOp(Name name, int arrayOpcode) {
 751         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH;
 752         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 753         assert elementType != null;
 754         emitPushArguments(name);
 755         if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) {
 756             Wrapper w = Wrapper.forPrimitiveType(elementType);
 757             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 758         }
 759         mv.visitInsn(arrayOpcode);
 760     }
 761 
 762     /**
 763      * Emit an invoke for the given name.
 764      */
 765     void emitInvoke(Name name) {
 766         assert(!isLinkerMethodInvoke(name));  // should use the static path for these
 767         if (true) {
 768             // push receiver
 769             MethodHandle target = name.function.resolvedHandle();
 770             assert(target != null) : name.exprString();
 771             mv.visitLdcInsn(constantPlaceholder(target));
 772             emitReferenceCast(MethodHandle.class, target);
 773         } else {
 774             // load receiver
 775             emitAloadInsn(0);
 776             emitReferenceCast(MethodHandle.class, null);
 777             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 778             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 779             // TODO more to come
 780         }
 781 
 782         // push arguments
 783         emitPushArguments(name);
 784 
 785         // invocation
 786         MethodType type = name.function.methodType();
 787         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 788     }
 789 
 790     private static Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 791         // Sample classes from each package we are willing to bind to statically:
 792         java.lang.Object.class,
 793         java.util.Arrays.class,
 794         jdk.internal.misc.Unsafe.class
 795         //MethodHandle.class already covered
 796     };
 797 
 798     static boolean isStaticallyInvocable(NamedFunction[] functions) {
 799         for (NamedFunction nf : functions) {
 800             if (!isStaticallyInvocable(nf.member())) {
 801                 return false;
 802             }
 803         }
 804         return true;
 805     }
 806 
 807     static boolean isStaticallyInvocable(Name name) {
 808         return isStaticallyInvocable(name.function.member());
 809     }
 810 
 811     static boolean isStaticallyInvocable(MemberName member) {
 812         if (member == null)  return false;
 813         if (member.isConstructor())  return false;
 814         Class<?> cls = member.getDeclaringClass();
 815         if (cls.isArray() || cls.isPrimitive())
 816             return false;  // FIXME
 817         if (cls.isAnonymousClass() || cls.isLocalClass())
 818             return false;  // inner class of some sort
 819         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 820             return false;  // not on BCP
 821         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 822             return false;
 823         MethodType mtype = member.getMethodOrFieldType();
 824         if (!isStaticallyNameable(mtype.returnType()))
 825             return false;
 826         for (Class<?> ptype : mtype.parameterArray())
 827             if (!isStaticallyNameable(ptype))
 828                 return false;
 829         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 830             return true;   // in java.lang.invoke package
 831         if (member.isPublic() && isStaticallyNameable(cls))
 832             return true;
 833         return false;
 834     }
 835 
 836     static boolean isStaticallyNameable(Class<?> cls) {
 837         if (cls == Object.class)
 838             return true;
 839         while (cls.isArray())
 840             cls = cls.getComponentType();
 841         if (cls.isPrimitive())
 842             return true;  // int[].class, for example
 843         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 844             return false;
 845         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 846         if (cls.getClassLoader() != Object.class.getClassLoader())
 847             return false;
 848         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 849             return true;
 850         if (!Modifier.isPublic(cls.getModifiers()))
 851             return false;
 852         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 853             if (VerifyAccess.isSamePackage(pkgcls, cls))
 854                 return true;
 855         }
 856         return false;
 857     }
 858 
 859     void emitStaticInvoke(Name name) {
 860         emitStaticInvoke(name.function.member(), name);
 861     }
 862 
 863     /**
 864      * Emit an invoke for the given name, using the MemberName directly.
 865      */
 866     void emitStaticInvoke(MemberName member, Name name) {
 867         assert(member.equals(name.function.member()));
 868         Class<?> defc = member.getDeclaringClass();
 869         String cname = getInternalName(defc);
 870         String mname = member.getName();
 871         String mtype;
 872         byte refKind = member.getReferenceKind();
 873         if (refKind == REF_invokeSpecial) {
 874             // in order to pass the verifier, we need to convert this to invokevirtual in all cases
 875             assert(member.canBeStaticallyBound()) : member;
 876             refKind = REF_invokeVirtual;
 877         }
 878 
 879         assert(!(member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual));
 880 
 881         // push arguments
 882         emitPushArguments(name);
 883 
 884         // invocation
 885         if (member.isMethod()) {
 886             mtype = member.getMethodType().toMethodDescriptorString();
 887             mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype,
 888                                member.getDeclaringClass().isInterface());
 889         } else {
 890             mtype = MethodType.toFieldDescriptorString(member.getFieldType());
 891             mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype);
 892         }
 893         // Issue a type assertion for the result, so we can avoid casts later.
 894         if (name.type == L_TYPE) {
 895             Class<?> rtype = member.getInvocationType().returnType();
 896             assert(!rtype.isPrimitive());
 897             if (rtype != Object.class && !rtype.isInterface()) {
 898                 assertStaticType(rtype, name);
 899             }
 900         }
 901     }
 902 
 903     void emitNewArray(Name name) throws InternalError {
 904         Class<?> rtype = name.function.methodType().returnType();
 905         if (name.arguments.length == 0) {
 906             // The array will be a constant.
 907             Object emptyArray;
 908             try {
 909                 emptyArray = name.function.resolvedHandle().invoke();
 910             } catch (Throwable ex) {
 911                 throw newInternalError(ex);
 912             }
 913             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
 914             assert(emptyArray.getClass() == rtype);  // exact typing
 915             mv.visitLdcInsn(constantPlaceholder(emptyArray));
 916             emitReferenceCast(rtype, emptyArray);
 917             return;
 918         }
 919         Class<?> arrayElementType = rtype.getComponentType();
 920         assert(arrayElementType != null);
 921         emitIconstInsn(name.arguments.length);
 922         int xas = Opcodes.AASTORE;
 923         if (!arrayElementType.isPrimitive()) {
 924             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
 925         } else {
 926             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
 927             xas = arrayInsnOpcode(tc, xas);
 928             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
 929         }
 930         // store arguments
 931         for (int i = 0; i < name.arguments.length; i++) {
 932             mv.visitInsn(Opcodes.DUP);
 933             emitIconstInsn(i);
 934             emitPushArgument(name, i);
 935             mv.visitInsn(xas);
 936         }
 937         // the array is left on the stack
 938         assertStaticType(rtype, name);
 939     }
 940     int refKindOpcode(byte refKind) {
 941         switch (refKind) {
 942         case REF_invokeVirtual:      return Opcodes.INVOKEVIRTUAL;
 943         case REF_invokeStatic:       return Opcodes.INVOKESTATIC;
 944         case REF_invokeSpecial:      return Opcodes.INVOKESPECIAL;
 945         case REF_invokeInterface:    return Opcodes.INVOKEINTERFACE;
 946         case REF_getField:           return Opcodes.GETFIELD;
 947         case REF_putField:           return Opcodes.PUTFIELD;
 948         case REF_getStatic:          return Opcodes.GETSTATIC;
 949         case REF_putStatic:          return Opcodes.PUTSTATIC;
 950         }
 951         throw new InternalError("refKind="+refKind);
 952     }
 953 
 954     /**
 955      * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}.
 956      */
 957     private boolean memberRefersTo(MemberName member, Class<?> declaringClass, String name) {
 958         return member != null &&
 959                member.getDeclaringClass() == declaringClass &&
 960                member.getName().equals(name);
 961     }
 962     private boolean nameRefersTo(Name name, Class<?> declaringClass, String methodName) {
 963         return name.function != null &&
 964                memberRefersTo(name.function.member(), declaringClass, methodName);
 965     }
 966 
 967     /**
 968      * Check if MemberName is a call to MethodHandle.invokeBasic.
 969      */
 970     private boolean isInvokeBasic(Name name) {
 971         if (name.function == null)
 972             return false;
 973         if (name.arguments.length < 1)
 974             return false;  // must have MH argument
 975         MemberName member = name.function.member();
 976         return memberRefersTo(member, MethodHandle.class, "invokeBasic") &&
 977                !member.isPublic() && !member.isStatic();
 978     }
 979 
 980     /**
 981      * Check if MemberName is a call to MethodHandle.linkToStatic, etc.
 982      */
 983     private boolean isLinkerMethodInvoke(Name name) {
 984         if (name.function == null)
 985             return false;
 986         if (name.arguments.length < 1)
 987             return false;  // must have MH argument
 988         MemberName member = name.function.member();
 989         return member != null &&
 990                member.getDeclaringClass() == MethodHandle.class &&
 991                !member.isPublic() && member.isStatic() &&
 992                member.getName().startsWith("linkTo");
 993     }
 994 
 995     /**
 996      * Check if i-th name is a call to MethodHandleImpl.selectAlternative.
 997      */
 998     private boolean isSelectAlternative(int pos) {
 999         // selectAlternative idiom:
1000         //   t_{n}:L=MethodHandleImpl.selectAlternative(...)
1001         //   t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
1002         if (pos+1 >= lambdaForm.names.length)  return false;
1003         Name name0 = lambdaForm.names[pos];
1004         Name name1 = lambdaForm.names[pos+1];
1005         return nameRefersTo(name0, MethodHandleImpl.class, "selectAlternative") &&
1006                isInvokeBasic(name1) &&
1007                name1.lastUseIndex(name0) == 0 &&        // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
1008                lambdaForm.lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1}
1009     }
1010 
1011     /**
1012      * Check if i-th name is a start of GuardWithCatch idiom.
1013      */
1014     private boolean isGuardWithCatch(int pos) {
1015         // GuardWithCatch idiom:
1016         //   t_{n}:L=MethodHandle.invokeBasic(...)
1017         //   t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
1018         //   t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
1019         if (pos+2 >= lambdaForm.names.length)  return false;
1020         Name name0 = lambdaForm.names[pos];
1021         Name name1 = lambdaForm.names[pos+1];
1022         Name name2 = lambdaForm.names[pos+2];
1023         return nameRefersTo(name1, MethodHandleImpl.class, "guardWithCatch") &&
1024                isInvokeBasic(name0) &&
1025                isInvokeBasic(name2) &&
1026                name1.lastUseIndex(name0) == 3 &&          // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
1027                lambdaForm.lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1}
1028                name2.lastUseIndex(name1) == 1 &&          // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
1029                lambdaForm.lastUseIndex(name1) == pos+2;   // t_{n+1} is local: used only in t_{n+2}
1030     }
1031 
1032     /**
1033      * Emit bytecode for the selectAlternative idiom.
1034      *
1035      * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest):
1036      * <blockquote><pre>{@code
1037      *   Lambda(a0:L,a1:I)=>{
1038      *     t2:I=foo.test(a1:I);
1039      *     t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
1040      *     t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
1041      * }</pre></blockquote>
1042      */
1043     private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) {
1044         assert isStaticallyInvocable(invokeBasicName);
1045 
1046         Name receiver = (Name) invokeBasicName.arguments[0];
1047 
1048         Label L_fallback = new Label();
1049         Label L_done     = new Label();
1050 
1051         // load test result
1052         emitPushArgument(selectAlternativeName, 0);
1053 
1054         // if_icmpne L_fallback
1055         mv.visitJumpInsn(Opcodes.IFEQ, L_fallback);
1056 
1057         // invoke selectAlternativeName.arguments[1]
1058         Class<?>[] preForkClasses = localClasses.clone();
1059         emitPushArgument(selectAlternativeName, 1);  // get 2nd argument of selectAlternative
1060         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1061         emitStaticInvoke(invokeBasicName);
1062 
1063         // goto L_done
1064         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1065 
1066         // L_fallback:
1067         mv.visitLabel(L_fallback);
1068 
1069         // invoke selectAlternativeName.arguments[2]
1070         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1071         emitPushArgument(selectAlternativeName, 2);  // get 3rd argument of selectAlternative
1072         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1073         emitStaticInvoke(invokeBasicName);
1074 
1075         // L_done:
1076         mv.visitLabel(L_done);
1077         // for now do not bother to merge typestate; just reset to the dominator state
1078         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1079 
1080         return invokeBasicName;  // return what's on stack
1081     }
1082 
1083     /**
1084       * Emit bytecode for the guardWithCatch idiom.
1085       *
1086       * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
1087       * <blockquote><pre>{@code
1088       *  guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
1089       *    t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
1090       *    t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
1091       *   t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
1092       * }</pre></blockquote>
1093       *
1094       * It is compiled into bytecode equivalent of the following code:
1095       * <blockquote><pre>{@code
1096       *  try {
1097       *      return a1.invokeBasic(a6, a7);
1098       *  } catch (Throwable e) {
1099       *      if (!a2.isInstance(e)) throw e;
1100       *      return a3.invokeBasic(ex, a6, a7);
1101       *  }}
1102       */
1103     private Name emitGuardWithCatch(int pos) {
1104         Name args    = lambdaForm.names[pos];
1105         Name invoker = lambdaForm.names[pos+1];
1106         Name result  = lambdaForm.names[pos+2];
1107 
1108         Label L_startBlock = new Label();
1109         Label L_endBlock = new Label();
1110         Label L_handler = new Label();
1111         Label L_done = new Label();
1112 
1113         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1114         MethodType type = args.function.resolvedHandle().type()
1115                               .dropParameterTypes(0,1)
1116                               .changeReturnType(returnType);
1117 
1118         mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable");
1119 
1120         // Normal case
1121         mv.visitLabel(L_startBlock);
1122         // load target
1123         emitPushArgument(invoker, 0);
1124         emitPushArguments(args, 1); // skip 1st argument: method handle
1125         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1126         mv.visitLabel(L_endBlock);
1127         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1128 
1129         // Exceptional case
1130         mv.visitLabel(L_handler);
1131 
1132         // Check exception's type
1133         mv.visitInsn(Opcodes.DUP);
1134         // load exception class
1135         emitPushArgument(invoker, 1);
1136         mv.visitInsn(Opcodes.SWAP);
1137         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false);
1138         Label L_rethrow = new Label();
1139         mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow);
1140 
1141         // Invoke catcher
1142         // load catcher
1143         emitPushArgument(invoker, 2);
1144         mv.visitInsn(Opcodes.SWAP);
1145         emitPushArguments(args, 1); // skip 1st argument: method handle
1146         MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
1147         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false);
1148         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1149 
1150         mv.visitLabel(L_rethrow);
1151         mv.visitInsn(Opcodes.ATHROW);
1152 
1153         mv.visitLabel(L_done);
1154 
1155         return result;
1156     }
1157 
1158     private void emitPushArguments(Name args) {
1159         emitPushArguments(args, 0);
1160     }
1161 
1162     private void emitPushArguments(Name args, int start) {
1163         for (int i = start; i < args.arguments.length; i++) {
1164             emitPushArgument(args, i);
1165         }
1166     }
1167 
1168     private void emitPushArgument(Name name, int paramIndex) {
1169         Object arg = name.arguments[paramIndex];
1170         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1171         emitPushArgument(ptype, arg);
1172     }
1173 
1174     private void emitPushArgument(Class<?> ptype, Object arg) {
1175         BasicType bptype = basicType(ptype);
1176         if (arg instanceof Name) {
1177             Name n = (Name) arg;
1178             emitLoadInsn(n.type, n.index());
1179             emitImplicitConversion(n.type, ptype, n);
1180         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1181             emitConst(arg);
1182         } else {
1183             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1184                 emitConst(arg);
1185             } else {
1186                 mv.visitLdcInsn(constantPlaceholder(arg));
1187                 emitImplicitConversion(L_TYPE, ptype, arg);
1188             }
1189         }
1190     }
1191 
1192     /**
1193      * Store the name to its local, if necessary.
1194      */
1195     private void emitStoreResult(Name name) {
1196         if (name != null && name.type != V_TYPE) {
1197             // non-void: actually assign
1198             emitStoreInsn(name.type, name.index());
1199         }
1200     }
1201 
1202     /**
1203      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1204      */
1205     private void emitReturn(Name onStack) {
1206         // return statement
1207         Class<?> rclass = invokerType.returnType();
1208         BasicType rtype = lambdaForm.returnType();
1209         assert(rtype == basicType(rclass));  // must agree
1210         if (rtype == V_TYPE) {
1211             // void
1212             mv.visitInsn(Opcodes.RETURN);
1213             // it doesn't matter what rclass is; the JVM will discard any value
1214         } else {
1215             LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
1216 
1217             // put return value on the stack if it is not already there
1218             if (rn != onStack) {
1219                 emitLoadInsn(rtype, lambdaForm.result);
1220             }
1221 
1222             emitImplicitConversion(rtype, rclass, rn);
1223 
1224             // generate actual return statement
1225             emitReturnInsn(rtype);
1226         }
1227     }
1228 
1229     /**
1230      * Emit a type conversion bytecode casting from "from" to "to".
1231      */
1232     private void emitPrimCast(Wrapper from, Wrapper to) {
1233         // Here's how.
1234         // -   indicates forbidden
1235         // <-> indicates implicit
1236         //      to ----> boolean  byte     short    char     int      long     float    double
1237         // from boolean    <->        -        -        -        -        -        -        -
1238         //      byte        -       <->       i2s      i2c      <->      i2l      i2f      i2d
1239         //      short       -       i2b       <->      i2c      <->      i2l      i2f      i2d
1240         //      char        -       i2b       i2s      <->      <->      i2l      i2f      i2d
1241         //      int         -       i2b       i2s      i2c      <->      i2l      i2f      i2d
1242         //      long        -     l2i,i2b   l2i,i2s  l2i,i2c    l2i      <->      l2f      l2d
1243         //      float       -     f2i,i2b   f2i,i2s  f2i,i2c    f2i      f2l      <->      f2d
1244         //      double      -     d2i,i2b   d2i,i2s  d2i,i2c    d2i      d2l      d2f      <->
1245         if (from == to) {
1246             // no cast required, should be dead code anyway
1247             return;
1248         }
1249         if (from.isSubwordOrInt()) {
1250             // cast from {byte,short,char,int} to anything
1251             emitI2X(to);
1252         } else {
1253             // cast from {long,float,double} to anything
1254             if (to.isSubwordOrInt()) {
1255                 // cast to {byte,short,char,int}
1256                 emitX2I(from);
1257                 if (to.bitWidth() < 32) {
1258                     // targets other than int require another conversion
1259                     emitI2X(to);
1260                 }
1261             } else {
1262                 // cast to {long,float,double} - this is verbose
1263                 boolean error = false;
1264                 switch (from) {
1265                 case LONG:
1266                     switch (to) {
1267                     case FLOAT:   mv.visitInsn(Opcodes.L2F);  break;
1268                     case DOUBLE:  mv.visitInsn(Opcodes.L2D);  break;
1269                     default:      error = true;               break;
1270                     }
1271                     break;
1272                 case FLOAT:
1273                     switch (to) {
1274                     case LONG :   mv.visitInsn(Opcodes.F2L);  break;
1275                     case DOUBLE:  mv.visitInsn(Opcodes.F2D);  break;
1276                     default:      error = true;               break;
1277                     }
1278                     break;
1279                 case DOUBLE:
1280                     switch (to) {
1281                     case LONG :   mv.visitInsn(Opcodes.D2L);  break;
1282                     case FLOAT:   mv.visitInsn(Opcodes.D2F);  break;
1283                     default:      error = true;               break;
1284                     }
1285                     break;
1286                 default:
1287                     error = true;
1288                     break;
1289                 }
1290                 if (error) {
1291                     throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
1292                 }
1293             }
1294         }
1295     }
1296 
1297     private void emitI2X(Wrapper type) {
1298         switch (type) {
1299         case BYTE:    mv.visitInsn(Opcodes.I2B);  break;
1300         case SHORT:   mv.visitInsn(Opcodes.I2S);  break;
1301         case CHAR:    mv.visitInsn(Opcodes.I2C);  break;
1302         case INT:     /* naught */                break;
1303         case LONG:    mv.visitInsn(Opcodes.I2L);  break;
1304         case FLOAT:   mv.visitInsn(Opcodes.I2F);  break;
1305         case DOUBLE:  mv.visitInsn(Opcodes.I2D);  break;
1306         case BOOLEAN:
1307             // For compatibility with ValueConversions and explicitCastArguments:
1308             mv.visitInsn(Opcodes.ICONST_1);
1309             mv.visitInsn(Opcodes.IAND);
1310             break;
1311         default:   throw new InternalError("unknown type: " + type);
1312         }
1313     }
1314 
1315     private void emitX2I(Wrapper type) {
1316         switch (type) {
1317         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1318         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1319         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1320         default:      throw new InternalError("unknown type: " + type);
1321         }
1322     }
1323 
1324     /**
1325      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1326      */
1327     static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) {
1328         assert(isValidSignature(basicTypeSignature(mt)));
1329         String name = "interpret_"+basicTypeChar(mt.returnType());
1330         MethodType type = mt;  // includes leading argument
1331         type = type.changeParameterType(0, MethodHandle.class);
1332         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1333         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1334     }
1335 
1336     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1337         classFilePrologue();
1338 
1339         // Suppress this method in backtraces displayed to the user.
1340         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1341 
1342         // Don't inline the interpreter entry.
1343         mv.visitAnnotation(DONTINLINE_SIG, true);
1344 
1345         // create parameter array
1346         emitIconstInsn(invokerType.parameterCount());
1347         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1348 
1349         // fill parameter array
1350         for (int i = 0; i < invokerType.parameterCount(); i++) {
1351             Class<?> ptype = invokerType.parameterType(i);
1352             mv.visitInsn(Opcodes.DUP);
1353             emitIconstInsn(i);
1354             emitLoadInsn(basicType(ptype), i);
1355             // box if primitive type
1356             if (ptype.isPrimitive()) {
1357                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1358             }
1359             mv.visitInsn(Opcodes.AASTORE);
1360         }
1361         // invoke
1362         emitAloadInsn(0);
1363         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1364         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1365         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1366 
1367         // maybe unbox
1368         Class<?> rtype = invokerType.returnType();
1369         if (rtype.isPrimitive() && rtype != void.class) {
1370             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1371         }
1372 
1373         // return statement
1374         emitReturnInsn(basicType(rtype));
1375 
1376         classFileEpilogue();
1377         bogusMethod(invokerType);
1378 
1379         final byte[] classFile = cw.toByteArray();
1380         maybeDump(className, classFile);
1381         return classFile;
1382     }
1383 
1384     /**
1385      * Generate bytecode for a NamedFunction invoker.
1386      */
1387     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1388         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1389         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1390         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1391         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1392     }
1393 
1394     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1395         MethodType dstType = typeForm.erasedType();
1396         classFilePrologue();
1397 
1398         // Suppress this method in backtraces displayed to the user.
1399         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1400 
1401         // Force inlining of this invoker method.
1402         mv.visitAnnotation(FORCEINLINE_SIG, true);
1403 
1404         // Load receiver
1405         emitAloadInsn(0);
1406 
1407         // Load arguments from array
1408         for (int i = 0; i < dstType.parameterCount(); i++) {
1409             emitAloadInsn(1);
1410             emitIconstInsn(i);
1411             mv.visitInsn(Opcodes.AALOAD);
1412 
1413             // Maybe unbox
1414             Class<?> dptype = dstType.parameterType(i);
1415             if (dptype.isPrimitive()) {
1416                 Class<?> sptype = dstType.basicType().wrap().parameterType(i);
1417                 Wrapper dstWrapper = Wrapper.forBasicType(dptype);
1418                 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper;  // narrow subword from int
1419                 emitUnboxing(srcWrapper);
1420                 emitPrimCast(srcWrapper, dstWrapper);
1421             }
1422         }
1423 
1424         // Invoke
1425         String targetDesc = dstType.basicType().toMethodDescriptorString();
1426         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1427 
1428         // Box primitive types
1429         Class<?> rtype = dstType.returnType();
1430         if (rtype != void.class && rtype.isPrimitive()) {
1431             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1432             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1433             // boolean casts not allowed
1434             emitPrimCast(srcWrapper, dstWrapper);
1435             emitBoxing(dstWrapper);
1436         }
1437 
1438         // If the return type is void we return a null reference.
1439         if (rtype == void.class) {
1440             mv.visitInsn(Opcodes.ACONST_NULL);
1441         }
1442         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1443 
1444         classFileEpilogue();
1445         bogusMethod(dstType);
1446 
1447         final byte[] classFile = cw.toByteArray();
1448         maybeDump(className, classFile);
1449         return classFile;
1450     }
1451 
1452     /**
1453      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1454      * for debugging purposes.
1455      */
1456     private void bogusMethod(Object... os) {
1457         if (DUMP_CLASS_FILES) {
1458             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1459             for (Object o : os) {
1460                 mv.visitLdcInsn(o.toString());
1461                 mv.visitInsn(Opcodes.POP);
1462             }
1463             mv.visitInsn(Opcodes.RETURN);
1464             mv.visitMaxs(0, 0);
1465             mv.visitEnd();
1466         }
1467     }
1468 }