1 /*
   2  * Copyright (c) 2008, 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.access.JavaLangInvokeAccess;
  29 import jdk.internal.access.SharedSecrets;
  30 import jdk.internal.invoke.NativeEntryPoint;
  31 import jdk.internal.org.objectweb.asm.ClassWriter;
  32 import jdk.internal.org.objectweb.asm.MethodVisitor;
  33 import jdk.internal.reflect.CallerSensitive;
  34 import jdk.internal.reflect.Reflection;
  35 import jdk.internal.vm.annotation.ForceInline;
  36 import jdk.internal.vm.annotation.Hidden;
  37 import jdk.internal.vm.annotation.Stable;
  38 import sun.invoke.empty.Empty;
  39 import sun.invoke.util.ValueConversions;
  40 import sun.invoke.util.VerifyType;
  41 import sun.invoke.util.Wrapper;
  42 
  43 import java.lang.invoke.MethodHandles.Lookup;
  44 import java.lang.reflect.Array;
  45 import java.lang.reflect.Constructor;
  46 import java.lang.reflect.Method;
  47 import java.nio.ByteOrder;
  48 import java.util.Arrays;
  49 import java.util.Collections;
  50 import java.util.HashMap;
  51 import java.util.Iterator;
  52 import java.util.List;
  53 import java.util.Map;
  54 import java.util.Objects;
  55 import java.util.concurrent.ConcurrentHashMap;
  56 import java.util.function.Function;
  57 import java.util.stream.Stream;
  58 
  59 import static java.lang.invoke.LambdaForm.*;
  60 import static java.lang.invoke.MethodHandleStatics.*;
  61 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  62 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  63 
  64 /**
  65  * Trusted implementation code for MethodHandle.
  66  * @author jrose
  67  */
  68 /*non-public*/
  69 abstract class MethodHandleImpl {
  70 
  71     /// Factory methods to create method handles:
  72 
  73     static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, ArrayAccess access) {
  74         if (arrayClass == Object[].class) {
  75             return ArrayAccess.objectAccessor(access);
  76         }
  77         if (!arrayClass.isArray())
  78             throw newIllegalArgumentException("not an array: "+arrayClass);
  79         MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass);
  80         int cacheIndex = ArrayAccess.cacheIndex(access);
  81         MethodHandle mh = cache[cacheIndex];
  82         if (mh != null)  return mh;
  83         mh = ArrayAccessor.getAccessor(arrayClass, access);
  84         MethodType correctType = ArrayAccessor.correctType(arrayClass, access);
  85         if (mh.type() != correctType) {
  86             assert(mh.type().parameterType(0) == Object[].class);
  87             /* if access == SET */ assert(access != ArrayAccess.SET || mh.type().parameterType(2) == Object.class);
  88             /* if access == GET */ assert(access != ArrayAccess.GET ||
  89                     (mh.type().returnType() == Object.class &&
  90                      correctType.parameterType(0).getComponentType() == correctType.returnType()));
  91             // safe to view non-strictly, because element type follows from array type
  92             mh = mh.viewAsType(correctType, false);
  93         }
  94         mh = makeIntrinsic(mh, ArrayAccess.intrinsic(access));
  95         // Atomically update accessor cache.
  96         synchronized(cache) {
  97             if (cache[cacheIndex] == null) {
  98                 cache[cacheIndex] = mh;
  99             } else {
 100                 // Throw away newly constructed accessor and use cached version.
 101                 mh = cache[cacheIndex];
 102             }
 103         }
 104         return mh;
 105     }
 106 
 107     enum ArrayAccess {
 108         GET, SET, LENGTH;
 109 
 110         // As ArrayAccess and ArrayAccessor have a circular dependency, the ArrayAccess properties cannot be stored in
 111         // final fields.
 112 
 113         static String opName(ArrayAccess a) {
 114             return switch (a) {
 115                 case GET    -> "getElement";
 116                 case SET    -> "setElement";
 117                 case LENGTH -> "length";
 118                 default -> throw unmatchedArrayAccess(a);
 119             };
 120         }
 121 
 122         static MethodHandle objectAccessor(ArrayAccess a) {
 123             return switch (a) {
 124                 case GET    -> ArrayAccessor.OBJECT_ARRAY_GETTER;
 125                 case SET    -> ArrayAccessor.OBJECT_ARRAY_SETTER;
 126                 case LENGTH -> ArrayAccessor.OBJECT_ARRAY_LENGTH;
 127                 default -> throw unmatchedArrayAccess(a);
 128             };
 129         }
 130 
 131         static int cacheIndex(ArrayAccess a) {
 132             return switch (a) {
 133                 case GET    -> ArrayAccessor.GETTER_INDEX;
 134                 case SET    -> ArrayAccessor.SETTER_INDEX;
 135                 case LENGTH -> ArrayAccessor.LENGTH_INDEX;
 136                 default -> throw unmatchedArrayAccess(a);
 137             };
 138         }
 139 
 140         static Intrinsic intrinsic(ArrayAccess a) {
 141             return switch (a) {
 142                 case GET    -> Intrinsic.ARRAY_LOAD;
 143                 case SET    -> Intrinsic.ARRAY_STORE;
 144                 case LENGTH -> Intrinsic.ARRAY_LENGTH;
 145                 default -> throw unmatchedArrayAccess(a);
 146             };
 147         }
 148     }
 149 
 150     static InternalError unmatchedArrayAccess(ArrayAccess a) {
 151         return newInternalError("should not reach here (unmatched ArrayAccess: " + a + ")");
 152     }
 153 
 154     static final class ArrayAccessor {
 155         /// Support for array element and length access
 156         static final int GETTER_INDEX = 0, SETTER_INDEX = 1, LENGTH_INDEX = 2, INDEX_LIMIT = 3;
 157         static final ClassValue<MethodHandle[]> TYPED_ACCESSORS
 158                 = new ClassValue<MethodHandle[]>() {
 159                     @Override
 160                     protected MethodHandle[] computeValue(Class<?> type) {
 161                         return new MethodHandle[INDEX_LIMIT];
 162                     }
 163                 };
 164         static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER, OBJECT_ARRAY_LENGTH;
 165         static {
 166             MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class);
 167             cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.GET),    Intrinsic.ARRAY_LOAD);
 168             cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.SET),    Intrinsic.ARRAY_STORE);
 169             cache[LENGTH_INDEX] = OBJECT_ARRAY_LENGTH = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.LENGTH), Intrinsic.ARRAY_LENGTH);
 170 
 171             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName()));
 172             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName()));
 173             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_LENGTH.internalMemberName()));
 174         }
 175 
 176         static int     getElementI(int[]     a, int i)            { return              a[i]; }
 177         static long    getElementJ(long[]    a, int i)            { return              a[i]; }
 178         static float   getElementF(float[]   a, int i)            { return              a[i]; }
 179         static double  getElementD(double[]  a, int i)            { return              a[i]; }
 180         static boolean getElementZ(boolean[] a, int i)            { return              a[i]; }
 181         static byte    getElementB(byte[]    a, int i)            { return              a[i]; }
 182         static short   getElementS(short[]   a, int i)            { return              a[i]; }
 183         static char    getElementC(char[]    a, int i)            { return              a[i]; }
 184         static Object  getElementL(Object[]  a, int i)            { return              a[i]; }
 185 
 186         static void    setElementI(int[]     a, int i, int     x) {              a[i] = x; }
 187         static void    setElementJ(long[]    a, int i, long    x) {              a[i] = x; }
 188         static void    setElementF(float[]   a, int i, float   x) {              a[i] = x; }
 189         static void    setElementD(double[]  a, int i, double  x) {              a[i] = x; }
 190         static void    setElementZ(boolean[] a, int i, boolean x) {              a[i] = x; }
 191         static void    setElementB(byte[]    a, int i, byte    x) {              a[i] = x; }
 192         static void    setElementS(short[]   a, int i, short   x) {              a[i] = x; }
 193         static void    setElementC(char[]    a, int i, char    x) {              a[i] = x; }
 194         static void    setElementL(Object[]  a, int i, Object  x) {              a[i] = x; }
 195 
 196         static int     lengthI(int[]     a)                       { return a.length; }
 197         static int     lengthJ(long[]    a)                       { return a.length; }
 198         static int     lengthF(float[]   a)                       { return a.length; }
 199         static int     lengthD(double[]  a)                       { return a.length; }
 200         static int     lengthZ(boolean[] a)                       { return a.length; }
 201         static int     lengthB(byte[]    a)                       { return a.length; }
 202         static int     lengthS(short[]   a)                       { return a.length; }
 203         static int     lengthC(char[]    a)                       { return a.length; }
 204         static int     lengthL(Object[]  a)                       { return a.length; }
 205 
 206         static String name(Class<?> arrayClass, ArrayAccess access) {
 207             Class<?> elemClass = arrayClass.getComponentType();
 208             if (elemClass == null)  throw newIllegalArgumentException("not an array", arrayClass);
 209             return ArrayAccess.opName(access) + Wrapper.basicTypeChar(elemClass);
 210         }
 211         static MethodType type(Class<?> arrayClass, ArrayAccess access) {
 212             Class<?> elemClass = arrayClass.getComponentType();
 213             Class<?> arrayArgClass = arrayClass;
 214             if (!elemClass.isPrimitive()) {
 215                 arrayArgClass = Object[].class;
 216                 elemClass = Object.class;
 217             }
 218             return switch (access) {
 219                 case GET    -> MethodType.methodType(elemClass, arrayArgClass, int.class);
 220                 case SET    -> MethodType.methodType(void.class, arrayArgClass, int.class, elemClass);
 221                 case LENGTH -> MethodType.methodType(int.class, arrayArgClass);
 222                 default -> throw unmatchedArrayAccess(access);
 223             };
 224         }
 225         static MethodType correctType(Class<?> arrayClass, ArrayAccess access) {
 226             Class<?> elemClass = arrayClass.getComponentType();
 227             return switch (access) {
 228                 case GET    -> MethodType.methodType(elemClass, arrayClass, int.class);
 229                 case SET    -> MethodType.methodType(void.class, arrayClass, int.class, elemClass);
 230                 case LENGTH -> MethodType.methodType(int.class, arrayClass);
 231                 default -> throw unmatchedArrayAccess(access);
 232             };
 233         }
 234         static MethodHandle getAccessor(Class<?> arrayClass, ArrayAccess access) {
 235             String     name = name(arrayClass, access);
 236             MethodType type = type(arrayClass, access);
 237             try {
 238                 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type);
 239             } catch (ReflectiveOperationException ex) {
 240                 throw uncaughtException(ex);
 241             }
 242         }
 243     }
 244 
 245     /**
 246      * Create a JVM-level adapter method handle to conform the given method
 247      * handle to the similar newType, using only pairwise argument conversions.
 248      * For each argument, convert incoming argument to the exact type needed.
 249      * The argument conversions allowed are casting, boxing and unboxing,
 250      * integral widening or narrowing, and floating point widening or narrowing.
 251      * @param srcType required call type
 252      * @param target original method handle
 253      * @param strict if true, only asType conversions are allowed; if false, explicitCastArguments conversions allowed
 254      * @param monobox if true, unboxing conversions are assumed to be exactly typed (Integer to int only, not long or double)
 255      * @return an adapter to the original handle with the desired new type,
 256      *          or the original target if the types are already identical
 257      *          or null if the adaptation cannot be made
 258      */
 259     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 260                                             boolean strict, boolean monobox) {
 261         MethodType dstType = target.type();
 262         if (srcType == dstType)
 263             return target;
 264         return makePairwiseConvertByEditor(target, srcType, strict, monobox);
 265     }
 266 
 267     private static int countNonNull(Object[] array) {
 268         int count = 0;
 269         if (array != null) {
 270             for (Object x : array) {
 271                 if (x != null) ++count;
 272             }
 273         }
 274         return count;
 275     }
 276 
 277     static MethodHandle makePairwiseConvertByEditor(MethodHandle target, MethodType srcType,
 278                                                     boolean strict, boolean monobox) {
 279         // In method types arguments start at index 0, while the LF
 280         // editor have the MH receiver at position 0 - adjust appropriately.
 281         final int MH_RECEIVER_OFFSET = 1;
 282         Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox);
 283         int convCount = countNonNull(convSpecs);
 284         if (convCount == 0)
 285             return target.viewAsType(srcType, strict);
 286         MethodType basicSrcType = srcType.basicType();
 287         MethodType midType = target.type().basicType();
 288         BoundMethodHandle mh = target.rebind();
 289 
 290         // Match each unique conversion to the positions at which it is to be applied
 291         var convSpecMap = new HashMap<Object, int[]>(((4 * convCount) / 3) + 1);
 292         for (int i = 0; i < convSpecs.length - MH_RECEIVER_OFFSET; i++) {
 293             Object convSpec = convSpecs[i];
 294             if (convSpec == null) continue;
 295             int[] positions = convSpecMap.get(convSpec);
 296             if (positions == null) {
 297                 positions = new int[] { i + MH_RECEIVER_OFFSET };
 298             } else {
 299                 positions = Arrays.copyOf(positions, positions.length + 1);
 300                 positions[positions.length - 1] = i + MH_RECEIVER_OFFSET;
 301             }
 302             convSpecMap.put(convSpec, positions);
 303         }
 304         for (var entry : convSpecMap.entrySet()) {
 305             Object convSpec = entry.getKey();
 306 
 307             MethodHandle fn;
 308             if (convSpec instanceof Class) {
 309                 fn = getConstantHandle(MH_cast).bindTo(convSpec);
 310             } else {
 311                 fn = (MethodHandle) convSpec;
 312             }
 313             int[] positions = entry.getValue();
 314             Class<?> newType = basicSrcType.parameterType(positions[0] - MH_RECEIVER_OFFSET);
 315             BasicType newBasicType = BasicType.basicType(newType);
 316             convCount -= positions.length;
 317             if (convCount == 0) {
 318                 midType = srcType;
 319             } else {
 320                 Class<?>[] ptypes = midType.ptypes().clone();
 321                 for (int pos : positions) {
 322                     ptypes[pos - 1] = newType;
 323                 }
 324                 midType = MethodType.makeImpl(midType.rtype(), ptypes, true);
 325             }
 326             LambdaForm form2;
 327             if (positions.length > 1) {
 328                 form2 = mh.editor().filterRepeatedArgumentForm(newBasicType, positions);
 329             } else {
 330                 form2 = mh.editor().filterArgumentForm(positions[0], newBasicType);
 331             }
 332             mh = mh.copyWithExtendL(midType, form2, fn);
 333         }
 334         Object convSpec = convSpecs[convSpecs.length - 1];
 335         if (convSpec != null) {
 336             MethodHandle fn;
 337             if (convSpec instanceof Class) {
 338                 if (convSpec == void.class)
 339                     fn = null;
 340                 else
 341                     fn = getConstantHandle(MH_cast).bindTo(convSpec);
 342             } else {
 343                 fn = (MethodHandle) convSpec;
 344             }
 345             Class<?> newType = basicSrcType.returnType();
 346             assert(--convCount == 0);
 347             midType = srcType;
 348             if (fn != null) {
 349                 mh = mh.rebind();  // rebind if too complex
 350                 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), false);
 351                 mh = mh.copyWithExtendL(midType, form2, fn);
 352             } else {
 353                 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), true);
 354                 mh = mh.copyWith(midType, form2);
 355             }
 356         }
 357         assert(convCount == 0);
 358         assert(mh.type().equals(srcType));
 359         return mh;
 360     }
 361 
 362     static Object[] computeValueConversions(MethodType srcType, MethodType dstType,
 363                                             boolean strict, boolean monobox) {
 364         final int INARG_COUNT = srcType.parameterCount();
 365         Object[] convSpecs = null;
 366         for (int i = 0; i <= INARG_COUNT; i++) {
 367             boolean isRet = (i == INARG_COUNT);
 368             Class<?> src = isRet ? dstType.returnType() : srcType.parameterType(i);
 369             Class<?> dst = isRet ? srcType.returnType() : dstType.parameterType(i);
 370             if (!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)) {
 371                 if (convSpecs == null) {
 372                     convSpecs = new Object[INARG_COUNT + 1];
 373                 }
 374                 convSpecs[i] = valueConversion(src, dst, strict, monobox);
 375             }
 376         }
 377         return convSpecs;
 378     }
 379     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 380                                             boolean strict) {
 381         return makePairwiseConvert(target, srcType, strict, /*monobox=*/ false);
 382     }
 383 
 384     /**
 385      * Find a conversion function from the given source to the given destination.
 386      * This conversion function will be used as a LF NamedFunction.
 387      * Return a Class object if a simple cast is needed.
 388      * Return void.class if void is involved.
 389      */
 390     static Object valueConversion(Class<?> src, Class<?> dst, boolean strict, boolean monobox) {
 391         assert(!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict));  // caller responsibility
 392         if (dst == void.class)
 393             return dst;
 394         MethodHandle fn;
 395         if (src.isPrimitive()) {
 396             if (src == void.class) {
 397                 return void.class;  // caller must recognize this specially
 398             } else if (dst.isPrimitive()) {
 399                 // Examples: int->byte, byte->int, boolean->int (!strict)
 400                 fn = ValueConversions.convertPrimitive(src, dst);
 401             } else {
 402                 // Examples: int->Integer, boolean->Object, float->Number
 403                 Wrapper wsrc = Wrapper.forPrimitiveType(src);
 404                 fn = ValueConversions.boxExact(wsrc);
 405                 assert(fn.type().parameterType(0) == wsrc.primitiveType());
 406                 assert(fn.type().returnType() == wsrc.wrapperType());
 407                 if (!VerifyType.isNullConversion(wsrc.wrapperType(), dst, strict)) {
 408                     // Corner case, such as int->Long, which will probably fail.
 409                     MethodType mt = MethodType.methodType(dst, src);
 410                     if (strict)
 411                         fn = fn.asType(mt);
 412                     else
 413                         fn = MethodHandleImpl.makePairwiseConvert(fn, mt, /*strict=*/ false);
 414                 }
 415             }
 416         } else if (dst.isPrimitive()) {
 417             Wrapper wdst = Wrapper.forPrimitiveType(dst);
 418             if (monobox || src == wdst.wrapperType()) {
 419                 // Use a strongly-typed unboxer, if possible.
 420                 fn = ValueConversions.unboxExact(wdst, strict);
 421             } else {
 422                 // Examples:  Object->int, Number->int, Comparable->int, Byte->int
 423                 // must include additional conversions
 424                 // src must be examined at runtime, to detect Byte, Character, etc.
 425                 fn = (strict
 426                         ? ValueConversions.unboxWiden(wdst)
 427                         : ValueConversions.unboxCast(wdst));
 428             }
 429         } else {
 430             // Simple reference conversion.
 431             // Note:  Do not check for a class hierarchy relation
 432             // between src and dst.  In all cases a 'null' argument
 433             // will pass the cast conversion.
 434             return dst;
 435         }
 436         assert(fn.type().parameterCount() <= 1) : "pc"+Arrays.asList(src.getSimpleName(), dst.getSimpleName(), fn);
 437         return fn;
 438     }
 439 
 440     static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) {
 441         MethodType type = target.type();
 442         int last = type.parameterCount() - 1;
 443         if (type.parameterType(last) != arrayType)
 444             target = target.asType(type.changeParameterType(last, arrayType));
 445         target = target.asFixedArity();  // make sure this attribute is turned off
 446         return new AsVarargsCollector(target, arrayType);
 447     }
 448 
 449     private static final class AsVarargsCollector extends DelegatingMethodHandle {
 450         private final MethodHandle target;
 451         private final Class<?> arrayType;
 452         private @Stable MethodHandle asCollectorCache;
 453 
 454         AsVarargsCollector(MethodHandle target, Class<?> arrayType) {
 455             this(target.type(), target, arrayType);
 456         }
 457         AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) {
 458             super(type, target);
 459             this.target = target;
 460             this.arrayType = arrayType;
 461         }
 462 
 463         @Override
 464         public boolean isVarargsCollector() {
 465             return true;
 466         }
 467 
 468         @Override
 469         protected MethodHandle getTarget() {
 470             return target;
 471         }
 472 
 473         @Override
 474         public MethodHandle asFixedArity() {
 475             return target;
 476         }
 477 
 478         @Override
 479         MethodHandle setVarargs(MemberName member) {
 480             if (member.isVarargs())  return this;
 481             return asFixedArity();
 482         }
 483 
 484         @Override
 485         public MethodHandle withVarargs(boolean makeVarargs) {
 486             if (makeVarargs)  return this;
 487             return asFixedArity();
 488         }
 489 
 490         @Override
 491         public MethodHandle asTypeUncached(MethodType newType) {
 492             MethodType type = this.type();
 493             int collectArg = type.parameterCount() - 1;
 494             int newArity = newType.parameterCount();
 495             if (newArity == collectArg+1 &&
 496                 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
 497                 // if arity and trailing parameter are compatible, do normal thing
 498                 return asFixedArity().asType(newType);
 499             }
 500             // check cache
 501             MethodHandle acc = asCollectorCache;
 502             if (acc != null && acc.type().parameterCount() == newArity)
 503                 return acc.asType(newType);
 504             // build and cache a collector
 505             int arrayLength = newArity - collectArg;
 506             MethodHandle collector;
 507             try {
 508                 collector = asFixedArity().asCollector(arrayType, arrayLength);
 509                 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector;
 510             } catch (IllegalArgumentException ex) {
 511                 throw new WrongMethodTypeException("cannot build collector", ex);
 512             }
 513             asCollectorCache = collector;
 514             return collector.asType(newType);
 515         }
 516 
 517         @Override
 518         boolean viewAsTypeChecks(MethodType newType, boolean strict) {
 519             super.viewAsTypeChecks(newType, true);
 520             if (strict) return true;
 521             // extra assertion for non-strict checks:
 522             assert (type().lastParameterType().getComponentType()
 523                     .isAssignableFrom(
 524                             newType.lastParameterType().getComponentType()))
 525                     : Arrays.asList(this, newType);
 526             return true;
 527         }
 528 
 529         @Override
 530         public Object invokeWithArguments(Object... arguments) throws Throwable {
 531             MethodType type = this.type();
 532             int argc;
 533             final int MAX_SAFE = 127;  // 127 longs require 254 slots, which is safe to spread
 534             if (arguments == null
 535                     || (argc = arguments.length) <= MAX_SAFE
 536                     || argc < type.parameterCount()) {
 537                 return super.invokeWithArguments(arguments);
 538             }
 539 
 540             // a jumbo invocation requires more explicit reboxing of the trailing arguments
 541             int uncollected = type.parameterCount() - 1;
 542             Class<?> elemType = arrayType.getComponentType();
 543             int collected = argc - uncollected;
 544             Object collArgs = (elemType == Object.class)
 545                 ? new Object[collected] : Array.newInstance(elemType, collected);
 546             if (!elemType.isPrimitive()) {
 547                 // simple cast:  just do some casting
 548                 try {
 549                     System.arraycopy(arguments, uncollected, collArgs, 0, collected);
 550                 } catch (ArrayStoreException ex) {
 551                     return super.invokeWithArguments(arguments);
 552                 }
 553             } else {
 554                 // corner case of flat array requires reflection (or specialized copy loop)
 555                 MethodHandle arraySetter = MethodHandles.arrayElementSetter(arrayType);
 556                 try {
 557                     for (int i = 0; i < collected; i++) {
 558                         arraySetter.invoke(collArgs, i, arguments[uncollected + i]);
 559                     }
 560                 } catch (WrongMethodTypeException|ClassCastException ex) {
 561                     return super.invokeWithArguments(arguments);
 562                 }
 563             }
 564 
 565             // chop the jumbo list down to size and call in non-varargs mode
 566             Object[] newArgs = new Object[uncollected + 1];
 567             System.arraycopy(arguments, 0, newArgs, 0, uncollected);
 568             newArgs[uncollected] = collArgs;
 569             return asFixedArity().invokeWithArguments(newArgs);
 570         }
 571     }
 572 
 573     static void checkSpreadArgument(Object av, int n) {
 574         if (av == null && n == 0) {
 575             return;
 576         } else if (av == null) {
 577             throw new NullPointerException("null array reference");
 578         } else if (av instanceof Object[]) {
 579             int len = ((Object[])av).length;
 580             if (len == n)  return;
 581         } else {
 582             int len = java.lang.reflect.Array.getLength(av);
 583             if (len == n)  return;
 584         }
 585         // fall through to error:
 586         throw newIllegalArgumentException("array is not of length "+n);
 587     }
 588 
 589     @Hidden
 590     static MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
 591         if (testResult) {
 592             return target;
 593         } else {
 594             return fallback;
 595         }
 596     }
 597 
 598     // Intrinsified by C2. Counters are used during parsing to calculate branch frequencies.
 599     @Hidden
 600     @jdk.internal.vm.annotation.IntrinsicCandidate
 601     static boolean profileBoolean(boolean result, int[] counters) {
 602         // Profile is int[2] where [0] and [1] correspond to false and true occurrences respectively.
 603         int idx = result ? 1 : 0;
 604         try {
 605             counters[idx] = Math.addExact(counters[idx], 1);
 606         } catch (ArithmeticException e) {
 607             // Avoid continuous overflow by halving the problematic count.
 608             counters[idx] = counters[idx] / 2;
 609         }
 610         return result;
 611     }
 612 
 613     // Intrinsified by C2. Returns true if obj is a compile-time constant.
 614     @Hidden
 615     @jdk.internal.vm.annotation.IntrinsicCandidate
 616     static boolean isCompileConstant(Object obj) {
 617         return false;
 618     }
 619 
 620     static MethodHandle makeGuardWithTest(MethodHandle test,
 621                                    MethodHandle target,
 622                                    MethodHandle fallback) {
 623         MethodType type = target.type();
 624         assert(test.type().equals(type.changeReturnType(boolean.class)) && fallback.type().equals(type));
 625         MethodType basicType = type.basicType();
 626         LambdaForm form = makeGuardWithTestForm(basicType);
 627         BoundMethodHandle mh;
 628         try {
 629             if (PROFILE_GWT) {
 630                 int[] counts = new int[2];
 631                 mh = (BoundMethodHandle)
 632                         BoundMethodHandle.speciesData_LLLL().factory().invokeBasic(type, form,
 633                                 (Object) test, (Object) profile(target), (Object) profile(fallback), counts);
 634             } else {
 635                 mh = (BoundMethodHandle)
 636                         BoundMethodHandle.speciesData_LLL().factory().invokeBasic(type, form,
 637                                 (Object) test, (Object) profile(target), (Object) profile(fallback));
 638             }
 639         } catch (Throwable ex) {
 640             throw uncaughtException(ex);
 641         }
 642         assert(mh.type() == type);
 643         return mh;
 644     }
 645 
 646 
 647     static MethodHandle profile(MethodHandle target) {
 648         if (DONT_INLINE_THRESHOLD >= 0) {
 649             return makeBlockInliningWrapper(target);
 650         } else {
 651             return target;
 652         }
 653     }
 654 
 655     /**
 656      * Block inlining during JIT-compilation of a target method handle if it hasn't been invoked enough times.
 657      * Corresponding LambdaForm has @DontInline when compiled into bytecode.
 658      */
 659     static MethodHandle makeBlockInliningWrapper(MethodHandle target) {
 660         LambdaForm lform;
 661         if (DONT_INLINE_THRESHOLD > 0) {
 662             lform = Makers.PRODUCE_BLOCK_INLINING_FORM.apply(target);
 663         } else {
 664             lform = Makers.PRODUCE_REINVOKER_FORM.apply(target);
 665         }
 666         return new CountingWrapper(target, lform,
 667                 Makers.PRODUCE_BLOCK_INLINING_FORM, Makers.PRODUCE_REINVOKER_FORM,
 668                                    DONT_INLINE_THRESHOLD);
 669     }
 670 
 671     private static final class Makers {
 672         /** Constructs reinvoker lambda form which block inlining during JIT-compilation for a particular method handle */
 673         static final Function<MethodHandle, LambdaForm> PRODUCE_BLOCK_INLINING_FORM = new Function<MethodHandle, LambdaForm>() {
 674             @Override
 675             public LambdaForm apply(MethodHandle target) {
 676                 return DelegatingMethodHandle.makeReinvokerForm(target,
 677                                    MethodTypeForm.LF_DELEGATE_BLOCK_INLINING, CountingWrapper.class, false,
 678                                    DelegatingMethodHandle.NF_getTarget, CountingWrapper.NF_maybeStopCounting);
 679             }
 680         };
 681 
 682         /** Constructs simple reinvoker lambda form for a particular method handle */
 683         static final Function<MethodHandle, LambdaForm> PRODUCE_REINVOKER_FORM = new Function<MethodHandle, LambdaForm>() {
 684             @Override
 685             public LambdaForm apply(MethodHandle target) {
 686                 return DelegatingMethodHandle.makeReinvokerForm(target,
 687                         MethodTypeForm.LF_DELEGATE, DelegatingMethodHandle.class, DelegatingMethodHandle.NF_getTarget);
 688             }
 689         };
 690 
 691         /** Maker of type-polymorphic varargs */
 692         static final ClassValue<MethodHandle[]> TYPED_COLLECTORS = new ClassValue<MethodHandle[]>() {
 693             @Override
 694             protected MethodHandle[] computeValue(Class<?> type) {
 695                 return new MethodHandle[MAX_JVM_ARITY + 1];
 696             }
 697         };
 698     }
 699 
 700     /**
 701      * Counting method handle. It has 2 states: counting and non-counting.
 702      * It is in counting state for the first n invocations and then transitions to non-counting state.
 703      * Behavior in counting and non-counting states is determined by lambda forms produced by
 704      * countingFormProducer & nonCountingFormProducer respectively.
 705      */
 706     static class CountingWrapper extends DelegatingMethodHandle {
 707         private final MethodHandle target;
 708         private int count;
 709         private Function<MethodHandle, LambdaForm> countingFormProducer;
 710         private Function<MethodHandle, LambdaForm> nonCountingFormProducer;
 711         private volatile boolean isCounting;
 712 
 713         private CountingWrapper(MethodHandle target, LambdaForm lform,
 714                                 Function<MethodHandle, LambdaForm> countingFromProducer,
 715                                 Function<MethodHandle, LambdaForm> nonCountingFormProducer,
 716                                 int count) {
 717             super(target.type(), lform);
 718             this.target = target;
 719             this.count = count;
 720             this.countingFormProducer = countingFromProducer;
 721             this.nonCountingFormProducer = nonCountingFormProducer;
 722             this.isCounting = (count > 0);
 723         }
 724 
 725         @Hidden
 726         @Override
 727         protected MethodHandle getTarget() {
 728             return target;
 729         }
 730 
 731         @Override
 732         public MethodHandle asTypeUncached(MethodType newType) {
 733             MethodHandle newTarget = target.asType(newType);
 734             MethodHandle wrapper;
 735             if (isCounting) {
 736                 LambdaForm lform;
 737                 lform = countingFormProducer.apply(newTarget);
 738                 wrapper = new CountingWrapper(newTarget, lform, countingFormProducer, nonCountingFormProducer, DONT_INLINE_THRESHOLD);
 739             } else {
 740                 wrapper = newTarget; // no need for a counting wrapper anymore
 741             }
 742             return wrapper;
 743         }
 744 
 745         boolean countDown() {
 746             int c = count;
 747             target.maybeCustomize(); // customize if counting happens for too long
 748             if (c <= 1) {
 749                 // Try to limit number of updates. MethodHandle.updateForm() doesn't guarantee LF update visibility.
 750                 if (isCounting) {
 751                     isCounting = false;
 752                     return true;
 753                 } else {
 754                     return false;
 755                 }
 756             } else {
 757                 count = c - 1;
 758                 return false;
 759             }
 760         }
 761 
 762         @Hidden
 763         static void maybeStopCounting(Object o1) {
 764              final CountingWrapper wrapper = (CountingWrapper) o1;
 765              if (wrapper.countDown()) {
 766                  // Reached invocation threshold. Replace counting behavior with a non-counting one.
 767                  wrapper.updateForm(new Function<>() {
 768                      public LambdaForm apply(LambdaForm oldForm) {
 769                          LambdaForm lform = wrapper.nonCountingFormProducer.apply(wrapper.target);
 770                          lform.compileToBytecode(); // speed up warmup by avoiding LF interpretation again after transition
 771                          return lform;
 772                      }});
 773              }
 774         }
 775 
 776         static final NamedFunction NF_maybeStopCounting;
 777         static {
 778             Class<?> THIS_CLASS = CountingWrapper.class;
 779             try {
 780                 NF_maybeStopCounting = new NamedFunction(THIS_CLASS.getDeclaredMethod("maybeStopCounting", Object.class));
 781             } catch (ReflectiveOperationException ex) {
 782                 throw newInternalError(ex);
 783             }
 784         }
 785     }
 786 
 787     static LambdaForm makeGuardWithTestForm(MethodType basicType) {
 788         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWT);
 789         if (lform != null)  return lform;
 790         final int THIS_MH      = 0;  // the BMH_LLL
 791         final int ARG_BASE     = 1;  // start of incoming arguments
 792         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 793         int nameCursor = ARG_LIMIT;
 794         final int GET_TEST     = nameCursor++;
 795         final int GET_TARGET   = nameCursor++;
 796         final int GET_FALLBACK = nameCursor++;
 797         final int GET_COUNTERS = PROFILE_GWT ? nameCursor++ : -1;
 798         final int CALL_TEST    = nameCursor++;
 799         final int PROFILE      = (GET_COUNTERS != -1) ? nameCursor++ : -1;
 800         final int TEST         = nameCursor-1; // previous statement: either PROFILE or CALL_TEST
 801         final int SELECT_ALT   = nameCursor++;
 802         final int CALL_TARGET  = nameCursor++;
 803         assert(CALL_TARGET == SELECT_ALT+1);  // must be true to trigger IBG.emitSelectAlternative
 804 
 805         MethodType lambdaType = basicType.invokerType();
 806         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 807 
 808         BoundMethodHandle.SpeciesData data =
 809                 (GET_COUNTERS != -1) ? BoundMethodHandle.speciesData_LLLL()
 810                                      : BoundMethodHandle.speciesData_LLL();
 811         names[THIS_MH] = names[THIS_MH].withConstraint(data);
 812         names[GET_TEST]     = new Name(data.getterFunction(0), names[THIS_MH]);
 813         names[GET_TARGET]   = new Name(data.getterFunction(1), names[THIS_MH]);
 814         names[GET_FALLBACK] = new Name(data.getterFunction(2), names[THIS_MH]);
 815         if (GET_COUNTERS != -1) {
 816             names[GET_COUNTERS] = new Name(data.getterFunction(3), names[THIS_MH]);
 817         }
 818         Object[] invokeArgs = Arrays.copyOfRange(names, 0, ARG_LIMIT, Object[].class);
 819 
 820         // call test
 821         MethodType testType = basicType.changeReturnType(boolean.class).basicType();
 822         invokeArgs[0] = names[GET_TEST];
 823         names[CALL_TEST] = new Name(testType, invokeArgs);
 824 
 825         // profile branch
 826         if (PROFILE != -1) {
 827             names[PROFILE] = new Name(getFunction(NF_profileBoolean), names[CALL_TEST], names[GET_COUNTERS]);
 828         }
 829         // call selectAlternative
 830         names[SELECT_ALT] = new Name(new NamedFunction(
 831                 makeIntrinsic(getConstantHandle(MH_selectAlternative), Intrinsic.SELECT_ALTERNATIVE)),
 832                 names[TEST], names[GET_TARGET], names[GET_FALLBACK]);
 833 
 834         // call target or fallback
 835         invokeArgs[0] = names[SELECT_ALT];
 836         names[CALL_TARGET] = new Name(basicType, invokeArgs);
 837 
 838         lform = new LambdaForm(lambdaType.parameterCount(), names, /*forceInline=*/true, Kind.GUARD);
 839 
 840         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWT, lform);
 841     }
 842 
 843     /**
 844      * The LambdaForm shape for catchException combinator is the following:
 845      * <blockquote><pre>{@code
 846      *  guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{
 847      *    t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L);
 848      *    t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L);
 849      *    t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L);
 850      *    t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L);
 851      *    t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L);
 852      *    t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L);
 853      *    t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L);
 854      *   t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I}
 855      * }</pre></blockquote>
 856      *
 857      * argL0 and argL2 are target and catcher method handles. argL1 is exception class.
 858      * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[]
 859      * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()).
 860      *
 861      * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms
 862      * among catchException combinators with the same basic type.
 863      */
 864     private static LambdaForm makeGuardWithCatchForm(MethodType basicType) {
 865         MethodType lambdaType = basicType.invokerType();
 866 
 867         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC);
 868         if (lform != null) {
 869             return lform;
 870         }
 871         final int THIS_MH      = 0;  // the BMH_LLLLL
 872         final int ARG_BASE     = 1;  // start of incoming arguments
 873         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 874 
 875         int nameCursor = ARG_LIMIT;
 876         final int GET_TARGET       = nameCursor++;
 877         final int GET_CLASS        = nameCursor++;
 878         final int GET_CATCHER      = nameCursor++;
 879         final int GET_COLLECT_ARGS = nameCursor++;
 880         final int GET_UNBOX_RESULT = nameCursor++;
 881         final int BOXED_ARGS       = nameCursor++;
 882         final int TRY_CATCH        = nameCursor++;
 883         final int UNBOX_RESULT     = nameCursor++;
 884 
 885         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 886 
 887         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 888         names[THIS_MH]          = names[THIS_MH].withConstraint(data);
 889         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
 890         names[GET_CLASS]        = new Name(data.getterFunction(1), names[THIS_MH]);
 891         names[GET_CATCHER]      = new Name(data.getterFunction(2), names[THIS_MH]);
 892         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]);
 893         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]);
 894 
 895         // FIXME: rework argument boxing/result unboxing logic for LF interpretation
 896 
 897         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
 898         MethodType collectArgsType = basicType.changeReturnType(Object.class);
 899         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
 900         Object[] args = new Object[invokeBasic.type().parameterCount()];
 901         args[0] = names[GET_COLLECT_ARGS];
 902         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
 903         names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.GUARD_WITH_CATCH)), args);
 904 
 905         // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L);
 906         Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]};
 907         names[TRY_CATCH] = new Name(getFunction(NF_guardWithCatch), gwcArgs);
 908 
 909         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
 910         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
 911         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]};
 912         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
 913 
 914         lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.GUARD_WITH_CATCH);
 915 
 916         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform);
 917     }
 918 
 919     static MethodHandle makeGuardWithCatch(MethodHandle target,
 920                                     Class<? extends Throwable> exType,
 921                                     MethodHandle catcher) {
 922         MethodType type = target.type();
 923         LambdaForm form = makeGuardWithCatchForm(type.basicType());
 924 
 925         // Prepare auxiliary method handles used during LambdaForm interpretation.
 926         // Box arguments and wrap them into Object[]: ValueConversions.array().
 927         MethodType varargsType = type.changeReturnType(Object[].class);
 928         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
 929         MethodHandle unboxResult = unboxResultHandle(type.returnType());
 930 
 931         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 932         BoundMethodHandle mh;
 933         try {
 934             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) target, (Object) exType,
 935                     (Object) catcher, (Object) collectArgs, (Object) unboxResult);
 936         } catch (Throwable ex) {
 937             throw uncaughtException(ex);
 938         }
 939         assert(mh.type() == type);
 940         return mh;
 941     }
 942 
 943     /**
 944      * Intrinsified during LambdaForm compilation
 945      * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}).
 946      */
 947     @Hidden
 948     static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher,
 949                                  Object... av) throws Throwable {
 950         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
 951         try {
 952             return target.asFixedArity().invokeWithArguments(av);
 953         } catch (Throwable t) {
 954             if (!exType.isInstance(t)) throw t;
 955             return catcher.asFixedArity().invokeWithArguments(prepend(av, t));
 956         }
 957     }
 958 
 959     /** Prepend elements to an array. */
 960     @Hidden
 961     private static Object[] prepend(Object[] array, Object... elems) {
 962         int nArray = array.length;
 963         int nElems = elems.length;
 964         Object[] newArray = new Object[nArray + nElems];
 965         System.arraycopy(elems, 0, newArray, 0, nElems);
 966         System.arraycopy(array, 0, newArray, nElems, nArray);
 967         return newArray;
 968     }
 969 
 970     static MethodHandle throwException(MethodType type) {
 971         assert(Throwable.class.isAssignableFrom(type.parameterType(0)));
 972         int arity = type.parameterCount();
 973         if (arity > 1) {
 974             MethodHandle mh = throwException(type.dropParameterTypes(1, arity));
 975             mh = MethodHandles.dropArguments(mh, 1, Arrays.copyOfRange(type.parameterArray(), 1, arity));
 976             return mh;
 977         }
 978         return makePairwiseConvert(getFunction(NF_throwException).resolvedHandle(), type, false, true);
 979     }
 980 
 981     static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
 982 
 983     static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2];
 984     static MethodHandle fakeMethodHandleInvoke(MemberName method) {
 985         assert(method.isMethodHandleInvoke());
 986         int idx = switch (method.getName()) {
 987             case "invoke"      -> 0;
 988             case "invokeExact" -> 1;
 989             default -> throw new InternalError(method.getName());
 990         };
 991         MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx];
 992         if (mh != null)  return mh;
 993         MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class,
 994                                                 MethodHandle.class, Object[].class);
 995         mh = throwException(type);
 996         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle"));
 997         if (!method.getInvocationType().equals(mh.type()))
 998             throw new InternalError(method.toString());
 999         mh = mh.withInternalMemberName(method, false);
1000         mh = mh.withVarargs(true);
1001         assert(method.isVarargs());
1002         FAKE_METHOD_HANDLE_INVOKE[idx] = mh;
1003         return mh;
1004     }
1005     static MethodHandle fakeVarHandleInvoke(MemberName method) {
1006         // TODO caching, is it necessary?
1007         MethodType type = MethodType.methodType(method.getReturnType(), UnsupportedOperationException.class,
1008                                                 VarHandle.class, Object[].class);
1009         MethodHandle mh = throwException(type);
1010         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke VarHandle"));
1011         if (!method.getInvocationType().equals(mh.type()))
1012             throw new InternalError(method.toString());
1013         mh = mh.withInternalMemberName(method, false);
1014         mh = mh.asVarargsCollector(Object[].class);
1015         assert(method.isVarargs());
1016         return mh;
1017     }
1018 
1019     /**
1020      * Create an alias for the method handle which, when called,
1021      * appears to be called from the same class loader and protection domain
1022      * as hostClass.
1023      * This is an expensive no-op unless the method which is called
1024      * is sensitive to its caller.  A small number of system methods
1025      * are in this category, including Class.forName and Method.invoke.
1026      */
1027     static MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
1028         return BindCaller.bindCaller(mh, hostClass);
1029     }
1030 
1031     // Put the whole mess into its own nested class.
1032     // That way we can lazily load the code and set up the constants.
1033     private static class BindCaller {
1034         private static MethodType INVOKER_MT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1035 
1036         static MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
1037             // Code in the boot layer should now be careful while creating method handles or
1038             // functional interface instances created from method references to @CallerSensitive  methods,
1039             // it needs to be ensured the handles or interface instances are kept safe and are not passed
1040             // from the boot layer to untrusted code.
1041             if (hostClass == null
1042                 ||    (hostClass.isArray() ||
1043                        hostClass.isPrimitive() ||
1044                        hostClass.getName().startsWith("java.lang.invoke."))) {
1045                 throw new InternalError();  // does not happen, and should not anyway
1046             }
1047             // For simplicity, convert mh to a varargs-like method.
1048             MethodHandle vamh = prepareForInvoker(mh);
1049             // Cache the result of makeInjectedInvoker once per argument class.
1050             MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
1051             return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass);
1052         }
1053 
1054         private static MethodHandle makeInjectedInvoker(Class<?> targetClass) {
1055             try {
1056                 /*
1057                  * The invoker class defined to the same class loader as the lookup class
1058                  * but in an unnamed package so that the class bytes can be cached and
1059                  * reused for any @CSM.
1060                  *
1061                  * @CSM must be public and exported if called by any module.
1062                  */
1063                 String name = targetClass.getName() + "$$InjectedInvoker";
1064                 if (targetClass.isHidden()) {
1065                     // use the original class name
1066                     name = name.replace('/', '_');
1067                 }
1068                 Class<?> invokerClass = new Lookup(targetClass)
1069                         .makeHiddenClassDefiner(name, INJECTED_INVOKER_TEMPLATE)
1070                         .defineClass(true);
1071                 assert checkInjectedInvoker(targetClass, invokerClass);
1072                 return IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT);
1073             } catch (ReflectiveOperationException ex) {
1074                 throw uncaughtException(ex);
1075             }
1076         }
1077 
1078         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
1079             @Override protected MethodHandle computeValue(Class<?> hostClass) {
1080                 return makeInjectedInvoker(hostClass);
1081             }
1082         };
1083 
1084         // Adapt mh so that it can be called directly from an injected invoker:
1085         private static MethodHandle prepareForInvoker(MethodHandle mh) {
1086             mh = mh.asFixedArity();
1087             MethodType mt = mh.type();
1088             int arity = mt.parameterCount();
1089             MethodHandle vamh = mh.asType(mt.generic());
1090             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
1091             vamh = vamh.asSpreader(Object[].class, arity);
1092             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
1093             return vamh;
1094         }
1095 
1096         // Undo the adapter effect of prepareForInvoker:
1097         private static MethodHandle restoreToType(MethodHandle vamh,
1098                                                   MethodHandle original,
1099                                                   Class<?> hostClass) {
1100             MethodType type = original.type();
1101             MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount());
1102             MemberName member = original.internalMemberName();
1103             mh = mh.asType(type);
1104             mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass);
1105             return mh;
1106         }
1107 
1108         private static boolean checkInjectedInvoker(Class<?> hostClass, Class<?> invokerClass) {
1109             assert (hostClass.getClassLoader() == invokerClass.getClassLoader()) : hostClass.getName()+" (CL)";
1110             try {
1111                 assert (hostClass.getProtectionDomain() == invokerClass.getProtectionDomain()) : hostClass.getName()+" (PD)";
1112             } catch (SecurityException ex) {
1113                 // Self-check was blocked by security manager. This is OK.
1114             }
1115             try {
1116                 // Test the invoker to ensure that it really injects into the right place.
1117                 MethodHandle invoker = IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT);
1118                 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
1119                 return (boolean)invoker.invoke(vamh, new Object[]{ invokerClass });
1120             } catch (Throwable ex) {
1121                 throw new InternalError(ex);
1122             }
1123         }
1124 
1125         private static final MethodHandle MH_checkCallerClass;
1126         static {
1127             final Class<?> THIS_CLASS = BindCaller.class;
1128             assert(checkCallerClass(THIS_CLASS));
1129             try {
1130                 MH_checkCallerClass = IMPL_LOOKUP
1131                     .findStatic(THIS_CLASS, "checkCallerClass",
1132                                 MethodType.methodType(boolean.class, Class.class));
1133                 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS));
1134             } catch (Throwable ex) {
1135                 throw new InternalError(ex);
1136             }
1137         }
1138 
1139         @CallerSensitive
1140         @ForceInline // to ensure Reflection.getCallerClass optimization
1141         private static boolean checkCallerClass(Class<?> expected) {
1142             // This method is called via MH_checkCallerClass and so it's correct to ask for the immediate caller here.
1143             Class<?> actual = Reflection.getCallerClass();
1144             if (actual != expected)
1145                 throw new InternalError("found " + actual.getName() + ", expected " + expected.getName());
1146             return true;
1147         }
1148 
1149         private static final byte[] INJECTED_INVOKER_TEMPLATE = generateInvokerTemplate();
1150 
1151         /** Produces byte code for a class that is used as an injected invoker. */
1152         private static byte[] generateInvokerTemplate() {
1153             ClassWriter cw = new ClassWriter(0);
1154 
1155             // private static class InjectedInvoker {
1156             //     @Hidden
1157             //     static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
1158             //        return vamh.invokeExact(args);
1159             //     }
1160             // }
1161             cw.visit(CLASSFILE_VERSION, ACC_PRIVATE | ACC_SUPER, "InjectedInvoker", null, "java/lang/Object", null);
1162 
1163             MethodVisitor mv = cw.visitMethod(ACC_STATIC, "invoke_V",
1164                           "(Ljava/lang/invoke/MethodHandle;[Ljava/lang/Object;)Ljava/lang/Object;",
1165                           null, null);
1166 
1167             mv.visitCode();
1168             mv.visitVarInsn(ALOAD, 0);
1169             mv.visitVarInsn(ALOAD, 1);
1170             mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "invokeExact",
1171                                "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1172             mv.visitInsn(ARETURN);
1173             mv.visitMaxs(2, 2);
1174             mv.visitEnd();
1175 
1176             cw.visitEnd();
1177             return cw.toByteArray();
1178         }
1179     }
1180 
1181     /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */
1182     private static final class WrappedMember extends DelegatingMethodHandle {
1183         private final MethodHandle target;
1184         private final MemberName member;
1185         private final Class<?> callerClass;
1186         private final boolean isInvokeSpecial;
1187 
1188         private WrappedMember(MethodHandle target, MethodType type,
1189                               MemberName member, boolean isInvokeSpecial,
1190                               Class<?> callerClass) {
1191             super(type, target);
1192             this.target = target;
1193             this.member = member;
1194             this.callerClass = callerClass;
1195             this.isInvokeSpecial = isInvokeSpecial;
1196         }
1197 
1198         @Override
1199         MemberName internalMemberName() {
1200             return member;
1201         }
1202         @Override
1203         Class<?> internalCallerClass() {
1204             return callerClass;
1205         }
1206         @Override
1207         boolean isInvokeSpecial() {
1208             return isInvokeSpecial;
1209         }
1210         @Override
1211         protected MethodHandle getTarget() {
1212             return target;
1213         }
1214         @Override
1215         public MethodHandle asTypeUncached(MethodType newType) {
1216             // This MH is an alias for target, except for the MemberName
1217             // Drop the MemberName if there is any conversion.
1218             return target.asType(newType);
1219         }
1220     }
1221 
1222     static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) {
1223         if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial())
1224             return target;
1225         return new WrappedMember(target, target.type(), member, isInvokeSpecial, null);
1226     }
1227 
1228     /** Intrinsic IDs */
1229     /*non-public*/
1230     enum Intrinsic {
1231         SELECT_ALTERNATIVE,
1232         GUARD_WITH_CATCH,
1233         TRY_FINALLY,
1234         TABLE_SWITCH,
1235         LOOP,
1236         ARRAY_LOAD,
1237         ARRAY_STORE,
1238         ARRAY_LENGTH,
1239         IDENTITY,
1240         ZERO,
1241         NONE // no intrinsic associated
1242     }
1243 
1244     /** Mark arbitrary method handle as intrinsic.
1245      * InvokerBytecodeGenerator uses this info to produce more efficient bytecode shape. */
1246     static final class IntrinsicMethodHandle extends DelegatingMethodHandle {
1247         private final MethodHandle target;
1248         private final Intrinsic intrinsicName;
1249         private final Object intrinsicData;
1250 
1251         IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName) {
1252            this(target, intrinsicName, null);
1253         }
1254 
1255         IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName, Object intrinsicData) {
1256             super(target.type(), target);
1257             this.target = target;
1258             this.intrinsicName = intrinsicName;
1259             this.intrinsicData = intrinsicData;
1260         }
1261 
1262         @Override
1263         protected MethodHandle getTarget() {
1264             return target;
1265         }
1266 
1267         @Override
1268         Intrinsic intrinsicName() {
1269             return intrinsicName;
1270         }
1271 
1272         @Override
1273         Object intrinsicData() {
1274             return intrinsicData;
1275         }
1276 
1277         @Override
1278         public MethodHandle asTypeUncached(MethodType newType) {
1279             // This MH is an alias for target, except for the intrinsic name
1280             // Drop the name if there is any conversion.
1281             return target.asType(newType);
1282         }
1283 
1284         @Override
1285         String internalProperties() {
1286             return super.internalProperties() +
1287                     "\n& Intrinsic="+intrinsicName;
1288         }
1289 
1290         @Override
1291         public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
1292             if (intrinsicName == Intrinsic.IDENTITY) {
1293                 MethodType resultType = type().asCollectorType(arrayType, type().parameterCount() - 1, arrayLength);
1294                 MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength);
1295                 return newArray.asType(resultType);
1296             }
1297             return super.asCollector(arrayType, arrayLength);
1298         }
1299     }
1300 
1301     static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName) {
1302         return makeIntrinsic(target, intrinsicName, null);
1303     }
1304 
1305     static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName, Object intrinsicData) {
1306         if (intrinsicName == target.intrinsicName())
1307             return target;
1308         return new IntrinsicMethodHandle(target, intrinsicName, intrinsicData);
1309     }
1310 
1311     static MethodHandle makeIntrinsic(MethodType type, LambdaForm form, Intrinsic intrinsicName) {
1312         return new IntrinsicMethodHandle(SimpleMethodHandle.make(type, form), intrinsicName);
1313     }
1314 
1315     private static final @Stable MethodHandle[] ARRAYS = new MethodHandle[MAX_ARITY + 1];
1316 
1317     /** Return a method handle that takes the indicated number of Object
1318      *  arguments and returns an Object array of them, as if for varargs.
1319      */
1320     static MethodHandle varargsArray(int nargs) {
1321         MethodHandle mh = ARRAYS[nargs];
1322         if (mh != null) {
1323             return mh;
1324         }
1325         mh = makeCollector(Object[].class, nargs);
1326         assert(assertCorrectArity(mh, nargs));
1327         return ARRAYS[nargs] = mh;
1328     }
1329 
1330     /** Return a method handle that takes the indicated number of
1331      *  typed arguments and returns an array of them.
1332      *  The type argument is the array type.
1333      */
1334     static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
1335         Class<?> elemType = arrayType.getComponentType();
1336         if (elemType == null)  throw new IllegalArgumentException("not an array: "+arrayType);
1337         if (nargs >= MAX_JVM_ARITY/2 - 1) {
1338             int slots = nargs;
1339             final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1;  // 1 for receiver MH
1340             if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive())
1341                 slots *= Wrapper.forPrimitiveType(elemType).stackSlots();
1342             if (slots > MAX_ARRAY_SLOTS)
1343                 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs);
1344         }
1345         if (elemType == Object.class)
1346             return varargsArray(nargs);
1347         // other cases:  primitive arrays, subtypes of Object[]
1348         MethodHandle cache[] = Makers.TYPED_COLLECTORS.get(elemType);
1349         MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
1350         if (mh != null)  return mh;
1351         mh = makeCollector(arrayType, nargs);
1352         assert(assertCorrectArity(mh, nargs));
1353         if (nargs < cache.length)
1354             cache[nargs] = mh;
1355         return mh;
1356     }
1357 
1358     private static boolean assertCorrectArity(MethodHandle mh, int arity) {
1359         assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh;
1360         return true;
1361     }
1362 
1363     static final int MAX_JVM_ARITY = 255;  // limit imposed by the JVM
1364 
1365     /*non-public*/
1366     static void assertSame(Object mh1, Object mh2) {
1367         if (mh1 != mh2) {
1368             String msg = String.format("mh1 != mh2: mh1 = %s (form: %s); mh2 = %s (form: %s)",
1369                     mh1, ((MethodHandle)mh1).form,
1370                     mh2, ((MethodHandle)mh2).form);
1371             throw newInternalError(msg);
1372         }
1373     }
1374 
1375     // Local constant functions:
1376 
1377     /* non-public */
1378     static final byte NF_checkSpreadArgument = 0,
1379             NF_guardWithCatch = 1,
1380             NF_throwException = 2,
1381             NF_tryFinally = 3,
1382             NF_loop = 4,
1383             NF_profileBoolean = 5,
1384             NF_tableSwitch = 6,
1385             NF_LIMIT = 7;
1386 
1387     private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT];
1388 
1389     static NamedFunction getFunction(byte func) {
1390         NamedFunction nf = NFS[func];
1391         if (nf != null) {
1392             return nf;
1393         }
1394         return NFS[func] = createFunction(func);
1395     }
1396 
1397     private static NamedFunction createFunction(byte func) {
1398         try {
1399             return switch (func) {
1400                 case NF_checkSpreadArgument -> new NamedFunction(MethodHandleImpl.class
1401                                                 .getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
1402                 case NF_guardWithCatch      -> new NamedFunction(MethodHandleImpl.class
1403                                                 .getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class,
1404                                                    MethodHandle.class, Object[].class));
1405                 case NF_tryFinally          -> new NamedFunction(MethodHandleImpl.class
1406                                                 .getDeclaredMethod("tryFinally", MethodHandle.class, MethodHandle.class, Object[].class));
1407                 case NF_loop                -> new NamedFunction(MethodHandleImpl.class
1408                                                 .getDeclaredMethod("loop", BasicType[].class, LoopClauses.class, Object[].class));
1409                 case NF_throwException      -> new NamedFunction(MethodHandleImpl.class
1410                                                 .getDeclaredMethod("throwException", Throwable.class));
1411                 case NF_profileBoolean      -> new NamedFunction(MethodHandleImpl.class
1412                                                 .getDeclaredMethod("profileBoolean", boolean.class, int[].class));
1413                 case NF_tableSwitch         -> new NamedFunction(MethodHandleImpl.class
1414                                                 .getDeclaredMethod("tableSwitch", int.class, MethodHandle.class, CasesHolder.class, Object[].class));
1415                 default -> throw new InternalError("Undefined function: " + func);
1416             };
1417         } catch (ReflectiveOperationException ex) {
1418             throw newInternalError(ex);
1419         }
1420     }
1421 
1422     static {
1423         SharedSecrets.setJavaLangInvokeAccess(new JavaLangInvokeAccess() {
1424 
1425             @Override
1426             public MethodHandle privilegedUnreflect(Method method) {
1427                 try {
1428                     return IMPL_LOOKUP.unreflect(method);
1429                 } catch (IllegalAccessException e) {
1430                     throw new InternalError(e);
1431                 }
1432             }
1433 
1434             @Override
1435             public MethodHandle privilegedUnreflect(Constructor<?> ctor) {
1436                 try {
1437                     return IMPL_LOOKUP.unreflectConstructor(ctor);
1438                 } catch (IllegalAccessException e) {
1439                     throw new InternalError(e);
1440                 }
1441             }
1442 
1443             @Override
1444             public MethodHandle privilegedFindStatic(Class<?> refc, String name, MethodType type)
1445                     throws NoSuchMethodException {
1446                 try {
1447                     return IMPL_LOOKUP.findStatic(refc, name, type);
1448                 } catch (IllegalAccessException e) {
1449                     throw new InternalError(e);
1450                 }
1451             }
1452 
1453             @Override
1454             public Object newMemberName() {
1455                 return new MemberName();
1456             }
1457 
1458             @Override
1459             public Object newMemberName(Method method) {
1460                 return new MemberName(method);
1461             }
1462 
1463             @Override
1464             public String getName(Object mname) {
1465                 MemberName memberName = (MemberName)mname;
1466                 return memberName.getName();
1467             }
1468             @Override
1469             public Class<?> getDeclaringClass(Object mname) {
1470                 MemberName memberName = (MemberName)mname;
1471                 return memberName.getDeclaringClass();
1472             }
1473 
1474             @Override
1475             public MethodType getMethodType(Object mname) {
1476                 MemberName memberName = (MemberName)mname;
1477                 return memberName.getMethodType();
1478             }
1479 
1480             @Override
1481             public String getMethodDescriptor(Object mname) {
1482                 MemberName memberName = (MemberName)mname;
1483                 return memberName.getMethodDescriptor();
1484             }
1485 
1486             @Override
1487             public boolean isNative(Object mname) {
1488                 MemberName memberName = (MemberName)mname;
1489                 return memberName.isNative();
1490             }
1491 
1492             @Override
1493             public Map<String, byte[]> generateHolderClasses(Stream<String> traces) {
1494                 return GenerateJLIClassesHelper.generateHolderClasses(traces);
1495             }
1496 
1497             @Override
1498             public void ensureCustomized(MethodHandle mh) {
1499                 mh.customize();
1500             }
1501 
1502             @Override
1503             public VarHandle memoryAccessVarHandle(Class<?> carrier, boolean skipAlignmentMaskCheck, long alignmentMask,
1504                                                    ByteOrder order) {
1505                 return VarHandles.makeMemoryAddressViewHandle(carrier, skipAlignmentMaskCheck, alignmentMask, order);
1506             }
1507 
1508             @Override
1509             public MethodHandle nativeMethodHandle(NativeEntryPoint nep, MethodHandle fallback) {
1510                 return NativeMethodHandle.make(nep, fallback);
1511             }
1512 
1513             @Override
1514             public VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
1515                 return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
1516             }
1517 
1518             @Override
1519             public VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
1520                 return VarHandles.filterCoordinates(target, pos, filters);
1521             }
1522 
1523             @Override
1524             public VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
1525                 return VarHandles.dropCoordinates(target, pos, valueTypes);
1526             }
1527 
1528             @Override
1529             public VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
1530                 return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
1531             }
1532 
1533             @Override
1534             public VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
1535                 return VarHandles.collectCoordinates(target, pos, filter);
1536             }
1537 
1538             @Override
1539             public VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
1540                 return VarHandles.insertCoordinates(target, pos, values);
1541             }
1542         });
1543     }
1544 
1545     /** Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore(). */
1546     private static MethodHandle unboxResultHandle(Class<?> returnType) {
1547         if (returnType.isPrimitive()) {
1548             if (returnType == void.class) {
1549                 return ValueConversions.ignore();
1550             } else {
1551                 Wrapper w = Wrapper.forPrimitiveType(returnType);
1552                 return ValueConversions.unboxExact(w);
1553             }
1554         } else {
1555             return MethodHandles.identity(Object.class);
1556         }
1557     }
1558 
1559     /**
1560      * Assembles a loop method handle from the given handles and type information.
1561      *
1562      * @param tloop the return type of the loop.
1563      * @param targs types of the arguments to be passed to the loop.
1564      * @param init sanitized array of initializers for loop-local variables.
1565      * @param step sanitited array of loop bodies.
1566      * @param pred sanitized array of predicates.
1567      * @param fini sanitized array of loop finalizers.
1568      *
1569      * @return a handle that, when invoked, will execute the loop.
1570      */
1571     static MethodHandle makeLoop(Class<?> tloop, List<Class<?>> targs, List<MethodHandle> init, List<MethodHandle> step,
1572                                  List<MethodHandle> pred, List<MethodHandle> fini) {
1573         MethodType type = MethodType.methodType(tloop, targs);
1574         BasicType[] initClauseTypes =
1575                 init.stream().map(h -> h.type().returnType()).map(BasicType::basicType).toArray(BasicType[]::new);
1576         LambdaForm form = makeLoopForm(type.basicType(), initClauseTypes);
1577 
1578         // Prepare auxiliary method handles used during LambdaForm interpretation.
1579         // Box arguments and wrap them into Object[]: ValueConversions.array().
1580         MethodType varargsType = type.changeReturnType(Object[].class);
1581         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
1582         MethodHandle unboxResult = unboxResultHandle(tloop);
1583 
1584         LoopClauses clauseData =
1585                 new LoopClauses(new MethodHandle[][]{toArray(init), toArray(step), toArray(pred), toArray(fini)});
1586         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL();
1587         BoundMethodHandle mh;
1588         try {
1589             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) clauseData,
1590                     (Object) collectArgs, (Object) unboxResult);
1591         } catch (Throwable ex) {
1592             throw uncaughtException(ex);
1593         }
1594         assert(mh.type() == type);
1595         return mh;
1596     }
1597 
1598     private static MethodHandle[] toArray(List<MethodHandle> l) {
1599         return l.toArray(new MethodHandle[0]);
1600     }
1601 
1602     /**
1603      * Loops introduce some complexity as they can have additional local state. Hence, LambdaForms for loops are
1604      * generated from a template. The LambdaForm template shape for the loop combinator is as follows (assuming one
1605      * reference parameter passed in {@code a1}, and a reference return type, with the return value represented by
1606      * {@code t12}):
1607      * <blockquote><pre>{@code
1608      *  loop=Lambda(a0:L,a1:L)=>{
1609      *    t2:L=BoundMethodHandle$Species_L3.argL0(a0:L);    // LoopClauses holding init, step, pred, fini handles
1610      *    t3:L=BoundMethodHandle$Species_L3.argL1(a0:L);    // helper handle to box the arguments into an Object[]
1611      *    t4:L=BoundMethodHandle$Species_L3.argL2(a0:L);    // helper handle to unbox the result
1612      *    t5:L=MethodHandle.invokeBasic(t3:L,a1:L);         // box the arguments into an Object[]
1613      *    t6:L=MethodHandleImpl.loop(null,t2:L,t3:L);       // call the loop executor
1614      *    t7:L=MethodHandle.invokeBasic(t4:L,t6:L);t7:L}    // unbox the result; return the result
1615      * }</pre></blockquote>
1616      * <p>
1617      * {@code argL0} is a LoopClauses instance holding, in a 2-dimensional array, the init, step, pred, and fini method
1618      * handles. {@code argL1} and {@code argL2} are auxiliary method handles: {@code argL1} boxes arguments and wraps
1619      * them into {@code Object[]} ({@code ValueConversions.array()}), and {@code argL2} unboxes the result if necessary
1620      * ({@code ValueConversions.unbox()}).
1621      * <p>
1622      * Having {@code t3} and {@code t4} passed in via a BMH and not hardcoded in the lambda form allows to share lambda
1623      * forms among loop combinators with the same basic type.
1624      * <p>
1625      * The above template is instantiated by using the {@link LambdaFormEditor} to replace the {@code null} argument to
1626      * the {@code loop} invocation with the {@code BasicType} array describing the loop clause types. This argument is
1627      * ignored in the loop invoker, but will be extracted and used in {@linkplain InvokerBytecodeGenerator#emitLoop(int)
1628      * bytecode generation}.
1629      */
1630     private static LambdaForm makeLoopForm(MethodType basicType, BasicType[] localVarTypes) {
1631         MethodType lambdaType = basicType.invokerType();
1632 
1633         final int THIS_MH = 0;  // the BMH_LLL
1634         final int ARG_BASE = 1; // start of incoming arguments
1635         final int ARG_LIMIT = ARG_BASE + basicType.parameterCount();
1636 
1637         int nameCursor = ARG_LIMIT;
1638         final int GET_CLAUSE_DATA = nameCursor++;
1639         final int GET_COLLECT_ARGS = nameCursor++;
1640         final int GET_UNBOX_RESULT = nameCursor++;
1641         final int BOXED_ARGS = nameCursor++;
1642         final int LOOP = nameCursor++;
1643         final int UNBOX_RESULT = nameCursor++;
1644 
1645         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_LOOP);
1646         if (lform == null) {
1647             Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
1648 
1649             BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL();
1650             names[THIS_MH] = names[THIS_MH].withConstraint(data);
1651             names[GET_CLAUSE_DATA] = new Name(data.getterFunction(0), names[THIS_MH]);
1652             names[GET_COLLECT_ARGS] = new Name(data.getterFunction(1), names[THIS_MH]);
1653             names[GET_UNBOX_RESULT] = new Name(data.getterFunction(2), names[THIS_MH]);
1654 
1655             // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
1656             MethodType collectArgsType = basicType.changeReturnType(Object.class);
1657             MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
1658             Object[] args = new Object[invokeBasic.type().parameterCount()];
1659             args[0] = names[GET_COLLECT_ARGS];
1660             System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT - ARG_BASE);
1661             names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.LOOP)), args);
1662 
1663             // t_{i+1}:L=MethodHandleImpl.loop(localTypes:L,clauses:L,t_{i}:L);
1664             Object[] lArgs =
1665                     new Object[]{null, // placeholder for BasicType[] localTypes - will be added by LambdaFormEditor
1666                             names[GET_CLAUSE_DATA], names[BOXED_ARGS]};
1667             names[LOOP] = new Name(getFunction(NF_loop), lArgs);
1668 
1669             // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
1670             MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
1671             Object[] unboxArgs = new Object[]{names[GET_UNBOX_RESULT], names[LOOP]};
1672             names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
1673 
1674             lform = basicType.form().setCachedLambdaForm(MethodTypeForm.LF_LOOP,
1675                     new LambdaForm(lambdaType.parameterCount(), names, Kind.LOOP));
1676         }
1677 
1678         // BOXED_ARGS is the index into the names array where the loop idiom starts
1679         return lform.editor().noteLoopLocalTypesForm(BOXED_ARGS, localVarTypes);
1680     }
1681 
1682     static class LoopClauses {
1683         @Stable final MethodHandle[][] clauses;
1684         LoopClauses(MethodHandle[][] clauses) {
1685             assert clauses.length == 4;
1686             this.clauses = clauses;
1687         }
1688         @Override
1689         public String toString() {
1690             StringBuilder sb = new StringBuilder("LoopClauses -- ");
1691             for (int i = 0; i < 4; ++i) {
1692                 if (i > 0) {
1693                     sb.append("       ");
1694                 }
1695                 sb.append('<').append(i).append(">: ");
1696                 MethodHandle[] hs = clauses[i];
1697                 for (int j = 0; j < hs.length; ++j) {
1698                     if (j > 0) {
1699                         sb.append("          ");
1700                     }
1701                     sb.append('*').append(j).append(": ").append(hs[j]).append('\n');
1702                 }
1703             }
1704             sb.append(" --\n");
1705             return sb.toString();
1706         }
1707     }
1708 
1709     /**
1710      * Intrinsified during LambdaForm compilation
1711      * (see {@link InvokerBytecodeGenerator#emitLoop(int)}).
1712      */
1713     @Hidden
1714     static Object loop(BasicType[] localTypes, LoopClauses clauseData, Object... av) throws Throwable {
1715         final MethodHandle[] init = clauseData.clauses[0];
1716         final MethodHandle[] step = clauseData.clauses[1];
1717         final MethodHandle[] pred = clauseData.clauses[2];
1718         final MethodHandle[] fini = clauseData.clauses[3];
1719         int varSize = (int) Stream.of(init).filter(h -> h.type().returnType() != void.class).count();
1720         int nArgs = init[0].type().parameterCount();
1721         Object[] varsAndArgs = new Object[varSize + nArgs];
1722         for (int i = 0, v = 0; i < init.length; ++i) {
1723             MethodHandle ih = init[i];
1724             if (ih.type().returnType() == void.class) {
1725                 ih.invokeWithArguments(av);
1726             } else {
1727                 varsAndArgs[v++] = ih.invokeWithArguments(av);
1728             }
1729         }
1730         System.arraycopy(av, 0, varsAndArgs, varSize, nArgs);
1731         final int nSteps = step.length;
1732         for (; ; ) {
1733             for (int i = 0, v = 0; i < nSteps; ++i) {
1734                 MethodHandle p = pred[i];
1735                 MethodHandle s = step[i];
1736                 MethodHandle f = fini[i];
1737                 if (s.type().returnType() == void.class) {
1738                     s.invokeWithArguments(varsAndArgs);
1739                 } else {
1740                     varsAndArgs[v++] = s.invokeWithArguments(varsAndArgs);
1741                 }
1742                 if (!(boolean) p.invokeWithArguments(varsAndArgs)) {
1743                     return f.invokeWithArguments(varsAndArgs);
1744                 }
1745             }
1746         }
1747     }
1748 
1749     /**
1750      * This method is bound as the predicate in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle,
1751      * MethodHandle) counting loops}.
1752      *
1753      * @param limit the upper bound of the parameter, statically bound at loop creation time.
1754      * @param counter the counter parameter, passed in during loop execution.
1755      *
1756      * @return whether the counter has reached the limit.
1757      */
1758     static boolean countedLoopPredicate(int limit, int counter) {
1759         return counter < limit;
1760     }
1761 
1762     /**
1763      * This method is bound as the step function in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle,
1764      * MethodHandle) counting loops} to increment the counter.
1765      *
1766      * @param limit the upper bound of the loop counter (ignored).
1767      * @param counter the loop counter.
1768      *
1769      * @return the loop counter incremented by 1.
1770      */
1771     static int countedLoopStep(int limit, int counter) {
1772         return counter + 1;
1773     }
1774 
1775     /**
1776      * This is bound to initialize the loop-local iterator in {@linkplain MethodHandles#iteratedLoop iterating loops}.
1777      *
1778      * @param it the {@link Iterable} over which the loop iterates.
1779      *
1780      * @return an {@link Iterator} over the argument's elements.
1781      */
1782     static Iterator<?> initIterator(Iterable<?> it) {
1783         return it.iterator();
1784     }
1785 
1786     /**
1787      * This method is bound as the predicate in {@linkplain MethodHandles#iteratedLoop iterating loops}.
1788      *
1789      * @param it the iterator to be checked.
1790      *
1791      * @return {@code true} iff there are more elements to iterate over.
1792      */
1793     static boolean iteratePredicate(Iterator<?> it) {
1794         return it.hasNext();
1795     }
1796 
1797     /**
1798      * This method is bound as the step for retrieving the current value from the iterator in {@linkplain
1799      * MethodHandles#iteratedLoop iterating loops}.
1800      *
1801      * @param it the iterator.
1802      *
1803      * @return the next element from the iterator.
1804      */
1805     static Object iterateNext(Iterator<?> it) {
1806         return it.next();
1807     }
1808 
1809     /**
1810      * Makes a {@code try-finally} handle that conforms to the type constraints.
1811      *
1812      * @param target the target to execute in a {@code try-finally} block.
1813      * @param cleanup the cleanup to execute in the {@code finally} block.
1814      * @param rtype the result type of the entire construct.
1815      * @param argTypes the types of the arguments.
1816      *
1817      * @return a handle on the constructed {@code try-finally} block.
1818      */
1819     static MethodHandle makeTryFinally(MethodHandle target, MethodHandle cleanup, Class<?> rtype, List<Class<?>> argTypes) {
1820         MethodType type = MethodType.methodType(rtype, argTypes);
1821         LambdaForm form = makeTryFinallyForm(type.basicType());
1822 
1823         // Prepare auxiliary method handles used during LambdaForm interpretation.
1824         // Box arguments and wrap them into Object[]: ValueConversions.array().
1825         MethodType varargsType = type.changeReturnType(Object[].class);
1826         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
1827         MethodHandle unboxResult = unboxResultHandle(rtype);
1828 
1829         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL();
1830         BoundMethodHandle mh;
1831         try {
1832             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) target, (Object) cleanup,
1833                     (Object) collectArgs, (Object) unboxResult);
1834         } catch (Throwable ex) {
1835             throw uncaughtException(ex);
1836         }
1837         assert(mh.type() == type);
1838         return mh;
1839     }
1840 
1841     /**
1842      * The LambdaForm shape for the tryFinally combinator is as follows (assuming one reference parameter passed in
1843      * {@code a1}, and a reference return type, with the return value represented by {@code t8}):
1844      * <blockquote><pre>{@code
1845      *  tryFinally=Lambda(a0:L,a1:L)=>{
1846      *    t2:L=BoundMethodHandle$Species_LLLL.argL0(a0:L);  // target method handle
1847      *    t3:L=BoundMethodHandle$Species_LLLL.argL1(a0:L);  // cleanup method handle
1848      *    t4:L=BoundMethodHandle$Species_LLLL.argL2(a0:L);  // helper handle to box the arguments into an Object[]
1849      *    t5:L=BoundMethodHandle$Species_LLLL.argL3(a0:L);  // helper handle to unbox the result
1850      *    t6:L=MethodHandle.invokeBasic(t4:L,a1:L);         // box the arguments into an Object[]
1851      *    t7:L=MethodHandleImpl.tryFinally(t2:L,t3:L,t6:L); // call the tryFinally executor
1852      *    t8:L=MethodHandle.invokeBasic(t5:L,t7:L);t8:L}    // unbox the result; return the result
1853      * }</pre></blockquote>
1854      * <p>
1855      * {@code argL0} and {@code argL1} are the target and cleanup method handles.
1856      * {@code argL2} and {@code argL3} are auxiliary method handles: {@code argL2} boxes arguments and wraps them into
1857      * {@code Object[]} ({@code ValueConversions.array()}), and {@code argL3} unboxes the result if necessary
1858      * ({@code ValueConversions.unbox()}).
1859      * <p>
1860      * Having {@code t4} and {@code t5} passed in via a BMH and not hardcoded in the lambda form allows to share lambda
1861      * forms among tryFinally combinators with the same basic type.
1862      */
1863     private static LambdaForm makeTryFinallyForm(MethodType basicType) {
1864         MethodType lambdaType = basicType.invokerType();
1865 
1866         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_TF);
1867         if (lform != null) {
1868             return lform;
1869         }
1870         final int THIS_MH      = 0;  // the BMH_LLLL
1871         final int ARG_BASE     = 1;  // start of incoming arguments
1872         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
1873 
1874         int nameCursor = ARG_LIMIT;
1875         final int GET_TARGET       = nameCursor++;
1876         final int GET_CLEANUP      = nameCursor++;
1877         final int GET_COLLECT_ARGS = nameCursor++;
1878         final int GET_UNBOX_RESULT = nameCursor++;
1879         final int BOXED_ARGS       = nameCursor++;
1880         final int TRY_FINALLY      = nameCursor++;
1881         final int UNBOX_RESULT     = nameCursor++;
1882 
1883         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
1884 
1885         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL();
1886         names[THIS_MH]          = names[THIS_MH].withConstraint(data);
1887         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
1888         names[GET_CLEANUP]      = new Name(data.getterFunction(1), names[THIS_MH]);
1889         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(2), names[THIS_MH]);
1890         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(3), names[THIS_MH]);
1891 
1892         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
1893         MethodType collectArgsType = basicType.changeReturnType(Object.class);
1894         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
1895         Object[] args = new Object[invokeBasic.type().parameterCount()];
1896         args[0] = names[GET_COLLECT_ARGS];
1897         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
1898         names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.TRY_FINALLY)), args);
1899 
1900         // t_{i+1}:L=MethodHandleImpl.tryFinally(target:L,exType:L,catcher:L,t_{i}:L);
1901         Object[] tfArgs = new Object[] {names[GET_TARGET], names[GET_CLEANUP], names[BOXED_ARGS]};
1902         names[TRY_FINALLY] = new Name(getFunction(NF_tryFinally), tfArgs);
1903 
1904         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
1905         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
1906         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_FINALLY]};
1907         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
1908 
1909         lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.TRY_FINALLY);
1910 
1911         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_TF, lform);
1912     }
1913 
1914     /**
1915      * Intrinsified during LambdaForm compilation
1916      * (see {@link InvokerBytecodeGenerator#emitTryFinally emitTryFinally}).
1917      */
1918     @Hidden
1919     static Object tryFinally(MethodHandle target, MethodHandle cleanup, Object... av) throws Throwable {
1920         Throwable t = null;
1921         Object r = null;
1922         try {
1923             r = target.invokeWithArguments(av);
1924         } catch (Throwable thrown) {
1925             t = thrown;
1926             throw t;
1927         } finally {
1928             Object[] args = target.type().returnType() == void.class ? prepend(av, t) : prepend(av, t, r);
1929             r = cleanup.invokeWithArguments(args);
1930         }
1931         return r;
1932     }
1933 
1934     // see varargsArray method for chaching/package-private version of this
1935     private static MethodHandle makeCollector(Class<?> arrayType, int parameterCount) {
1936         MethodType type = MethodType.methodType(arrayType, Collections.nCopies(parameterCount, arrayType.componentType()));
1937         MethodHandle newArray = MethodHandles.arrayConstructor(arrayType);
1938 
1939         LambdaForm form = makeCollectorForm(type.basicType(), arrayType);
1940 
1941         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_L();
1942         BoundMethodHandle mh;
1943         try {
1944             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) newArray);
1945         } catch (Throwable ex) {
1946             throw uncaughtException(ex);
1947         }
1948         assert(mh.type() == type);
1949         return mh;
1950     }
1951 
1952     private static LambdaForm makeCollectorForm(MethodType basicType, Class<?> arrayType) {
1953         MethodType lambdaType = basicType.invokerType();
1954         int parameterCount = basicType.parameterCount();
1955 
1956         // Only share the lambda form for empty arrays and reference types.
1957         // Sharing based on the basic type alone doesn't work because
1958         // we need a separate lambda form for byte/short/char/int which
1959         // are all erased to int otherwise.
1960         // Other caching for primitive types happens at the MethodHandle level (see varargsArray).
1961         boolean isReferenceType = !arrayType.componentType().isPrimitive();
1962         boolean isSharedLambdaForm = parameterCount == 0 || isReferenceType;
1963         if (isSharedLambdaForm) {
1964             LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_COLLECTOR);
1965             if (lform != null) {
1966                 return lform;
1967             }
1968         }
1969 
1970         // use erased accessor for reference types
1971         MethodHandle storeFunc = isReferenceType
1972                 ? ArrayAccessor.OBJECT_ARRAY_SETTER
1973                 : makeArrayElementAccessor(arrayType, ArrayAccess.SET);
1974 
1975         final int THIS_MH      = 0;  // the BMH_L
1976         final int ARG_BASE     = 1;  // start of incoming arguments
1977         final int ARG_LIMIT    = ARG_BASE + parameterCount;
1978 
1979         int nameCursor = ARG_LIMIT;
1980         final int GET_NEW_ARRAY       = nameCursor++;
1981         final int CALL_NEW_ARRAY      = nameCursor++;
1982         final int STORE_ELEMENT_BASE  = nameCursor;
1983         final int STORE_ELEMENT_LIMIT = STORE_ELEMENT_BASE + parameterCount;
1984         nameCursor = STORE_ELEMENT_LIMIT;
1985 
1986         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
1987 
1988         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_L();
1989         names[THIS_MH]          = names[THIS_MH].withConstraint(data);
1990         names[GET_NEW_ARRAY]    = new Name(data.getterFunction(0), names[THIS_MH]);
1991 
1992         MethodHandle invokeBasic = MethodHandles.basicInvoker(MethodType.methodType(Object.class, int.class));
1993         names[CALL_NEW_ARRAY] = new Name(new NamedFunction(invokeBasic), names[GET_NEW_ARRAY], parameterCount);
1994         for (int storeIndex = 0,
1995              storeNameCursor = STORE_ELEMENT_BASE,
1996              argCursor = ARG_BASE;
1997              storeNameCursor < STORE_ELEMENT_LIMIT;
1998              storeIndex++, storeNameCursor++, argCursor++){
1999 
2000             names[storeNameCursor] = new Name(new NamedFunction(makeIntrinsic(storeFunc, Intrinsic.ARRAY_STORE)),
2001                     names[CALL_NEW_ARRAY], storeIndex, names[argCursor]);
2002         }
2003 
2004         LambdaForm lform = new LambdaForm(lambdaType.parameterCount(), names, CALL_NEW_ARRAY, Kind.COLLECTOR);
2005         if (isSharedLambdaForm) {
2006             lform = basicType.form().setCachedLambdaForm(MethodTypeForm.LF_COLLECTOR, lform);
2007         }
2008         return lform;
2009     }
2010 
2011     // use a wrapper because we need this array to be @Stable
2012     static class CasesHolder {
2013         @Stable
2014         final MethodHandle[] cases;
2015 
2016         public CasesHolder(MethodHandle[] cases) {
2017             this.cases = cases;
2018         }
2019     }
2020 
2021     static MethodHandle makeTableSwitch(MethodType type, MethodHandle defaultCase, MethodHandle[] caseActions) {
2022         MethodType varargsType = type.changeReturnType(Object[].class);
2023         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
2024 
2025         MethodHandle unboxResult = unboxResultHandle(type.returnType());
2026 
2027         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL();
2028         LambdaForm form = makeTableSwitchForm(type.basicType(), data, caseActions.length);
2029         BoundMethodHandle mh;
2030         CasesHolder caseHolder =  new CasesHolder(caseActions);
2031         try {
2032             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) defaultCase, (Object) collectArgs,
2033                                                                 (Object) unboxResult, (Object) caseHolder);
2034         } catch (Throwable ex) {
2035             throw uncaughtException(ex);
2036         }
2037         assert(mh.type() == type);
2038         return mh;
2039     }
2040 
2041     private static class TableSwitchCacheKey {
2042         private static final Map<TableSwitchCacheKey, LambdaForm> CACHE = new ConcurrentHashMap<>();
2043 
2044         private final MethodType basicType;
2045         private final int numberOfCases;
2046 
2047         public TableSwitchCacheKey(MethodType basicType, int numberOfCases) {
2048             this.basicType = basicType;
2049             this.numberOfCases = numberOfCases;
2050         }
2051 
2052         @Override
2053         public boolean equals(Object o) {
2054             if (this == o) return true;
2055             if (o == null || getClass() != o.getClass()) return false;
2056             TableSwitchCacheKey that = (TableSwitchCacheKey) o;
2057             return numberOfCases == that.numberOfCases && Objects.equals(basicType, that.basicType);
2058         }
2059         @Override
2060         public int hashCode() {
2061             return Objects.hash(basicType, numberOfCases);
2062         }
2063     }
2064 
2065     private static LambdaForm makeTableSwitchForm(MethodType basicType, BoundMethodHandle.SpeciesData data,
2066                                                   int numCases) {
2067         MethodType lambdaType = basicType.invokerType();
2068 
2069         // We need to cache based on the basic type X number of cases,
2070         // since the number of cases is used when generating bytecode.
2071         // This also means that we can't use the cache in MethodTypeForm,
2072         // which only uses the basic type as a key.
2073         TableSwitchCacheKey key = new TableSwitchCacheKey(basicType, numCases);
2074         LambdaForm lform = TableSwitchCacheKey.CACHE.get(key);
2075         if (lform != null) {
2076             return lform;
2077         }
2078 
2079         final int THIS_MH       = 0;
2080         final int ARG_BASE      = 1;  // start of incoming arguments
2081         final int ARG_LIMIT     = ARG_BASE + basicType.parameterCount();
2082         final int ARG_SWITCH_ON = ARG_BASE;
2083         assert ARG_SWITCH_ON < ARG_LIMIT;
2084 
2085         int nameCursor = ARG_LIMIT;
2086         final int GET_COLLECT_ARGS  = nameCursor++;
2087         final int GET_DEFAULT_CASE  = nameCursor++;
2088         final int GET_UNBOX_RESULT  = nameCursor++;
2089         final int GET_CASES         = nameCursor++;
2090         final int BOXED_ARGS        = nameCursor++;
2091         final int TABLE_SWITCH      = nameCursor++;
2092         final int UNBOXED_RESULT    = nameCursor++;
2093 
2094         int fieldCursor = 0;
2095         final int FIELD_DEFAULT_CASE  = fieldCursor++;
2096         final int FIELD_COLLECT_ARGS  = fieldCursor++;
2097         final int FIELD_UNBOX_RESULT  = fieldCursor++;
2098         final int FIELD_CASES         = fieldCursor++;
2099 
2100         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
2101 
2102         names[THIS_MH] = names[THIS_MH].withConstraint(data);
2103         names[GET_DEFAULT_CASE] = new Name(data.getterFunction(FIELD_DEFAULT_CASE), names[THIS_MH]);
2104         names[GET_COLLECT_ARGS]  = new Name(data.getterFunction(FIELD_COLLECT_ARGS), names[THIS_MH]);
2105         names[GET_UNBOX_RESULT]  = new Name(data.getterFunction(FIELD_UNBOX_RESULT), names[THIS_MH]);
2106         names[GET_CASES] = new Name(data.getterFunction(FIELD_CASES), names[THIS_MH]);
2107 
2108         {
2109             MethodType collectArgsType = basicType.changeReturnType(Object.class);
2110             MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
2111             Object[] args = new Object[invokeBasic.type().parameterCount()];
2112             args[0] = names[GET_COLLECT_ARGS];
2113             System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT - ARG_BASE);
2114             names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.TABLE_SWITCH, numCases)), args);
2115         }
2116 
2117         {
2118             Object[] tfArgs = new Object[]{
2119                 names[ARG_SWITCH_ON], names[GET_DEFAULT_CASE], names[GET_CASES], names[BOXED_ARGS]};
2120             names[TABLE_SWITCH] = new Name(getFunction(NF_tableSwitch), tfArgs);
2121         }
2122 
2123         {
2124             MethodHandle invokeBasic = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
2125             Object[] unboxArgs = new Object[]{names[GET_UNBOX_RESULT], names[TABLE_SWITCH]};
2126             names[UNBOXED_RESULT] = new Name(invokeBasic, unboxArgs);
2127         }
2128 
2129         lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.TABLE_SWITCH);
2130         LambdaForm prev = TableSwitchCacheKey.CACHE.putIfAbsent(key, lform);
2131         return prev != null ? prev : lform;
2132     }
2133 
2134     @Hidden
2135     static Object tableSwitch(int input, MethodHandle defaultCase, CasesHolder holder, Object[] args) throws Throwable {
2136         MethodHandle[] caseActions = holder.cases;
2137         MethodHandle selectedCase;
2138         if (input < 0 || input >= caseActions.length) {
2139             selectedCase = defaultCase;
2140         } else {
2141             selectedCase = caseActions[input];
2142         }
2143         return selectedCase.invokeWithArguments(args);
2144     }
2145 
2146     // Indexes into constant method handles:
2147     static final int
2148             MH_cast                  = 0,
2149             MH_selectAlternative     = 1,
2150             MH_countedLoopPred       = 2,
2151             MH_countedLoopStep       = 3,
2152             MH_initIterator          = 4,
2153             MH_iteratePred           = 5,
2154             MH_iterateNext           = 6,
2155             MH_Array_newInstance     = 7,
2156             MH_LIMIT                 = 8;
2157 
2158     static MethodHandle getConstantHandle(int idx) {
2159         MethodHandle handle = HANDLES[idx];
2160         if (handle != null) {
2161             return handle;
2162         }
2163         return setCachedHandle(idx, makeConstantHandle(idx));
2164     }
2165 
2166     private static synchronized MethodHandle setCachedHandle(int idx, final MethodHandle method) {
2167         // Simulate a CAS, to avoid racy duplication of results.
2168         MethodHandle prev = HANDLES[idx];
2169         if (prev != null) {
2170             return prev;
2171         }
2172         HANDLES[idx] = method;
2173         return method;
2174     }
2175 
2176     // Local constant method handles:
2177     private static final @Stable MethodHandle[] HANDLES = new MethodHandle[MH_LIMIT];
2178 
2179     private static MethodHandle makeConstantHandle(int idx) {
2180         try {
2181             switch (idx) {
2182                 case MH_cast:
2183                     return IMPL_LOOKUP.findVirtual(Class.class, "cast",
2184                             MethodType.methodType(Object.class, Object.class));
2185                 case MH_selectAlternative:
2186                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "selectAlternative",
2187                             MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class));
2188                 case MH_countedLoopPred:
2189                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopPredicate",
2190                             MethodType.methodType(boolean.class, int.class, int.class));
2191                 case MH_countedLoopStep:
2192                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopStep",
2193                             MethodType.methodType(int.class, int.class, int.class));
2194                 case MH_initIterator:
2195                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "initIterator",
2196                             MethodType.methodType(Iterator.class, Iterable.class));
2197                 case MH_iteratePred:
2198                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iteratePredicate",
2199                             MethodType.methodType(boolean.class, Iterator.class));
2200                 case MH_iterateNext:
2201                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iterateNext",
2202                             MethodType.methodType(Object.class, Iterator.class));
2203                 case MH_Array_newInstance:
2204                     return IMPL_LOOKUP.findStatic(Array.class, "newInstance",
2205                             MethodType.methodType(Object.class, Class.class, int.class));
2206             }
2207         } catch (ReflectiveOperationException ex) {
2208             throw newInternalError(ex);
2209         }
2210         throw newInternalError("Unknown function index: " + idx);
2211     }
2212 }