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