1 /*
   2  * Copyright (c) 2012, 2015, 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         if (lambdaForm.customized != null) {
 659             // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute
 660             // receiver MethodHandle (at slot #0) with an embedded constant and use it instead.
 661             // It enables more efficient code generation in some situations, since embedded constants
 662             // are compile-time constants for JIT compiler.
 663             mv.visitLdcInsn(constantPlaceholder(lambdaForm.customized));
 664             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 665             assert(checkActualReceiver()); // expects MethodHandle on top of the stack
 666             mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]);
 667         }
 668 
 669         // iterate over the form's names, generating bytecode instructions for each
 670         // start iterating at the first name following the arguments
 671         Name onStack = null;
 672         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 673             Name name = lambdaForm.names[i];
 674 
 675             emitStoreResult(onStack);
 676             onStack = name;  // unless otherwise modified below
 677             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 678             switch (intr) {
 679                 case SELECT_ALTERNATIVE:
 680                     assert isSelectAlternative(i);
 681                     if (PROFILE_GWT) {
 682                         assert(name.arguments[0] instanceof Name &&
 683                                nameRefersTo((Name)name.arguments[0], MethodHandleImpl.class, "profileBoolean"));
 684                         mv.visitAnnotation(INJECTEDPROFILE_SIG, true);
 685                     }
 686                     onStack = emitSelectAlternative(name, lambdaForm.names[i+1]);
 687                     i++;  // skip MH.invokeBasic of the selectAlternative result
 688                     continue;
 689                 case GUARD_WITH_CATCH:
 690                     assert isGuardWithCatch(i);
 691                     onStack = emitGuardWithCatch(i);
 692                     i = i+2; // Jump to the end of GWC idiom
 693                     continue;
 694                 case NEW_ARRAY:
 695                     Class<?> rtype = name.function.methodType().returnType();
 696                     if (isStaticallyNameable(rtype)) {
 697                         emitNewArray(name);
 698                         continue;
 699                     }
 700                     break;
 701                 case ARRAY_LOAD:
 702                     emitArrayLoad(name);
 703                     continue;
 704                 case ARRAY_STORE:
 705                     emitArrayStore(name);
 706                     continue;
 707                 case IDENTITY:
 708                     assert(name.arguments.length == 1);
 709                     emitPushArguments(name);
 710                     continue;
 711                 case ZERO:
 712                     assert(name.arguments.length == 0);
 713                     emitConst(name.type.basicTypeWrapper().zero());
 714                     continue;
 715                 case NONE:
 716                     // no intrinsic associated
 717                     break;
 718                 default:
 719                     throw newInternalError("Unknown intrinsic: "+intr);
 720             }
 721 
 722             MemberName member = name.function.member();
 723             if (isStaticallyInvocable(member)) {
 724                 emitStaticInvoke(member, name);
 725             } else {
 726                 emitInvoke(name);
 727             }
 728         }
 729 
 730         // return statement
 731         emitReturn(onStack);
 732 
 733         classFileEpilogue();
 734         bogusMethod(lambdaForm);
 735 
 736         final byte[] classFile = cw.toByteArray();
 737         maybeDump(className, classFile);
 738         return classFile;
 739     }
 740 
 741     void emitArrayLoad(Name name)  { emitArrayOp(name, Opcodes.AALOAD);  }
 742     void emitArrayStore(Name name) { emitArrayOp(name, Opcodes.AASTORE); }
 743 
 744     void emitArrayOp(Name name, int arrayOpcode) {
 745         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE;
 746         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 747         assert elementType != null;
 748         emitPushArguments(name);
 749         if (elementType.isPrimitive()) {
 750             Wrapper w = Wrapper.forPrimitiveType(elementType);
 751             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 752         }
 753         mv.visitInsn(arrayOpcode);
 754     }
 755 
 756     /**
 757      * Emit an invoke for the given name.
 758      */
 759     void emitInvoke(Name name) {
 760         assert(!isLinkerMethodInvoke(name));  // should use the static path for these
 761         if (true) {
 762             // push receiver
 763             MethodHandle target = name.function.resolvedHandle();
 764             assert(target != null) : name.exprString();
 765             mv.visitLdcInsn(constantPlaceholder(target));
 766             emitReferenceCast(MethodHandle.class, target);
 767         } else {
 768             // load receiver
 769             emitAloadInsn(0);
 770             emitReferenceCast(MethodHandle.class, null);
 771             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 772             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 773             // TODO more to come
 774         }
 775 
 776         // push arguments
 777         emitPushArguments(name);
 778 
 779         // invocation
 780         MethodType type = name.function.methodType();
 781         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 782     }
 783 
 784     private static Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 785         // Sample classes from each package we are willing to bind to statically:
 786         java.lang.Object.class,
 787         java.util.Arrays.class,
 788         jdk.internal.misc.Unsafe.class
 789         //MethodHandle.class already covered
 790     };
 791 
 792     static boolean isStaticallyInvocable(NamedFunction[] functions) {
 793         for (NamedFunction nf : functions) {
 794             if (!isStaticallyInvocable(nf.member())) {
 795                 return false;
 796             }
 797         }
 798         return true;
 799     }
 800 
 801     static boolean isStaticallyInvocable(Name name) {
 802         return isStaticallyInvocable(name.function.member());
 803     }
 804 
 805     static boolean isStaticallyInvocable(MemberName member) {
 806         if (member == null)  return false;
 807         if (member.isConstructor())  return false;
 808         Class<?> cls = member.getDeclaringClass();
 809         if (cls.isArray() || cls.isPrimitive())
 810             return false;  // FIXME
 811         if (cls.isAnonymousClass() || cls.isLocalClass())
 812             return false;  // inner class of some sort
 813         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 814             return false;  // not on BCP
 815         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 816             return false;
 817         MethodType mtype = member.getMethodOrFieldType();
 818         if (!isStaticallyNameable(mtype.returnType()))
 819             return false;
 820         for (Class<?> ptype : mtype.parameterArray())
 821             if (!isStaticallyNameable(ptype))
 822                 return false;
 823         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 824             return true;   // in java.lang.invoke package
 825         if (member.isPublic() && isStaticallyNameable(cls))
 826             return true;
 827         return false;
 828     }
 829 
 830     static boolean isStaticallyNameable(Class<?> cls) {
 831         if (cls == Object.class)
 832             return true;
 833         while (cls.isArray())
 834             cls = cls.getComponentType();
 835         if (cls.isPrimitive())
 836             return true;  // int[].class, for example
 837         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 838             return false;
 839         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 840         if (cls.getClassLoader() != Object.class.getClassLoader())
 841             return false;
 842         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 843             return true;
 844         if (!Modifier.isPublic(cls.getModifiers()))
 845             return false;
 846         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 847             if (VerifyAccess.isSamePackage(pkgcls, cls))
 848                 return true;
 849         }
 850         return false;
 851     }
 852 
 853     void emitStaticInvoke(Name name) {
 854         emitStaticInvoke(name.function.member(), name);
 855     }
 856 
 857     /**
 858      * Emit an invoke for the given name, using the MemberName directly.
 859      */
 860     void emitStaticInvoke(MemberName member, Name name) {
 861         assert(member.equals(name.function.member()));
 862         Class<?> defc = member.getDeclaringClass();
 863         String cname = getInternalName(defc);
 864         String mname = member.getName();
 865         String mtype;
 866         byte refKind = member.getReferenceKind();
 867         if (refKind == REF_invokeSpecial) {
 868             // in order to pass the verifier, we need to convert this to invokevirtual in all cases
 869             assert(member.canBeStaticallyBound()) : member;
 870             refKind = REF_invokeVirtual;
 871         }
 872 
 873         assert(!(member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual));
 874 
 875         // push arguments
 876         emitPushArguments(name);
 877 
 878         // invocation
 879         if (member.isMethod()) {
 880             mtype = member.getMethodType().toMethodDescriptorString();
 881             mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype,
 882                                member.getDeclaringClass().isInterface());
 883         } else {
 884             mtype = MethodType.toFieldDescriptorString(member.getFieldType());
 885             mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype);
 886         }
 887         // Issue a type assertion for the result, so we can avoid casts later.
 888         if (name.type == L_TYPE) {
 889             Class<?> rtype = member.getInvocationType().returnType();
 890             assert(!rtype.isPrimitive());
 891             if (rtype != Object.class && !rtype.isInterface()) {
 892                 assertStaticType(rtype, name);
 893             }
 894         }
 895     }
 896 
 897     void emitNewArray(Name name) throws InternalError {
 898         Class<?> rtype = name.function.methodType().returnType();
 899         if (name.arguments.length == 0) {
 900             // The array will be a constant.
 901             Object emptyArray;
 902             try {
 903                 emptyArray = name.function.resolvedHandle().invoke();
 904             } catch (Throwable ex) {
 905                 throw newInternalError(ex);
 906             }
 907             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
 908             assert(emptyArray.getClass() == rtype);  // exact typing
 909             mv.visitLdcInsn(constantPlaceholder(emptyArray));
 910             emitReferenceCast(rtype, emptyArray);
 911             return;
 912         }
 913         Class<?> arrayElementType = rtype.getComponentType();
 914         assert(arrayElementType != null);
 915         emitIconstInsn(name.arguments.length);
 916         int xas = Opcodes.AASTORE;
 917         if (!arrayElementType.isPrimitive()) {
 918             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
 919         } else {
 920             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
 921             xas = arrayInsnOpcode(tc, xas);
 922             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
 923         }
 924         // store arguments
 925         for (int i = 0; i < name.arguments.length; i++) {
 926             mv.visitInsn(Opcodes.DUP);
 927             emitIconstInsn(i);
 928             emitPushArgument(name, i);
 929             mv.visitInsn(xas);
 930         }
 931         // the array is left on the stack
 932         assertStaticType(rtype, name);
 933     }
 934     int refKindOpcode(byte refKind) {
 935         switch (refKind) {
 936         case REF_invokeVirtual:      return Opcodes.INVOKEVIRTUAL;
 937         case REF_invokeStatic:       return Opcodes.INVOKESTATIC;
 938         case REF_invokeSpecial:      return Opcodes.INVOKESPECIAL;
 939         case REF_invokeInterface:    return Opcodes.INVOKEINTERFACE;
 940         case REF_getField:           return Opcodes.GETFIELD;
 941         case REF_putField:           return Opcodes.PUTFIELD;
 942         case REF_getStatic:          return Opcodes.GETSTATIC;
 943         case REF_putStatic:          return Opcodes.PUTSTATIC;
 944         }
 945         throw new InternalError("refKind="+refKind);
 946     }
 947 
 948     /**
 949      * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}.
 950      */
 951     private boolean memberRefersTo(MemberName member, Class<?> declaringClass, String name) {
 952         return member != null &&
 953                member.getDeclaringClass() == declaringClass &&
 954                member.getName().equals(name);
 955     }
 956     private boolean nameRefersTo(Name name, Class<?> declaringClass, String methodName) {
 957         return name.function != null &&
 958                memberRefersTo(name.function.member(), declaringClass, methodName);
 959     }
 960 
 961     /**
 962      * Check if MemberName is a call to MethodHandle.invokeBasic.
 963      */
 964     private boolean isInvokeBasic(Name name) {
 965         if (name.function == null)
 966             return false;
 967         if (name.arguments.length < 1)
 968             return false;  // must have MH argument
 969         MemberName member = name.function.member();
 970         return memberRefersTo(member, MethodHandle.class, "invokeBasic") &&
 971                !member.isPublic() && !member.isStatic();
 972     }
 973 
 974     /**
 975      * Check if MemberName is a call to MethodHandle.linkToStatic, etc.
 976      */
 977     private boolean isLinkerMethodInvoke(Name name) {
 978         if (name.function == null)
 979             return false;
 980         if (name.arguments.length < 1)
 981             return false;  // must have MH argument
 982         MemberName member = name.function.member();
 983         return member != null &&
 984                member.getDeclaringClass() == MethodHandle.class &&
 985                !member.isPublic() && member.isStatic() &&
 986                member.getName().startsWith("linkTo");
 987     }
 988 
 989     /**
 990      * Check if i-th name is a call to MethodHandleImpl.selectAlternative.
 991      */
 992     private boolean isSelectAlternative(int pos) {
 993         // selectAlternative idiom:
 994         //   t_{n}:L=MethodHandleImpl.selectAlternative(...)
 995         //   t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 996         if (pos+1 >= lambdaForm.names.length)  return false;
 997         Name name0 = lambdaForm.names[pos];
 998         Name name1 = lambdaForm.names[pos+1];
 999         return nameRefersTo(name0, MethodHandleImpl.class, "selectAlternative") &&
1000                isInvokeBasic(name1) &&
1001                name1.lastUseIndex(name0) == 0 &&        // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
1002                lambdaForm.lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1}
1003     }
1004 
1005     /**
1006      * Check if i-th name is a start of GuardWithCatch idiom.
1007      */
1008     private boolean isGuardWithCatch(int pos) {
1009         // GuardWithCatch idiom:
1010         //   t_{n}:L=MethodHandle.invokeBasic(...)
1011         //   t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
1012         //   t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
1013         if (pos+2 >= lambdaForm.names.length)  return false;
1014         Name name0 = lambdaForm.names[pos];
1015         Name name1 = lambdaForm.names[pos+1];
1016         Name name2 = lambdaForm.names[pos+2];
1017         return nameRefersTo(name1, MethodHandleImpl.class, "guardWithCatch") &&
1018                isInvokeBasic(name0) &&
1019                isInvokeBasic(name2) &&
1020                name1.lastUseIndex(name0) == 3 &&          // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
1021                lambdaForm.lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1}
1022                name2.lastUseIndex(name1) == 1 &&          // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
1023                lambdaForm.lastUseIndex(name1) == pos+2;   // t_{n+1} is local: used only in t_{n+2}
1024     }
1025 
1026     /**
1027      * Emit bytecode for the selectAlternative idiom.
1028      *
1029      * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest):
1030      * <blockquote><pre>{@code
1031      *   Lambda(a0:L,a1:I)=>{
1032      *     t2:I=foo.test(a1:I);
1033      *     t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
1034      *     t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
1035      * }</pre></blockquote>
1036      */
1037     private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) {
1038         assert isStaticallyInvocable(invokeBasicName);
1039 
1040         Name receiver = (Name) invokeBasicName.arguments[0];
1041 
1042         Label L_fallback = new Label();
1043         Label L_done     = new Label();
1044 
1045         // load test result
1046         emitPushArgument(selectAlternativeName, 0);
1047 
1048         // if_icmpne L_fallback
1049         mv.visitJumpInsn(Opcodes.IFEQ, L_fallback);
1050 
1051         // invoke selectAlternativeName.arguments[1]
1052         Class<?>[] preForkClasses = localClasses.clone();
1053         emitPushArgument(selectAlternativeName, 1);  // get 2nd argument of selectAlternative
1054         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1055         emitStaticInvoke(invokeBasicName);
1056 
1057         // goto L_done
1058         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1059 
1060         // L_fallback:
1061         mv.visitLabel(L_fallback);
1062 
1063         // invoke selectAlternativeName.arguments[2]
1064         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1065         emitPushArgument(selectAlternativeName, 2);  // get 3rd argument of selectAlternative
1066         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1067         emitStaticInvoke(invokeBasicName);
1068 
1069         // L_done:
1070         mv.visitLabel(L_done);
1071         // for now do not bother to merge typestate; just reset to the dominator state
1072         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1073 
1074         return invokeBasicName;  // return what's on stack
1075     }
1076 
1077     /**
1078       * Emit bytecode for the guardWithCatch idiom.
1079       *
1080       * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
1081       * <blockquote><pre>{@code
1082       *  guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
1083       *    t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
1084       *    t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
1085       *   t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
1086       * }</pre></blockquote>
1087       *
1088       * It is compiled into bytecode equivalent of the following code:
1089       * <blockquote><pre>{@code
1090       *  try {
1091       *      return a1.invokeBasic(a6, a7);
1092       *  } catch (Throwable e) {
1093       *      if (!a2.isInstance(e)) throw e;
1094       *      return a3.invokeBasic(ex, a6, a7);
1095       *  }}
1096       */
1097     private Name emitGuardWithCatch(int pos) {
1098         Name args    = lambdaForm.names[pos];
1099         Name invoker = lambdaForm.names[pos+1];
1100         Name result  = lambdaForm.names[pos+2];
1101 
1102         Label L_startBlock = new Label();
1103         Label L_endBlock = new Label();
1104         Label L_handler = new Label();
1105         Label L_done = new Label();
1106 
1107         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1108         MethodType type = args.function.resolvedHandle().type()
1109                               .dropParameterTypes(0,1)
1110                               .changeReturnType(returnType);
1111 
1112         mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable");
1113 
1114         // Normal case
1115         mv.visitLabel(L_startBlock);
1116         // load target
1117         emitPushArgument(invoker, 0);
1118         emitPushArguments(args, 1); // skip 1st argument: method handle
1119         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1120         mv.visitLabel(L_endBlock);
1121         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1122 
1123         // Exceptional case
1124         mv.visitLabel(L_handler);
1125 
1126         // Check exception's type
1127         mv.visitInsn(Opcodes.DUP);
1128         // load exception class
1129         emitPushArgument(invoker, 1);
1130         mv.visitInsn(Opcodes.SWAP);
1131         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false);
1132         Label L_rethrow = new Label();
1133         mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow);
1134 
1135         // Invoke catcher
1136         // load catcher
1137         emitPushArgument(invoker, 2);
1138         mv.visitInsn(Opcodes.SWAP);
1139         emitPushArguments(args, 1); // skip 1st argument: method handle
1140         MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
1141         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false);
1142         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1143 
1144         mv.visitLabel(L_rethrow);
1145         mv.visitInsn(Opcodes.ATHROW);
1146 
1147         mv.visitLabel(L_done);
1148 
1149         return result;
1150     }
1151 
1152     private void emitPushArguments(Name args) {
1153         emitPushArguments(args, 0);
1154     }
1155 
1156     private void emitPushArguments(Name args, int start) {
1157         for (int i = start; i < args.arguments.length; i++) {
1158             emitPushArgument(args, i);
1159         }
1160     }
1161 
1162     private void emitPushArgument(Name name, int paramIndex) {
1163         Object arg = name.arguments[paramIndex];
1164         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1165         emitPushArgument(ptype, arg);
1166     }
1167 
1168     private void emitPushArgument(Class<?> ptype, Object arg) {
1169         BasicType bptype = basicType(ptype);
1170         if (arg instanceof Name) {
1171             Name n = (Name) arg;
1172             emitLoadInsn(n.type, n.index());
1173             emitImplicitConversion(n.type, ptype, n);
1174         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1175             emitConst(arg);
1176         } else {
1177             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1178                 emitConst(arg);
1179             } else {
1180                 mv.visitLdcInsn(constantPlaceholder(arg));
1181                 emitImplicitConversion(L_TYPE, ptype, arg);
1182             }
1183         }
1184     }
1185 
1186     /**
1187      * Store the name to its local, if necessary.
1188      */
1189     private void emitStoreResult(Name name) {
1190         if (name != null && name.type != V_TYPE) {
1191             // non-void: actually assign
1192             emitStoreInsn(name.type, name.index());
1193         }
1194     }
1195 
1196     /**
1197      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1198      */
1199     private void emitReturn(Name onStack) {
1200         // return statement
1201         Class<?> rclass = invokerType.returnType();
1202         BasicType rtype = lambdaForm.returnType();
1203         assert(rtype == basicType(rclass));  // must agree
1204         if (rtype == V_TYPE) {
1205             // void
1206             mv.visitInsn(Opcodes.RETURN);
1207             // it doesn't matter what rclass is; the JVM will discard any value
1208         } else {
1209             LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
1210 
1211             // put return value on the stack if it is not already there
1212             if (rn != onStack) {
1213                 emitLoadInsn(rtype, lambdaForm.result);
1214             }
1215 
1216             emitImplicitConversion(rtype, rclass, rn);
1217 
1218             // generate actual return statement
1219             emitReturnInsn(rtype);
1220         }
1221     }
1222 
1223     /**
1224      * Emit a type conversion bytecode casting from "from" to "to".
1225      */
1226     private void emitPrimCast(Wrapper from, Wrapper to) {
1227         // Here's how.
1228         // -   indicates forbidden
1229         // <-> indicates implicit
1230         //      to ----> boolean  byte     short    char     int      long     float    double
1231         // from boolean    <->        -        -        -        -        -        -        -
1232         //      byte        -       <->       i2s      i2c      <->      i2l      i2f      i2d
1233         //      short       -       i2b       <->      i2c      <->      i2l      i2f      i2d
1234         //      char        -       i2b       i2s      <->      <->      i2l      i2f      i2d
1235         //      int         -       i2b       i2s      i2c      <->      i2l      i2f      i2d
1236         //      long        -     l2i,i2b   l2i,i2s  l2i,i2c    l2i      <->      l2f      l2d
1237         //      float       -     f2i,i2b   f2i,i2s  f2i,i2c    f2i      f2l      <->      f2d
1238         //      double      -     d2i,i2b   d2i,i2s  d2i,i2c    d2i      d2l      d2f      <->
1239         if (from == to) {
1240             // no cast required, should be dead code anyway
1241             return;
1242         }
1243         if (from.isSubwordOrInt()) {
1244             // cast from {byte,short,char,int} to anything
1245             emitI2X(to);
1246         } else {
1247             // cast from {long,float,double} to anything
1248             if (to.isSubwordOrInt()) {
1249                 // cast to {byte,short,char,int}
1250                 emitX2I(from);
1251                 if (to.bitWidth() < 32) {
1252                     // targets other than int require another conversion
1253                     emitI2X(to);
1254                 }
1255             } else {
1256                 // cast to {long,float,double} - this is verbose
1257                 boolean error = false;
1258                 switch (from) {
1259                 case LONG:
1260                     switch (to) {
1261                     case FLOAT:   mv.visitInsn(Opcodes.L2F);  break;
1262                     case DOUBLE:  mv.visitInsn(Opcodes.L2D);  break;
1263                     default:      error = true;               break;
1264                     }
1265                     break;
1266                 case FLOAT:
1267                     switch (to) {
1268                     case LONG :   mv.visitInsn(Opcodes.F2L);  break;
1269                     case DOUBLE:  mv.visitInsn(Opcodes.F2D);  break;
1270                     default:      error = true;               break;
1271                     }
1272                     break;
1273                 case DOUBLE:
1274                     switch (to) {
1275                     case LONG :   mv.visitInsn(Opcodes.D2L);  break;
1276                     case FLOAT:   mv.visitInsn(Opcodes.D2F);  break;
1277                     default:      error = true;               break;
1278                     }
1279                     break;
1280                 default:
1281                     error = true;
1282                     break;
1283                 }
1284                 if (error) {
1285                     throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
1286                 }
1287             }
1288         }
1289     }
1290 
1291     private void emitI2X(Wrapper type) {
1292         switch (type) {
1293         case BYTE:    mv.visitInsn(Opcodes.I2B);  break;
1294         case SHORT:   mv.visitInsn(Opcodes.I2S);  break;
1295         case CHAR:    mv.visitInsn(Opcodes.I2C);  break;
1296         case INT:     /* naught */                break;
1297         case LONG:    mv.visitInsn(Opcodes.I2L);  break;
1298         case FLOAT:   mv.visitInsn(Opcodes.I2F);  break;
1299         case DOUBLE:  mv.visitInsn(Opcodes.I2D);  break;
1300         case BOOLEAN:
1301             // For compatibility with ValueConversions and explicitCastArguments:
1302             mv.visitInsn(Opcodes.ICONST_1);
1303             mv.visitInsn(Opcodes.IAND);
1304             break;
1305         default:   throw new InternalError("unknown type: " + type);
1306         }
1307     }
1308 
1309     private void emitX2I(Wrapper type) {
1310         switch (type) {
1311         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1312         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1313         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1314         default:      throw new InternalError("unknown type: " + type);
1315         }
1316     }
1317 
1318     /**
1319      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1320      */
1321     static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) {
1322         assert(isValidSignature(basicTypeSignature(mt)));
1323         String name = "interpret_"+basicTypeChar(mt.returnType());
1324         MethodType type = mt;  // includes leading argument
1325         type = type.changeParameterType(0, MethodHandle.class);
1326         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1327         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1328     }
1329 
1330     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1331         classFilePrologue();
1332 
1333         // Suppress this method in backtraces displayed to the user.
1334         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1335 
1336         // Don't inline the interpreter entry.
1337         mv.visitAnnotation(DONTINLINE_SIG, true);
1338 
1339         // create parameter array
1340         emitIconstInsn(invokerType.parameterCount());
1341         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1342 
1343         // fill parameter array
1344         for (int i = 0; i < invokerType.parameterCount(); i++) {
1345             Class<?> ptype = invokerType.parameterType(i);
1346             mv.visitInsn(Opcodes.DUP);
1347             emitIconstInsn(i);
1348             emitLoadInsn(basicType(ptype), i);
1349             // box if primitive type
1350             if (ptype.isPrimitive()) {
1351                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1352             }
1353             mv.visitInsn(Opcodes.AASTORE);
1354         }
1355         // invoke
1356         emitAloadInsn(0);
1357         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1358         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1359         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1360 
1361         // maybe unbox
1362         Class<?> rtype = invokerType.returnType();
1363         if (rtype.isPrimitive() && rtype != void.class) {
1364             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1365         }
1366 
1367         // return statement
1368         emitReturnInsn(basicType(rtype));
1369 
1370         classFileEpilogue();
1371         bogusMethod(invokerType);
1372 
1373         final byte[] classFile = cw.toByteArray();
1374         maybeDump(className, classFile);
1375         return classFile;
1376     }
1377 
1378     /**
1379      * Generate bytecode for a NamedFunction invoker.
1380      */
1381     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1382         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1383         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1384         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1385         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1386     }
1387 
1388     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1389         MethodType dstType = typeForm.erasedType();
1390         classFilePrologue();
1391 
1392         // Suppress this method in backtraces displayed to the user.
1393         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1394 
1395         // Force inlining of this invoker method.
1396         mv.visitAnnotation(FORCEINLINE_SIG, true);
1397 
1398         // Load receiver
1399         emitAloadInsn(0);
1400 
1401         // Load arguments from array
1402         for (int i = 0; i < dstType.parameterCount(); i++) {
1403             emitAloadInsn(1);
1404             emitIconstInsn(i);
1405             mv.visitInsn(Opcodes.AALOAD);
1406 
1407             // Maybe unbox
1408             Class<?> dptype = dstType.parameterType(i);
1409             if (dptype.isPrimitive()) {
1410                 Class<?> sptype = dstType.basicType().wrap().parameterType(i);
1411                 Wrapper dstWrapper = Wrapper.forBasicType(dptype);
1412                 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper;  // narrow subword from int
1413                 emitUnboxing(srcWrapper);
1414                 emitPrimCast(srcWrapper, dstWrapper);
1415             }
1416         }
1417 
1418         // Invoke
1419         String targetDesc = dstType.basicType().toMethodDescriptorString();
1420         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1421 
1422         // Box primitive types
1423         Class<?> rtype = dstType.returnType();
1424         if (rtype != void.class && rtype.isPrimitive()) {
1425             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1426             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1427             // boolean casts not allowed
1428             emitPrimCast(srcWrapper, dstWrapper);
1429             emitBoxing(dstWrapper);
1430         }
1431 
1432         // If the return type is void we return a null reference.
1433         if (rtype == void.class) {
1434             mv.visitInsn(Opcodes.ACONST_NULL);
1435         }
1436         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1437 
1438         classFileEpilogue();
1439         bogusMethod(dstType);
1440 
1441         final byte[] classFile = cw.toByteArray();
1442         maybeDump(className, classFile);
1443         return classFile;
1444     }
1445 
1446     /**
1447      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1448      * for debugging purposes.
1449      */
1450     private void bogusMethod(Object... os) {
1451         if (DUMP_CLASS_FILES) {
1452             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1453             for (Object o : os) {
1454                 mv.visitLdcInsn(o.toString());
1455                 mv.visitInsn(Opcodes.POP);
1456             }
1457             mv.visitInsn(Opcodes.RETURN);
1458             mv.visitMaxs(0, 0);
1459             mv.visitEnd();
1460         }
1461     }
1462 }