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