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