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