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