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