rev 15353 : 8164044: Generate the corresponding BoundMethodHandle to all generated DirectMethodHandles
Reviewed-by: vlivanov, mhaupt

   1 /*
   2  * Copyright (c) 2011, 2016, 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.perf.PerfCounter;
  29 import jdk.internal.vm.annotation.DontInline;
  30 import jdk.internal.vm.annotation.Stable;
  31 import sun.invoke.util.Wrapper;
  32 
  33 import java.lang.annotation.ElementType;
  34 import java.lang.annotation.Retention;
  35 import java.lang.annotation.RetentionPolicy;
  36 import java.lang.annotation.Target;
  37 import java.lang.reflect.Method;
  38 import java.util.Arrays;
  39 import java.util.HashMap;
  40 
  41 import static java.lang.invoke.LambdaForm.BasicType.*;
  42 import static java.lang.invoke.MethodHandleNatives.Constants.REF_invokeStatic;
  43 import static java.lang.invoke.MethodHandleStatics.*;
  44 import java.util.Objects;
  45 
  46 /**
  47  * The symbolic, non-executable form of a method handle's invocation semantics.
  48  * It consists of a series of names.
  49  * The first N (N=arity) names are parameters,
  50  * while any remaining names are temporary values.
  51  * Each temporary specifies the application of a function to some arguments.
  52  * The functions are method handles, while the arguments are mixes of
  53  * constant values and local names.
  54  * The result of the lambda is defined as one of the names, often the last one.
  55  * <p>
  56  * Here is an approximate grammar:
  57  * <blockquote><pre>{@code
  58  * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}"
  59  * ArgName = "a" N ":" T
  60  * TempName = "t" N ":" T "=" Function "(" Argument* ");"
  61  * Function = ConstantValue
  62  * Argument = NameRef | ConstantValue
  63  * Result = NameRef | "void"
  64  * NameRef = "a" N | "t" N
  65  * N = (any whole number)
  66  * T = "L" | "I" | "J" | "F" | "D" | "V"
  67  * }</pre></blockquote>
  68  * Names are numbered consecutively from left to right starting at zero.
  69  * (The letters are merely a taste of syntax sugar.)
  70  * Thus, the first temporary (if any) is always numbered N (where N=arity).
  71  * Every occurrence of a name reference in an argument list must refer to
  72  * a name previously defined within the same lambda.
  73  * A lambda has a void result if and only if its result index is -1.
  74  * If a temporary has the type "V", it cannot be the subject of a NameRef,
  75  * even though possesses a number.
  76  * Note that all reference types are erased to "L", which stands for {@code Object}.
  77  * All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}.
  78  * The other types stand for the usual primitive types.
  79  * <p>
  80  * Function invocation closely follows the static rules of the Java verifier.
  81  * Arguments and return values must exactly match when their "Name" types are
  82  * considered.
  83  * Conversions are allowed only if they do not change the erased type.
  84  * <ul>
  85  * <li>L = Object: casts are used freely to convert into and out of reference types
  86  * <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments})
  87  * <li>J = long: no implicit conversions
  88  * <li>F = float: no implicit conversions
  89  * <li>D = double: no implicit conversions
  90  * <li>V = void: a function result may be void if and only if its Name is of type "V"
  91  * </ul>
  92  * Although implicit conversions are not allowed, explicit ones can easily be
  93  * encoded by using temporary expressions which call type-transformed identity functions.
  94  * <p>
  95  * Examples:
  96  * <blockquote><pre>{@code
  97  * (a0:J)=>{ a0 }
  98  *     == identity(long)
  99  * (a0:I)=>{ t1:V = System.out#println(a0); void }
 100  *     == System.out#println(int)
 101  * (a0:L)=>{ t1:V = System.out#println(a0); a0 }
 102  *     == identity, with printing side-effect
 103  * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
 104  *                 t3:L = BoundMethodHandle#target(a0);
 105  *                 t4:L = MethodHandle#invoke(t3, t2, a1); t4 }
 106  *     == general invoker for unary insertArgument combination
 107  * (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0);
 108  *                 t3:L = MethodHandle#invoke(t2, a1);
 109  *                 t4:L = FilterMethodHandle#target(a0);
 110  *                 t5:L = MethodHandle#invoke(t4, t3); t5 }
 111  *     == general invoker for unary filterArgument combination
 112  * (a0:L, a1:L)=>{ ...(same as previous example)...
 113  *                 t5:L = MethodHandle#invoke(t4, t3, a1); t5 }
 114  *     == general invoker for unary/unary foldArgument combination
 115  * (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 }
 116  *     == invoker for identity method handle which performs i2l
 117  * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
 118  *                 t3:L = Class#cast(t2,a1); t3 }
 119  *     == invoker for identity method handle which performs cast
 120  * }</pre></blockquote>
 121  * <p>
 122  * @author John Rose, JSR 292 EG
 123  */
 124 class LambdaForm {
 125     final int arity;
 126     final int result;
 127     final boolean forceInline;
 128     final MethodHandle customized;
 129     @Stable final Name[] names;
 130     final String debugName;
 131     final Kind kind;
 132     MemberName vmentry;   // low-level behavior, or null if not yet prepared
 133     private boolean isCompiled;
 134 
 135     // Either a LambdaForm cache (managed by LambdaFormEditor) or a link to uncustomized version (for customized LF)
 136     volatile Object transformCache;
 137 
 138     public static final int VOID_RESULT = -1, LAST_RESULT = -2;
 139 
 140     enum BasicType {
 141         L_TYPE('L', Object.class, Wrapper.OBJECT),  // all reference types
 142         I_TYPE('I', int.class,    Wrapper.INT),
 143         J_TYPE('J', long.class,   Wrapper.LONG),
 144         F_TYPE('F', float.class,  Wrapper.FLOAT),
 145         D_TYPE('D', double.class, Wrapper.DOUBLE),  // all primitive types
 146         V_TYPE('V', void.class,   Wrapper.VOID);    // not valid in all contexts
 147 
 148         static final BasicType[] ALL_TYPES = BasicType.values();
 149         static final BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1);
 150 
 151         static final int ARG_TYPE_LIMIT = ARG_TYPES.length;
 152         static final int TYPE_LIMIT = ALL_TYPES.length;
 153 
 154         final char btChar;
 155         final Class<?> btClass;
 156         final Wrapper btWrapper;
 157 
 158         private BasicType(char btChar, Class<?> btClass, Wrapper wrapper) {
 159             this.btChar = btChar;
 160             this.btClass = btClass;
 161             this.btWrapper = wrapper;
 162         }
 163 
 164         char basicTypeChar() {
 165             return btChar;
 166         }
 167         Class<?> basicTypeClass() {
 168             return btClass;
 169         }
 170         Wrapper basicTypeWrapper() {
 171             return btWrapper;
 172         }
 173         int basicTypeSlots() {
 174             return btWrapper.stackSlots();
 175         }
 176 
 177         static BasicType basicType(byte type) {
 178             return ALL_TYPES[type];
 179         }
 180         static BasicType basicType(char type) {
 181             switch (type) {
 182                 case 'L': return L_TYPE;
 183                 case 'I': return I_TYPE;
 184                 case 'J': return J_TYPE;
 185                 case 'F': return F_TYPE;
 186                 case 'D': return D_TYPE;
 187                 case 'V': return V_TYPE;
 188                 // all subword types are represented as ints
 189                 case 'Z':
 190                 case 'B':
 191                 case 'S':
 192                 case 'C':
 193                     return I_TYPE;
 194                 default:
 195                     throw newInternalError("Unknown type char: '"+type+"'");
 196             }
 197         }
 198         static BasicType basicType(Wrapper type) {
 199             char c = type.basicTypeChar();
 200             return basicType(c);
 201         }
 202         static BasicType basicType(Class<?> type) {
 203             if (!type.isPrimitive())  return L_TYPE;
 204             return basicType(Wrapper.forPrimitiveType(type));
 205         }
 206         static BasicType[] basicTypes(String types) {
 207             BasicType[] btypes = new BasicType[types.length()];
 208             for (int i = 0; i < btypes.length; i++) {
 209                 btypes[i] = basicType(types.charAt(i));
 210             }
 211             return btypes;
 212         }
 213         static String basicTypeDesc(BasicType[] types) {
 214             if (types == null) {
 215                 return null;
 216             }
 217             if (types.length == 0) {
 218                 return "";
 219             }
 220             StringBuilder sb = new StringBuilder();
 221             for (BasicType bt : types) {
 222                 sb.append(bt.basicTypeChar());
 223             }
 224             return sb.toString();
 225         }
 226         static int[] basicTypeOrds(BasicType[] types) {
 227             if (types == null) {
 228                 return null;
 229             }
 230             int[] a = new int[types.length];
 231             for(int i = 0; i < types.length; ++i) {
 232                 a[i] = types[i].ordinal();
 233             }
 234             return a;
 235         }
 236 
 237         static char basicTypeChar(Class<?> type) {
 238             return basicType(type).btChar;
 239         }
 240 
 241         static byte[] basicTypesOrd(Class<?>[] types) {
 242             byte[] ords = new byte[types.length];
 243             for (int i = 0; i < ords.length; i++) {
 244                 ords[i] = (byte)basicType(types[i]).ordinal();
 245             }
 246             return ords;
 247         }
 248 
 249         static boolean isBasicTypeChar(char c) {
 250             return "LIJFDV".indexOf(c) >= 0;
 251         }
 252         static boolean isArgBasicTypeChar(char c) {
 253             return "LIJFD".indexOf(c) >= 0;
 254         }
 255 
 256         static { assert(checkBasicType()); }
 257         private static boolean checkBasicType() {
 258             for (int i = 0; i < ARG_TYPE_LIMIT; i++) {
 259                 assert ARG_TYPES[i].ordinal() == i;
 260                 assert ARG_TYPES[i] == ALL_TYPES[i];
 261             }
 262             for (int i = 0; i < TYPE_LIMIT; i++) {
 263                 assert ALL_TYPES[i].ordinal() == i;
 264             }
 265             assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE;
 266             assert !Arrays.asList(ARG_TYPES).contains(V_TYPE);
 267             return true;
 268         }
 269     }
 270 
 271     enum Kind {
 272         GENERIC(""),
 273         BOUND_REINVOKER("BMH.reinvoke"),
 274         REINVOKER("MH.reinvoke"),
 275         DELEGATE("MH.delegate"),
 276         DIRECT_INVOKE_VIRTUAL("DMH.invokeVirtual"),
 277         DIRECT_INVOKE_SPECIAL("DMH.invokeSpecial"),
 278         DIRECT_INVOKE_STATIC("DMH.invokeStatic"),
 279         DIRECT_NEW_INVOKE_SPECIAL("DMH.newInvokeSpecial"),
 280         DIRECT_INVOKE_INTERFACE("DMH.invokeInterface"),
 281         DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit");
 282 
 283         final String defaultLambdaName;
 284         final String methodName;
 285 
 286         private Kind(String defaultLambdaName) {
 287             this.defaultLambdaName = defaultLambdaName;
 288             int p = defaultLambdaName.indexOf('.');
 289             if (p > -1) {
 290                 this.methodName = defaultLambdaName.substring(p + 1);
 291             } else {
 292                 this.methodName = defaultLambdaName;
 293             }
 294         }
 295     }
 296 
 297     LambdaForm(String debugName,
 298                int arity, Name[] names, int result) {
 299         this(debugName, arity, names, result, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
 300     }
 301     LambdaForm(String debugName,
 302                int arity, Name[] names, int result, Kind kind) {
 303         this(debugName, arity, names, result, /*forceInline=*/true, /*customized=*/null, kind);
 304     }
 305     LambdaForm(String debugName,
 306                int arity, Name[] names, int result, boolean forceInline, MethodHandle customized) {
 307         this(debugName, arity, names, result, forceInline, customized, Kind.GENERIC);
 308     }
 309     LambdaForm(String debugName,
 310                int arity, Name[] names, int result, boolean forceInline, MethodHandle customized, Kind kind) {
 311         assert(namesOK(arity, names));
 312         this.arity = arity;
 313         this.result = fixResult(result, names);
 314         this.names = names.clone();
 315         this.debugName = fixDebugName(debugName);
 316         this.forceInline = forceInline;
 317         this.customized = customized;
 318         this.kind = kind;
 319         int maxOutArity = normalize();
 320         if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) {
 321             // Cannot use LF interpreter on very high arity expressions.
 322             assert(maxOutArity <= MethodType.MAX_JVM_ARITY);
 323             compileToBytecode();
 324         }
 325     }
 326     LambdaForm(String debugName,
 327                int arity, Name[] names) {
 328         this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
 329     }
 330     LambdaForm(String debugName,
 331                int arity, Name[] names, boolean forceInline) {
 332         this(debugName, arity, names, LAST_RESULT, forceInline, /*customized=*/null, Kind.GENERIC);
 333     }
 334     LambdaForm(String debugName,
 335                int arity, Name[] names, boolean forceInline, Kind kind) {
 336         this(debugName, arity, names, LAST_RESULT, forceInline, /*customized=*/null, kind);
 337     }
 338     LambdaForm(String debugName,
 339                Name[] formals, Name[] temps, Name result) {
 340         this(debugName,
 341              formals.length, buildNames(formals, temps, result), LAST_RESULT, /*forceInline=*/true, /*customized=*/null);
 342     }
 343     LambdaForm(String debugName,
 344                Name[] formals, Name[] temps, Name result, boolean forceInline) {
 345         this(debugName,
 346              formals.length, buildNames(formals, temps, result), LAST_RESULT, forceInline, /*customized=*/null);
 347     }
 348 
 349     private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
 350         int arity = formals.length;
 351         int length = arity + temps.length + (result == null ? 0 : 1);
 352         Name[] names = Arrays.copyOf(formals, length);
 353         System.arraycopy(temps, 0, names, arity, temps.length);
 354         if (result != null)
 355             names[length - 1] = result;
 356         return names;
 357     }
 358 
 359     private LambdaForm(MethodType mt) {
 360         // Make a blank lambda form, which returns a constant zero or null.
 361         // It is used as a template for managing the invocation of similar forms that are non-empty.
 362         // Called only from getPreparedForm.
 363         this.arity = mt.parameterCount();
 364         this.result = (mt.returnType() == void.class || mt.returnType() == Void.class) ? -1 : arity;
 365         this.names = buildEmptyNames(arity, mt, result == -1);
 366         this.debugName = "LF.zero";
 367         this.forceInline = true;
 368         this.customized = null;
 369         this.kind = Kind.GENERIC;
 370         assert(nameRefsAreLegal());
 371         assert(isEmpty());
 372         String sig = null;
 373         assert(isValidSignature(sig = basicTypeSignature()));
 374         assert(sig.equals(basicTypeSignature())) : sig + " != " + basicTypeSignature();
 375     }
 376 
 377     private static Name[] buildEmptyNames(int arity, MethodType mt, boolean isVoid) {
 378         Name[] names = arguments(isVoid ? 0 : 1, mt);
 379         if (!isVoid) {
 380             Name zero = new Name(constantZero(basicType(mt.returnType())));
 381             names[arity] = zero.newIndex(arity);
 382         }
 383         return names;
 384     }
 385 
 386     private static int fixResult(int result, Name[] names) {
 387         if (result == LAST_RESULT)
 388             result = names.length - 1;  // might still be void
 389         if (result >= 0 && names[result].type == V_TYPE)
 390             result = VOID_RESULT;
 391         return result;
 392     }
 393 
 394     private static String fixDebugName(String debugName) {
 395         if (DEBUG_NAME_COUNTERS != null) {
 396             int under = debugName.indexOf('_');
 397             int length = debugName.length();
 398             if (under < 0)  under = length;
 399             String debugNameStem = debugName.substring(0, under);
 400             Integer ctr;
 401             synchronized (DEBUG_NAME_COUNTERS) {
 402                 ctr = DEBUG_NAME_COUNTERS.get(debugNameStem);
 403                 if (ctr == null)  ctr = 0;
 404                 DEBUG_NAME_COUNTERS.put(debugNameStem, ctr+1);
 405             }
 406             StringBuilder buf = new StringBuilder(debugNameStem);
 407             buf.append('_');
 408             int leadingZero = buf.length();
 409             buf.append((int) ctr);
 410             for (int i = buf.length() - leadingZero; i < 3; i++)
 411                 buf.insert(leadingZero, '0');
 412             if (under < length) {
 413                 ++under;    // skip "_"
 414                 while (under < length && Character.isDigit(debugName.charAt(under))) {
 415                     ++under;
 416                 }
 417                 if (under < length && debugName.charAt(under) == '_')  ++under;
 418                 if (under < length)
 419                     buf.append('_').append(debugName, under, length);
 420             }
 421             return buf.toString();
 422         }
 423         return debugName;
 424     }
 425 
 426     private static boolean namesOK(int arity, Name[] names) {
 427         for (int i = 0; i < names.length; i++) {
 428             Name n = names[i];
 429             assert(n != null) : "n is null";
 430             if (i < arity)
 431                 assert( n.isParam()) : n + " is not param at " + i;
 432             else
 433                 assert(!n.isParam()) : n + " is param at " + i;
 434         }
 435         return true;
 436     }
 437 
 438     /** Customize LambdaForm for a particular MethodHandle */
 439     LambdaForm customize(MethodHandle mh) {
 440         LambdaForm customForm = new LambdaForm(debugName, arity, names, result, forceInline, mh, kind);
 441         if (COMPILE_THRESHOLD >= 0 && isCompiled) {
 442             // If shared LambdaForm has been compiled, compile customized version as well.
 443             customForm.compileToBytecode();
 444         }
 445         customForm.transformCache = this; // LambdaFormEditor should always use uncustomized form.
 446         return customForm;
 447     }
 448 
 449     /** Get uncustomized flavor of the LambdaForm */
 450     LambdaForm uncustomize() {
 451         if (customized == null) {
 452             return this;
 453         }
 454         assert(transformCache != null); // Customized LambdaForm should always has a link to uncustomized version.
 455         LambdaForm uncustomizedForm = (LambdaForm)transformCache;
 456         if (COMPILE_THRESHOLD >= 0 && isCompiled) {
 457             // If customized LambdaForm has been compiled, compile uncustomized version as well.
 458             uncustomizedForm.compileToBytecode();
 459         }
 460         return uncustomizedForm;
 461     }
 462 
 463     /** Renumber and/or replace params so that they are interned and canonically numbered.
 464      *  @return maximum argument list length among the names (since we have to pass over them anyway)
 465      */
 466     private int normalize() {
 467         Name[] oldNames = null;
 468         int maxOutArity = 0;
 469         int changesStart = 0;
 470         for (int i = 0; i < names.length; i++) {
 471             Name n = names[i];
 472             if (!n.initIndex(i)) {
 473                 if (oldNames == null) {
 474                     oldNames = names.clone();
 475                     changesStart = i;
 476                 }
 477                 names[i] = n.cloneWithIndex(i);
 478             }
 479             if (n.arguments != null && maxOutArity < n.arguments.length)
 480                 maxOutArity = n.arguments.length;
 481         }
 482         if (oldNames != null) {
 483             int startFixing = arity;
 484             if (startFixing <= changesStart)
 485                 startFixing = changesStart+1;
 486             for (int i = startFixing; i < names.length; i++) {
 487                 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i);
 488                 names[i] = fixed.newIndex(i);
 489             }
 490         }
 491         assert(nameRefsAreLegal());
 492         int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT);
 493         boolean needIntern = false;
 494         for (int i = 0; i < maxInterned; i++) {
 495             Name n = names[i], n2 = internArgument(n);
 496             if (n != n2) {
 497                 names[i] = n2;
 498                 needIntern = true;
 499             }
 500         }
 501         if (needIntern) {
 502             for (int i = arity; i < names.length; i++) {
 503                 names[i].internArguments();
 504             }
 505         }
 506         assert(nameRefsAreLegal());
 507         return maxOutArity;
 508     }
 509 
 510     /**
 511      * Check that all embedded Name references are localizable to this lambda,
 512      * and are properly ordered after their corresponding definitions.
 513      * <p>
 514      * Note that a Name can be local to multiple lambdas, as long as
 515      * it possesses the same index in each use site.
 516      * This allows Name references to be freely reused to construct
 517      * fresh lambdas, without confusion.
 518      */
 519     boolean nameRefsAreLegal() {
 520         assert(arity >= 0 && arity <= names.length);
 521         assert(result >= -1 && result < names.length);
 522         // Do all names possess an index consistent with their local definition order?
 523         for (int i = 0; i < arity; i++) {
 524             Name n = names[i];
 525             assert(n.index() == i) : Arrays.asList(n.index(), i);
 526             assert(n.isParam());
 527         }
 528         // Also, do all local name references
 529         for (int i = arity; i < names.length; i++) {
 530             Name n = names[i];
 531             assert(n.index() == i);
 532             for (Object arg : n.arguments) {
 533                 if (arg instanceof Name) {
 534                     Name n2 = (Name) arg;
 535                     int i2 = n2.index;
 536                     assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length;
 537                     assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this);
 538                     assert(i2 < i);  // ref must come after def!
 539                 }
 540             }
 541         }
 542         return true;
 543     }
 544 
 545     /** Invoke this form on the given arguments. */
 546     // final Object invoke(Object... args) throws Throwable {
 547     //     // NYI: fit this into the fast path?
 548     //     return interpretWithArguments(args);
 549     // }
 550 
 551     /** Report the return type. */
 552     BasicType returnType() {
 553         if (result < 0)  return V_TYPE;
 554         Name n = names[result];
 555         return n.type;
 556     }
 557 
 558     /** Report the N-th argument type. */
 559     BasicType parameterType(int n) {
 560         return parameter(n).type;
 561     }
 562 
 563     /** Report the N-th argument name. */
 564     Name parameter(int n) {
 565         assert(n < arity);
 566         Name param = names[n];
 567         assert(param.isParam());
 568         return param;
 569     }
 570 
 571     /** Report the N-th argument type constraint. */
 572     Object parameterConstraint(int n) {
 573         return parameter(n).constraint;
 574     }
 575 
 576     /** Report the arity. */
 577     int arity() {
 578         return arity;
 579     }
 580 
 581     /** Report the number of expressions (non-parameter names). */
 582     int expressionCount() {
 583         return names.length - arity;
 584     }
 585 
 586     /** Return the method type corresponding to my basic type signature. */
 587     MethodType methodType() {
 588         Class<?>[] ptypes = new Class<?>[arity];
 589         for (int i = 0; i < arity; ++i) {
 590             ptypes[i] = parameterType(i).btClass;
 591         }
 592         return MethodType.methodType(returnType().btClass, ptypes);
 593     }
 594 
 595     /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */
 596     final String basicTypeSignature() {
 597         StringBuilder buf = new StringBuilder(arity() + 3);
 598         for (int i = 0, a = arity(); i < a; i++)
 599             buf.append(parameterType(i).basicTypeChar());
 600         return buf.append('_').append(returnType().basicTypeChar()).toString();
 601     }
 602     static int signatureArity(String sig) {
 603         assert(isValidSignature(sig));
 604         return sig.indexOf('_');
 605     }
 606     static BasicType signatureReturn(String sig) {
 607         return basicType(sig.charAt(signatureArity(sig) + 1));
 608     }
 609     static boolean isValidSignature(String sig) {
 610         int arity = sig.indexOf('_');
 611         if (arity < 0)  return false;  // must be of the form *_*
 612         int siglen = sig.length();
 613         if (siglen != arity + 2)  return false;  // *_X
 614         for (int i = 0; i < siglen; i++) {
 615             if (i == arity)  continue;  // skip '_'
 616             char c = sig.charAt(i);
 617             if (c == 'V')
 618                 return (i == siglen - 1 && arity == siglen - 2);
 619             if (!isArgBasicTypeChar(c))  return false; // must be [LIJFD]
 620         }
 621         return true;  // [LIJFD]*_[LIJFDV]
 622     }
 623     static MethodType signatureType(String sig) {
 624         Class<?>[] ptypes = new Class<?>[signatureArity(sig)];
 625         for (int i = 0; i < ptypes.length; i++)
 626             ptypes[i] = basicType(sig.charAt(i)).btClass;
 627         Class<?> rtype = signatureReturn(sig).btClass;
 628         return MethodType.methodType(rtype, ptypes);
 629     }
 630 
 631     /**
 632      * Check if i-th name is a call to MethodHandleImpl.selectAlternative.
 633      */
 634     boolean isSelectAlternative(int pos) {
 635         // selectAlternative idiom:
 636         //   t_{n}:L=MethodHandleImpl.selectAlternative(...)
 637         //   t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 638         if (pos+1 >= names.length)  return false;
 639         Name name0 = names[pos];
 640         Name name1 = names[pos+1];
 641         return name0.refersTo(MethodHandleImpl.class, "selectAlternative") &&
 642                 name1.isInvokeBasic() &&
 643                 name1.lastUseIndex(name0) == 0 && // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 644                 lastUseIndex(name0) == pos+1;     // t_{n} is local: used only in t_{n+1}
 645     }
 646 
 647     private boolean isMatchingIdiom(int pos, String idiomName, int nArgs) {
 648         if (pos+2 >= names.length)  return false;
 649         Name name0 = names[pos];
 650         Name name1 = names[pos+1];
 651         Name name2 = names[pos+2];
 652         return name1.refersTo(MethodHandleImpl.class, idiomName) &&
 653                 name0.isInvokeBasic() &&
 654                 name2.isInvokeBasic() &&
 655                 name1.lastUseIndex(name0) == nArgs && // t_{n+1}:L=MethodHandleImpl.<invoker>(<args>, t_{n});
 656                 lastUseIndex(name0) == pos+1 &&       // t_{n} is local: used only in t_{n+1}
 657                 name2.lastUseIndex(name1) == 1 &&     // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 658                 lastUseIndex(name1) == pos+2;         // t_{n+1} is local: used only in t_{n+2}
 659     }
 660 
 661     /**
 662      * Check if i-th name is a start of GuardWithCatch idiom.
 663      */
 664     boolean isGuardWithCatch(int pos) {
 665         // GuardWithCatch idiom:
 666         //   t_{n}:L=MethodHandle.invokeBasic(...)
 667         //   t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
 668         //   t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 669         return isMatchingIdiom(pos, "guardWithCatch", 3);
 670     }
 671 
 672     /**
 673      * Check if i-th name is a start of the tryFinally idiom.
 674      */
 675     boolean isTryFinally(int pos) {
 676         // tryFinally idiom:
 677         //   t_{n}:L=MethodHandle.invokeBasic(...)
 678         //   t_{n+1}:L=MethodHandleImpl.tryFinally(*, *, t_{n})
 679         //   t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 680         return isMatchingIdiom(pos, "tryFinally", 2);
 681     }
 682 
 683     /**
 684      * Check if i-th name is a start of the loop idiom.
 685      */
 686     boolean isLoop(int pos) {
 687         // loop idiom:
 688         //   t_{n}:L=MethodHandle.invokeBasic(...)
 689         //   t_{n+1}:L=MethodHandleImpl.loop(types, *, *, *, *, t_{n})
 690         //   t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 691         return isMatchingIdiom(pos, "loop", 5);
 692     }
 693 
 694     /*
 695      * Code generation issues:
 696      *
 697      * Compiled LFs should be reusable in general.
 698      * The biggest issue is how to decide when to pull a name into
 699      * the bytecode, versus loading a reified form from the MH data.
 700      *
 701      * For example, an asType wrapper may require execution of a cast
 702      * after a call to a MH.  The target type of the cast can be placed
 703      * as a constant in the LF itself.  This will force the cast type
 704      * to be compiled into the bytecodes and native code for the MH.
 705      * Or, the target type of the cast can be erased in the LF, and
 706      * loaded from the MH data.  (Later on, if the MH as a whole is
 707      * inlined, the data will flow into the inlined instance of the LF,
 708      * as a constant, and the end result will be an optimal cast.)
 709      *
 710      * This erasure of cast types can be done with any use of
 711      * reference types.  It can also be done with whole method
 712      * handles.  Erasing a method handle might leave behind
 713      * LF code that executes correctly for any MH of a given
 714      * type, and load the required MH from the enclosing MH's data.
 715      * Or, the erasure might even erase the expected MT.
 716      *
 717      * Also, for direct MHs, the MemberName of the target
 718      * could be erased, and loaded from the containing direct MH.
 719      * As a simple case, a LF for all int-valued non-static
 720      * field getters would perform a cast on its input argument
 721      * (to non-constant base type derived from the MemberName)
 722      * and load an integer value from the input object
 723      * (at a non-constant offset also derived from the MemberName).
 724      * Such MN-erased LFs would be inlinable back to optimized
 725      * code, whenever a constant enclosing DMH is available
 726      * to supply a constant MN from its data.
 727      *
 728      * The main problem here is to keep LFs reasonably generic,
 729      * while ensuring that hot spots will inline good instances.
 730      * "Reasonably generic" means that we don't end up with
 731      * repeated versions of bytecode or machine code that do
 732      * not differ in their optimized form.  Repeated versions
 733      * of machine would have the undesirable overheads of
 734      * (a) redundant compilation work and (b) extra I$ pressure.
 735      * To control repeated versions, we need to be ready to
 736      * erase details from LFs and move them into MH data,
 737      * whevener those details are not relevant to significant
 738      * optimization.  "Significant" means optimization of
 739      * code that is actually hot.
 740      *
 741      * Achieving this may require dynamic splitting of MHs, by replacing
 742      * a generic LF with a more specialized one, on the same MH,
 743      * if (a) the MH is frequently executed and (b) the MH cannot
 744      * be inlined into a containing caller, such as an invokedynamic.
 745      *
 746      * Compiled LFs that are no longer used should be GC-able.
 747      * If they contain non-BCP references, they should be properly
 748      * interlinked with the class loader(s) that their embedded types
 749      * depend on.  This probably means that reusable compiled LFs
 750      * will be tabulated (indexed) on relevant class loaders,
 751      * or else that the tables that cache them will have weak links.
 752      */
 753 
 754     /**
 755      * Make this LF directly executable, as part of a MethodHandle.
 756      * Invariant:  Every MH which is invoked must prepare its LF
 757      * before invocation.
 758      * (In principle, the JVM could do this very lazily,
 759      * as a sort of pre-invocation linkage step.)
 760      */
 761     public void prepare() {
 762         if (COMPILE_THRESHOLD == 0 && !forceInterpretation() && !isCompiled) {
 763             compileToBytecode();
 764         }
 765         if (this.vmentry != null) {
 766             // already prepared (e.g., a primitive DMH invoker form)
 767             return;
 768         }
 769         MethodType mtype = methodType();
 770         LambdaForm prep = mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET);
 771         if (prep == null) {
 772             assert (isValidSignature(basicTypeSignature()));
 773             prep = new LambdaForm(mtype);
 774             prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(mtype);
 775             prep = mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep);
 776         }
 777         this.vmentry = prep.vmentry;
 778         // TO DO: Maybe add invokeGeneric, invokeWithArguments
 779     }
 780 
 781     private static @Stable PerfCounter LF_FAILED;
 782 
 783     private static PerfCounter failedCompilationCounter() {
 784         if (LF_FAILED == null) {
 785             LF_FAILED = PerfCounter.newPerfCounter("java.lang.invoke.failedLambdaFormCompilations");
 786         }
 787         return LF_FAILED;
 788     }
 789 
 790     /** Generate optimizable bytecode for this form. */
 791     void compileToBytecode() {
 792         if (forceInterpretation()) {
 793             return; // this should not be compiled
 794         }
 795         if (vmentry != null && isCompiled) {
 796             return;  // already compiled somehow
 797         }
 798         MethodType invokerType = methodType();
 799         assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType));
 800         try {
 801             vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType);
 802             if (TRACE_INTERPRETER)
 803                 traceInterpreter("compileToBytecode", this);
 804             isCompiled = true;
 805         } catch (InvokerBytecodeGenerator.BytecodeGenerationException bge) {
 806             // bytecode generation failed - mark this LambdaForm as to be run in interpretation mode only
 807             invocationCounter = -1;
 808             failedCompilationCounter().increment();
 809             if (LOG_LF_COMPILATION_FAILURE) {
 810                 System.out.println("LambdaForm compilation failed: " + this);
 811                 bge.printStackTrace(System.out);
 812             }
 813         } catch (Error | Exception e) {
 814             throw newInternalError(this.toString(), e);






















 815         }
 816     }
 817 
 818     private static void computeInitialPreparedForms() {
 819         // Find all predefined invokers and associate them with canonical empty lambda forms.
 820         for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
 821             if (!m.isStatic() || !m.isPackage())  continue;
 822             MethodType mt = m.getMethodType();
 823             if (mt.parameterCount() > 0 &&
 824                 mt.parameterType(0) == MethodHandle.class &&
 825                 m.getName().startsWith("interpret_")) {
 826                 String sig = null;
 827                 assert((sig = basicTypeSignature(mt)) != null &&
 828                         m.getName().equals("interpret" + sig.substring(sig.indexOf('_'))));
 829                 LambdaForm form = new LambdaForm(mt);
 830                 form.vmentry = m;
 831                 form = mt.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, form);
 832             }
 833         }
 834     }
 835 
 836     // Set this false to disable use of the interpret_L methods defined in this file.
 837     private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true;
 838 
 839     // The following are predefined exact invokers.  The system must build
 840     // a separate invoker for each distinct signature.
 841     static Object interpret_L(MethodHandle mh) throws Throwable {
 842         Object[] av = {mh};
 843         String sig = null;
 844         assert(argumentTypesMatch(sig = "L_L", av));
 845         Object res = mh.form.interpretWithArguments(av);
 846         assert(returnTypesMatch(sig, av, res));
 847         return res;
 848     }
 849     static Object interpret_L(MethodHandle mh, Object x1) throws Throwable {
 850         Object[] av = {mh, x1};
 851         String sig = null;
 852         assert(argumentTypesMatch(sig = "LL_L", av));
 853         Object res = mh.form.interpretWithArguments(av);
 854         assert(returnTypesMatch(sig, av, res));
 855         return res;
 856     }
 857     static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable {
 858         Object[] av = {mh, x1, x2};
 859         String sig = null;
 860         assert(argumentTypesMatch(sig = "LLL_L", av));
 861         Object res = mh.form.interpretWithArguments(av);
 862         assert(returnTypesMatch(sig, av, res));
 863         return res;
 864     }
 865 
 866     // The next few routines are called only from assert expressions
 867     // They verify that the built-in invokers process the correct raw data types.
 868     private static boolean argumentTypesMatch(String sig, Object[] av) {
 869         int arity = signatureArity(sig);
 870         assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity;
 871         assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0];
 872         MethodHandle mh = (MethodHandle) av[0];
 873         MethodType mt = mh.type();
 874         assert(mt.parameterCount() == arity-1);
 875         for (int i = 0; i < av.length; i++) {
 876             Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1));
 877             assert(valueMatches(basicType(sig.charAt(i)), pt, av[i]));
 878         }
 879         return true;
 880     }
 881     private static boolean valueMatches(BasicType tc, Class<?> type, Object x) {
 882         // The following line is needed because (...)void method handles can use non-void invokers
 883         if (type == void.class)  tc = V_TYPE;   // can drop any kind of value
 884         assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type);
 885         switch (tc) {
 886         case I_TYPE: assert checkInt(type, x)   : "checkInt(" + type + "," + x +")";   break;
 887         case J_TYPE: assert x instanceof Long   : "instanceof Long: " + x;             break;
 888         case F_TYPE: assert x instanceof Float  : "instanceof Float: " + x;            break;
 889         case D_TYPE: assert x instanceof Double : "instanceof Double: " + x;           break;
 890         case L_TYPE: assert checkRef(type, x)   : "checkRef(" + type + "," + x + ")";  break;
 891         case V_TYPE: break;  // allow anything here; will be dropped
 892         default:  assert(false);
 893         }
 894         return true;
 895     }
 896     private static boolean returnTypesMatch(String sig, Object[] av, Object res) {
 897         MethodHandle mh = (MethodHandle) av[0];
 898         return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
 899     }
 900     private static boolean checkInt(Class<?> type, Object x) {
 901         assert(x instanceof Integer);
 902         if (type == int.class)  return true;
 903         Wrapper w = Wrapper.forBasicType(type);
 904         assert(w.isSubwordOrInt());
 905         Object x1 = Wrapper.INT.wrap(w.wrap(x));
 906         return x.equals(x1);
 907     }
 908     private static boolean checkRef(Class<?> type, Object x) {
 909         assert(!type.isPrimitive());
 910         if (x == null)  return true;
 911         if (type.isInterface())  return true;
 912         return type.isInstance(x);
 913     }
 914 
 915     /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */
 916     private static final int COMPILE_THRESHOLD;
 917     static {
 918         COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD);
 919     }
 920     private int invocationCounter = 0; // a value of -1 indicates LambdaForm interpretation mode forever
 921 
 922     private boolean forceInterpretation() {
 923         return invocationCounter == -1;
 924     }
 925 
 926     @Hidden
 927     @DontInline
 928     /** Interpretively invoke this form on the given arguments. */
 929     Object interpretWithArguments(Object... argumentValues) throws Throwable {
 930         if (TRACE_INTERPRETER)
 931             return interpretWithArgumentsTracing(argumentValues);
 932         checkInvocationCounter();
 933         assert(arityCheck(argumentValues));
 934         Object[] values = Arrays.copyOf(argumentValues, names.length);
 935         for (int i = argumentValues.length; i < values.length; i++) {
 936             values[i] = interpretName(names[i], values);
 937         }
 938         Object rv = (result < 0) ? null : values[result];
 939         assert(resultCheck(argumentValues, rv));
 940         return rv;
 941     }
 942 
 943     @Hidden
 944     @DontInline
 945     /** Evaluate a single Name within this form, applying its function to its arguments. */
 946     Object interpretName(Name name, Object[] values) throws Throwable {
 947         if (TRACE_INTERPRETER)
 948             traceInterpreter("| interpretName", name.debugString(), (Object[]) null);
 949         Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class);
 950         for (int i = 0; i < arguments.length; i++) {
 951             Object a = arguments[i];
 952             if (a instanceof Name) {
 953                 int i2 = ((Name)a).index();
 954                 assert(names[i2] == a);
 955                 a = values[i2];
 956                 arguments[i] = a;
 957             }
 958         }
 959         return name.function.invokeWithArguments(arguments);
 960     }
 961 
 962     private void checkInvocationCounter() {
 963         if (COMPILE_THRESHOLD != 0 &&
 964             !forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) {
 965             invocationCounter++;  // benign race
 966             if (invocationCounter >= COMPILE_THRESHOLD) {
 967                 // Replace vmentry with a bytecode version of this LF.
 968                 compileToBytecode();
 969             }
 970         }
 971     }
 972     Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable {
 973         traceInterpreter("[ interpretWithArguments", this, argumentValues);
 974         if (!forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) {
 975             int ctr = invocationCounter++;  // benign race
 976             traceInterpreter("| invocationCounter", ctr);
 977             if (invocationCounter >= COMPILE_THRESHOLD) {
 978                 compileToBytecode();
 979             }
 980         }
 981         Object rval;
 982         try {
 983             assert(arityCheck(argumentValues));
 984             Object[] values = Arrays.copyOf(argumentValues, names.length);
 985             for (int i = argumentValues.length; i < values.length; i++) {
 986                 values[i] = interpretName(names[i], values);
 987             }
 988             rval = (result < 0) ? null : values[result];
 989         } catch (Throwable ex) {
 990             traceInterpreter("] throw =>", ex);
 991             throw ex;
 992         }
 993         traceInterpreter("] return =>", rval);
 994         return rval;
 995     }
 996 
 997     static void traceInterpreter(String event, Object obj, Object... args) {
 998         if (TRACE_INTERPRETER) {
 999             System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
1000         }
1001     }
1002     static void traceInterpreter(String event, Object obj) {
1003         traceInterpreter(event, obj, (Object[])null);
1004     }
1005     private boolean arityCheck(Object[] argumentValues) {
1006         assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
1007         // also check that the leading (receiver) argument is somehow bound to this LF:
1008         assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
1009         MethodHandle mh = (MethodHandle) argumentValues[0];
1010         assert(mh.internalForm() == this);
1011         // note:  argument #0 could also be an interface wrapper, in the future
1012         argumentTypesMatch(basicTypeSignature(), argumentValues);
1013         return true;
1014     }
1015     private boolean resultCheck(Object[] argumentValues, Object result) {
1016         MethodHandle mh = (MethodHandle) argumentValues[0];
1017         MethodType mt = mh.type();
1018         assert(valueMatches(returnType(), mt.returnType(), result));
1019         return true;
1020     }
1021 
1022     private boolean isEmpty() {
1023         if (result < 0)
1024             return (names.length == arity);
1025         else if (result == arity && names.length == arity + 1)
1026             return names[arity].isConstantZero();
1027         else
1028             return false;
1029     }
1030 
1031     public String toString() {
1032         StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
1033         for (int i = 0; i < names.length; i++) {
1034             if (i == arity)  buf.append(")=>{");
1035             Name n = names[i];
1036             if (i >= arity)  buf.append("\n    ");
1037             buf.append(n.paramString());
1038             if (i < arity) {
1039                 if (i+1 < arity)  buf.append(",");
1040                 continue;
1041             }
1042             buf.append("=").append(n.exprString());
1043             buf.append(";");
1044         }
1045         if (arity == names.length)  buf.append(")=>{");
1046         buf.append(result < 0 ? "void" : names[result]).append("}");
1047         if (TRACE_INTERPRETER) {
1048             // Extra verbosity:
1049             buf.append(":").append(basicTypeSignature());
1050             buf.append("/").append(vmentry);
1051         }
1052         return buf.toString();
1053     }
1054 
1055     @Override
1056     public boolean equals(Object obj) {
1057         return obj instanceof LambdaForm && equals((LambdaForm)obj);
1058     }
1059     public boolean equals(LambdaForm that) {
1060         if (this.result != that.result)  return false;
1061         return Arrays.equals(this.names, that.names);
1062     }
1063     public int hashCode() {
1064         return result + 31 * Arrays.hashCode(names);
1065     }
1066     LambdaFormEditor editor() {
1067         return LambdaFormEditor.lambdaFormEditor(this);
1068     }
1069 
1070     boolean contains(Name name) {
1071         int pos = name.index();
1072         if (pos >= 0) {
1073             return pos < names.length && name.equals(names[pos]);
1074         }
1075         for (int i = arity; i < names.length; i++) {
1076             if (name.equals(names[i]))
1077                 return true;
1078         }
1079         return false;
1080     }
1081 
1082     static class NamedFunction {
1083         final MemberName member;
1084         private @Stable MethodHandle resolvedHandle;
1085         @Stable MethodHandle invoker;
1086 
1087         NamedFunction(MethodHandle resolvedHandle) {
1088             this(resolvedHandle.internalMemberName(), resolvedHandle);
1089         }
1090         NamedFunction(MemberName member, MethodHandle resolvedHandle) {
1091             this.member = member;
1092             this.resolvedHandle = resolvedHandle;
1093              // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest.
1094              //assert(!isInvokeBasic(member));
1095         }
1096         NamedFunction(MethodType basicInvokerType) {
1097             assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
1098             if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
1099                 this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
1100                 this.member = resolvedHandle.internalMemberName();
1101             } else {
1102                 // necessary to pass BigArityTest
1103                 this.member = Invokers.invokeBasicMethod(basicInvokerType);
1104             }
1105             assert(isInvokeBasic(member));
1106         }
1107 
1108         private static boolean isInvokeBasic(MemberName member) {
1109             return member != null &&
1110                    member.getDeclaringClass() == MethodHandle.class &&
1111                   "invokeBasic".equals(member.getName());
1112         }
1113 
1114         // The next 2 constructors are used to break circular dependencies on MH.invokeStatic, etc.
1115         // Any LambdaForm containing such a member is not interpretable.
1116         // This is OK, since all such LFs are prepared with special primitive vmentry points.
1117         // And even without the resolvedHandle, the name can still be compiled and optimized.
1118         NamedFunction(Method method) {
1119             this(new MemberName(method));
1120         }
1121         NamedFunction(MemberName member) {
1122             this(member, null);
1123         }
1124 
1125         MethodHandle resolvedHandle() {
1126             if (resolvedHandle == null)  resolve();
1127             return resolvedHandle;
1128         }
1129 
1130         synchronized void resolve() {
1131             if (resolvedHandle == null) {
1132                 resolvedHandle = DirectMethodHandle.make(member);
1133             }
1134         }
1135 
1136         @Override
1137         public boolean equals(Object other) {
1138             if (this == other) return true;
1139             if (other == null) return false;
1140             if (!(other instanceof NamedFunction)) return false;
1141             NamedFunction that = (NamedFunction) other;
1142             return this.member != null && this.member.equals(that.member);
1143         }
1144 
1145         @Override
1146         public int hashCode() {
1147             if (member != null)
1148                 return member.hashCode();
1149             return super.hashCode();
1150         }
1151 
1152         // Put the predefined NamedFunction invokers into the table.
1153         static void initializeInvokers() {
1154             for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
1155                 if (!m.isStatic() || !m.isPackage())  continue;
1156                 MethodType type = m.getMethodType();
1157                 if (type.equals(INVOKER_METHOD_TYPE) &&
1158                     m.getName().startsWith("invoke_")) {
1159                     String sig = m.getName().substring("invoke_".length());
1160                     int arity = LambdaForm.signatureArity(sig);
1161                     MethodType srcType = MethodType.genericMethodType(arity);
1162                     if (LambdaForm.signatureReturn(sig) == V_TYPE)
1163                         srcType = srcType.changeReturnType(void.class);
1164                     MethodTypeForm typeForm = srcType.form();
1165                     typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, DirectMethodHandle.make(m));
1166                 }
1167             }
1168         }
1169 
1170         // The following are predefined NamedFunction invokers.  The system must build
1171         // a separate invoker for each distinct signature.
1172         /** void return type invokers. */
1173         @Hidden
1174         static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
1175             assert(arityCheck(0, void.class, mh, a));
1176             mh.invokeBasic();
1177             return null;
1178         }
1179         @Hidden
1180         static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
1181             assert(arityCheck(1, void.class, mh, a));
1182             mh.invokeBasic(a[0]);
1183             return null;
1184         }
1185         @Hidden
1186         static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
1187             assert(arityCheck(2, void.class, mh, a));
1188             mh.invokeBasic(a[0], a[1]);
1189             return null;
1190         }
1191         @Hidden
1192         static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
1193             assert(arityCheck(3, void.class, mh, a));
1194             mh.invokeBasic(a[0], a[1], a[2]);
1195             return null;
1196         }
1197         @Hidden
1198         static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1199             assert(arityCheck(4, void.class, mh, a));
1200             mh.invokeBasic(a[0], a[1], a[2], a[3]);
1201             return null;
1202         }
1203         @Hidden
1204         static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1205             assert(arityCheck(5, void.class, mh, a));
1206             mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1207             return null;
1208         }
1209         /** Object return type invokers. */
1210         @Hidden
1211         static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
1212             assert(arityCheck(0, mh, a));
1213             return mh.invokeBasic();
1214         }
1215         @Hidden
1216         static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
1217             assert(arityCheck(1, mh, a));
1218             return mh.invokeBasic(a[0]);
1219         }
1220         @Hidden
1221         static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
1222             assert(arityCheck(2, mh, a));
1223             return mh.invokeBasic(a[0], a[1]);
1224         }
1225         @Hidden
1226         static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
1227             assert(arityCheck(3, mh, a));
1228             return mh.invokeBasic(a[0], a[1], a[2]);
1229         }
1230         @Hidden
1231         static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1232             assert(arityCheck(4, mh, a));
1233             return mh.invokeBasic(a[0], a[1], a[2], a[3]);
1234         }
1235         @Hidden
1236         static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1237             assert(arityCheck(5, mh, a));
1238             return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1239         }
1240         private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) {
1241             return arityCheck(arity, Object.class, mh, a);
1242         }
1243         private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) {
1244             assert(a.length == arity)
1245                     : Arrays.asList(a.length, arity);
1246             assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
1247                     : Arrays.asList(mh, rtype, arity);
1248             MemberName member = mh.internalMemberName();
1249             if (isInvokeBasic(member)) {
1250                 assert(arity > 0);
1251                 assert(a[0] instanceof MethodHandle);
1252                 MethodHandle mh2 = (MethodHandle) a[0];
1253                 assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype))
1254                         : Arrays.asList(member, mh2, rtype, arity);
1255             }
1256             return true;
1257         }
1258 
1259         static final MethodType INVOKER_METHOD_TYPE =
1260             MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1261 
1262         private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1263             typeForm = typeForm.basicType().form();  // normalize to basic type
1264             MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1265             if (mh != null)  return mh;
1266             MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm);  // this could take a while
1267             mh = DirectMethodHandle.make(invoker);
1268             MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1269             if (mh2 != null)  return mh2;  // benign race
1270             if (!mh.type().equals(INVOKER_METHOD_TYPE))
1271                 throw newInternalError(mh.debugString());
1272             return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh);
1273         }
1274 
1275         @Hidden
1276         Object invokeWithArguments(Object... arguments) throws Throwable {
1277             // If we have a cached invoker, call it right away.
1278             // NOTE: The invoker always returns a reference value.
1279             if (TRACE_INTERPRETER)  return invokeWithArgumentsTracing(arguments);
1280             assert(checkArgumentTypes(arguments, methodType()));
1281             return invoker().invokeBasic(resolvedHandle(), arguments);
1282         }
1283 
1284         @Hidden
1285         Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
1286             Object rval;
1287             try {
1288                 traceInterpreter("[ call", this, arguments);
1289                 if (invoker == null) {
1290                     traceInterpreter("| getInvoker", this);
1291                     invoker();
1292                 }
1293                 // resolvedHandle might be uninitialized, ok for tracing
1294                 if (resolvedHandle == null) {
1295                     traceInterpreter("| resolve", this);
1296                     resolvedHandle();
1297                 }
1298                 assert(checkArgumentTypes(arguments, methodType()));
1299                 rval = invoker().invokeBasic(resolvedHandle(), arguments);
1300             } catch (Throwable ex) {
1301                 traceInterpreter("] throw =>", ex);
1302                 throw ex;
1303             }
1304             traceInterpreter("] return =>", rval);
1305             return rval;
1306         }
1307 
1308         private MethodHandle invoker() {
1309             if (invoker != null)  return invoker;
1310             // Get an invoker and cache it.
1311             return invoker = computeInvoker(methodType().form());
1312         }
1313 
1314         private static boolean checkArgumentTypes(Object[] arguments, MethodType methodType) {
1315             if (true)  return true;  // FIXME
1316             MethodType dstType = methodType.form().erasedType();
1317             MethodType srcType = dstType.basicType().wrap();
1318             Class<?>[] ptypes = new Class<?>[arguments.length];
1319             for (int i = 0; i < arguments.length; i++) {
1320                 Object arg = arguments[i];
1321                 Class<?> ptype = arg == null ? Object.class : arg.getClass();
1322                 // If the dest. type is a primitive we keep the
1323                 // argument type.
1324                 ptypes[i] = dstType.parameterType(i).isPrimitive() ? ptype : Object.class;
1325             }
1326             MethodType argType = MethodType.methodType(srcType.returnType(), ptypes).wrap();
1327             assert(argType.isConvertibleTo(srcType)) : "wrong argument types: cannot convert " + argType + " to " + srcType;
1328             return true;
1329         }
1330 
1331         MethodType methodType() {
1332             if (resolvedHandle != null)
1333                 return resolvedHandle.type();
1334             else
1335                 // only for certain internal LFs during bootstrapping
1336                 return member.getInvocationType();
1337         }
1338 
1339         MemberName member() {
1340             assert(assertMemberIsConsistent());
1341             return member;
1342         }
1343 
1344         // Called only from assert.
1345         private boolean assertMemberIsConsistent() {
1346             if (resolvedHandle instanceof DirectMethodHandle) {
1347                 MemberName m = resolvedHandle.internalMemberName();
1348                 assert(m.equals(member));
1349             }
1350             return true;
1351         }
1352 
1353         Class<?> memberDeclaringClassOrNull() {
1354             return (member == null) ? null : member.getDeclaringClass();
1355         }
1356 
1357         BasicType returnType() {
1358             return basicType(methodType().returnType());
1359         }
1360 
1361         BasicType parameterType(int n) {
1362             return basicType(methodType().parameterType(n));
1363         }
1364 
1365         int arity() {
1366             return methodType().parameterCount();
1367         }
1368 
1369         public String toString() {
1370             if (member == null)  return String.valueOf(resolvedHandle);
1371             return member.getDeclaringClass().getSimpleName()+"."+member.getName();
1372         }
1373 
1374         public boolean isIdentity() {
1375             return this.equals(identity(returnType()));
1376         }
1377 
1378         public boolean isConstantZero() {
1379             return this.equals(constantZero(returnType()));
1380         }
1381 
1382         public MethodHandleImpl.Intrinsic intrinsicName() {
1383             return resolvedHandle == null ? MethodHandleImpl.Intrinsic.NONE
1384                                           : resolvedHandle.intrinsicName();
1385         }
1386     }
1387 
1388     public static String basicTypeSignature(MethodType type) {
1389         int params = type.parameterCount();
1390         char[] sig = new char[params + 2];
1391         int sigp = 0;
1392         while (sigp < params) {
1393             sig[sigp] = basicTypeChar(type.parameterType(sigp++));
1394         }
1395         sig[sigp++] = '_';
1396         sig[sigp++] = basicTypeChar(type.returnType());
1397         assert(sigp == sig.length);
1398         return String.valueOf(sig);
1399     }
1400     public static String shortenSignature(String signature) {
1401         // Hack to make signatures more readable when they show up in method names.
1402         final int NO_CHAR = -1, MIN_RUN = 3;
1403         int c0, c1 = NO_CHAR, c1reps = 0;
1404         StringBuilder buf = null;
1405         int len = signature.length();
1406         if (len < MIN_RUN)  return signature;
1407         for (int i = 0; i <= len; i++) {
1408             // shift in the next char:
1409             c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i));
1410             if (c1 == c0) { ++c1reps; continue; }
1411             // shift in the next count:
1412             int c0reps = c1reps; c1reps = 1;
1413             // end of a  character run
1414             if (c0reps < MIN_RUN) {
1415                 if (buf != null) {
1416                     while (--c0reps >= 0)
1417                         buf.append((char)c0);
1418                 }
1419                 continue;
1420             }
1421             // found three or more in a row
1422             if (buf == null)
1423                 buf = new StringBuilder().append(signature, 0, i - c0reps);
1424             buf.append((char)c0).append(c0reps);
1425         }
1426         return (buf == null) ? signature : buf.toString();
1427     }
1428 
1429     static final class Name {
1430         final BasicType type;
1431         @Stable short index;
1432         final NamedFunction function;
1433         final Object constraint;  // additional type information, if not null
1434         @Stable final Object[] arguments;
1435 
1436         private Name(int index, BasicType type, NamedFunction function, Object[] arguments) {
1437             this.index = (short)index;
1438             this.type = type;
1439             this.function = function;
1440             this.arguments = arguments;
1441             this.constraint = null;
1442             assert(this.index == index);
1443         }
1444         private Name(Name that, Object constraint) {
1445             this.index = that.index;
1446             this.type = that.type;
1447             this.function = that.function;
1448             this.arguments = that.arguments;
1449             this.constraint = constraint;
1450             assert(constraint == null || isParam());  // only params have constraints
1451             assert(constraint == null || constraint instanceof BoundMethodHandle.SpeciesData || constraint instanceof Class);
1452         }
1453         Name(MethodHandle function, Object... arguments) {
1454             this(new NamedFunction(function), arguments);
1455         }
1456         Name(MethodType functionType, Object... arguments) {
1457             this(new NamedFunction(functionType), arguments);
1458             assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE);
1459         }
1460         Name(MemberName function, Object... arguments) {
1461             this(new NamedFunction(function), arguments);
1462         }
1463         Name(NamedFunction function, Object... arguments) {
1464             this(-1, function.returnType(), function, arguments = Arrays.copyOf(arguments, arguments.length, Object[].class));
1465             assert(typesMatch(function, arguments));
1466         }
1467         /** Create a raw parameter of the given type, with an expected index. */
1468         Name(int index, BasicType type) {
1469             this(index, type, null, null);
1470         }
1471         /** Create a raw parameter of the given type. */
1472         Name(BasicType type) { this(-1, type); }
1473 
1474         BasicType type() { return type; }
1475         int index() { return index; }
1476         boolean initIndex(int i) {
1477             if (index != i) {
1478                 if (index != -1)  return false;
1479                 index = (short)i;
1480             }
1481             return true;
1482         }
1483         char typeChar() {
1484             return type.btChar;
1485         }
1486 
1487         void resolve() {
1488             if (function != null)
1489                 function.resolve();
1490         }
1491 
1492         Name newIndex(int i) {
1493             if (initIndex(i))  return this;
1494             return cloneWithIndex(i);
1495         }
1496         Name cloneWithIndex(int i) {
1497             Object[] newArguments = (arguments == null) ? null : arguments.clone();
1498             return new Name(i, type, function, newArguments).withConstraint(constraint);
1499         }
1500         Name withConstraint(Object constraint) {
1501             if (constraint == this.constraint)  return this;
1502             return new Name(this, constraint);
1503         }
1504         Name replaceName(Name oldName, Name newName) {  // FIXME: use replaceNames uniformly
1505             if (oldName == newName)  return this;
1506             @SuppressWarnings("LocalVariableHidesMemberVariable")
1507             Object[] arguments = this.arguments;
1508             if (arguments == null)  return this;
1509             boolean replaced = false;
1510             for (int j = 0; j < arguments.length; j++) {
1511                 if (arguments[j] == oldName) {
1512                     if (!replaced) {
1513                         replaced = true;
1514                         arguments = arguments.clone();
1515                     }
1516                     arguments[j] = newName;
1517                 }
1518             }
1519             if (!replaced)  return this;
1520             return new Name(function, arguments);
1521         }
1522         /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i].
1523          *  Limit such replacements to {@code start<=i<end}.  Return possibly changed self.
1524          */
1525         Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
1526             if (start >= end)  return this;
1527             @SuppressWarnings("LocalVariableHidesMemberVariable")
1528             Object[] arguments = this.arguments;
1529             boolean replaced = false;
1530         eachArg:
1531             for (int j = 0; j < arguments.length; j++) {
1532                 if (arguments[j] instanceof Name) {
1533                     Name n = (Name) arguments[j];
1534                     int check = n.index;
1535                     // harmless check to see if the thing is already in newNames:
1536                     if (check >= 0 && check < newNames.length && n == newNames[check])
1537                         continue eachArg;
1538                     // n might not have the correct index: n != oldNames[n.index].
1539                     for (int i = start; i < end; i++) {
1540                         if (n == oldNames[i]) {
1541                             if (n == newNames[i])
1542                                 continue eachArg;
1543                             if (!replaced) {
1544                                 replaced = true;
1545                                 arguments = arguments.clone();
1546                             }
1547                             arguments[j] = newNames[i];
1548                             continue eachArg;
1549                         }
1550                     }
1551                 }
1552             }
1553             if (!replaced)  return this;
1554             return new Name(function, arguments);
1555         }
1556         void internArguments() {
1557             @SuppressWarnings("LocalVariableHidesMemberVariable")
1558             Object[] arguments = this.arguments;
1559             for (int j = 0; j < arguments.length; j++) {
1560                 if (arguments[j] instanceof Name) {
1561                     Name n = (Name) arguments[j];
1562                     if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
1563                         arguments[j] = internArgument(n);
1564                 }
1565             }
1566         }
1567         boolean isParam() {
1568             return function == null;
1569         }
1570         boolean isConstantZero() {
1571             return !isParam() && arguments.length == 0 && function.isConstantZero();
1572         }
1573 
1574         boolean refersTo(Class<?> declaringClass, String methodName) {
1575             return function != null &&
1576                     function.member() != null && function.member().refersTo(declaringClass, methodName);
1577         }
1578 
1579         /**
1580          * Check if MemberName is a call to MethodHandle.invokeBasic.
1581          */
1582         boolean isInvokeBasic() {
1583             if (function == null)
1584                 return false;
1585             if (arguments.length < 1)
1586                 return false;  // must have MH argument
1587             MemberName member = function.member();
1588             return member != null && member.refersTo(MethodHandle.class, "invokeBasic") &&
1589                     !member.isPublic() && !member.isStatic();
1590         }
1591 
1592         /**
1593          * Check if MemberName is a call to MethodHandle.linkToStatic, etc.
1594          */
1595         boolean isLinkerMethodInvoke() {
1596             if (function == null)
1597                 return false;
1598             if (arguments.length < 1)
1599                 return false;  // must have MH argument
1600             MemberName member = function.member();
1601             return member != null &&
1602                     member.getDeclaringClass() == MethodHandle.class &&
1603                     !member.isPublic() && member.isStatic() &&
1604                     member.getName().startsWith("linkTo");
1605         }
1606 
1607         public String toString() {
1608             return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar();
1609         }
1610         public String debugString() {
1611             String s = paramString();
1612             return (function == null) ? s : s + "=" + exprString();
1613         }
1614         public String paramString() {
1615             String s = toString();
1616             Object c = constraint;
1617             if (c == null)
1618                 return s;
1619             if (c instanceof Class)  c = ((Class<?>)c).getSimpleName();
1620             return s + "/" + c;
1621         }
1622         public String exprString() {
1623             if (function == null)  return toString();
1624             StringBuilder buf = new StringBuilder(function.toString());
1625             buf.append("(");
1626             String cma = "";
1627             for (Object a : arguments) {
1628                 buf.append(cma); cma = ",";
1629                 if (a instanceof Name || a instanceof Integer)
1630                     buf.append(a);
1631                 else
1632                     buf.append("(").append(a).append(")");
1633             }
1634             buf.append(")");
1635             return buf.toString();
1636         }
1637 
1638         private boolean typesMatch(NamedFunction function, Object ... arguments) {
1639             assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
1640             for (int i = 0; i < arguments.length; i++) {
1641                 assert (typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
1642             }
1643             return true;
1644         }
1645 
1646         private static boolean typesMatch(BasicType parameterType, Object object) {
1647             if (object instanceof Name) {
1648                 return ((Name)object).type == parameterType;
1649             }
1650             switch (parameterType) {
1651                 case I_TYPE:  return object instanceof Integer;
1652                 case J_TYPE:  return object instanceof Long;
1653                 case F_TYPE:  return object instanceof Float;
1654                 case D_TYPE:  return object instanceof Double;
1655             }
1656             assert(parameterType == L_TYPE);
1657             return true;
1658         }
1659 
1660         /** Return the index of the last occurrence of n in the argument array.
1661          *  Return -1 if the name is not used.
1662          */
1663         int lastUseIndex(Name n) {
1664             if (arguments == null)  return -1;
1665             for (int i = arguments.length; --i >= 0; ) {
1666                 if (arguments[i] == n)  return i;
1667             }
1668             return -1;
1669         }
1670 
1671         /** Return the number of occurrences of n in the argument array.
1672          *  Return 0 if the name is not used.
1673          */
1674         int useCount(Name n) {
1675             if (arguments == null)  return 0;
1676             int count = 0;
1677             for (int i = arguments.length; --i >= 0; ) {
1678                 if (arguments[i] == n)  ++count;
1679             }
1680             return count;
1681         }
1682 
1683         boolean contains(Name n) {
1684             return this == n || lastUseIndex(n) >= 0;
1685         }
1686 
1687         public boolean equals(Name that) {
1688             if (this == that)  return true;
1689             if (isParam())
1690                 // each parameter is a unique atom
1691                 return false;  // this != that
1692             return
1693                 //this.index == that.index &&
1694                 this.type == that.type &&
1695                 this.function.equals(that.function) &&
1696                 Arrays.equals(this.arguments, that.arguments);
1697         }
1698         @Override
1699         public boolean equals(Object x) {
1700             return x instanceof Name && equals((Name)x);
1701         }
1702         @Override
1703         public int hashCode() {
1704             if (isParam())
1705                 return index | (type.ordinal() << 8);
1706             return function.hashCode() ^ Arrays.hashCode(arguments);
1707         }
1708     }
1709 
1710     /** Return the index of the last name which contains n as an argument.
1711      *  Return -1 if the name is not used.  Return names.length if it is the return value.
1712      */
1713     int lastUseIndex(Name n) {
1714         int ni = n.index, nmax = names.length;
1715         assert(names[ni] == n);
1716         if (result == ni)  return nmax;  // live all the way beyond the end
1717         for (int i = nmax; --i > ni; ) {
1718             if (names[i].lastUseIndex(n) >= 0)
1719                 return i;
1720         }
1721         return -1;
1722     }
1723 
1724     /** Return the number of times n is used as an argument or return value. */
1725     int useCount(Name n) {
1726         int nmax = names.length;
1727         int end = lastUseIndex(n);
1728         if (end < 0)  return 0;
1729         int count = 0;
1730         if (end == nmax) { count++; end--; }
1731         int beg = n.index() + 1;
1732         if (beg < arity)  beg = arity;
1733         for (int i = beg; i <= end; i++) {
1734             count += names[i].useCount(n);
1735         }
1736         return count;
1737     }
1738 
1739     static Name argument(int which, BasicType type) {
1740         if (which >= INTERNED_ARGUMENT_LIMIT)
1741             return new Name(which, type);
1742         return INTERNED_ARGUMENTS[type.ordinal()][which];
1743     }
1744     static Name internArgument(Name n) {
1745         assert(n.isParam()) : "not param: " + n;
1746         assert(n.index < INTERNED_ARGUMENT_LIMIT);
1747         if (n.constraint != null)  return n;
1748         return argument(n.index, n.type);
1749     }
1750     static Name[] arguments(int extra, MethodType types) {
1751         int length = types.parameterCount();
1752         Name[] names = new Name[length + extra];
1753         for (int i = 0; i < length; i++)
1754             names[i] = argument(i, basicType(types.parameterType(i)));
1755         return names;
1756     }
1757     static final int INTERNED_ARGUMENT_LIMIT = 10;
1758     private static final Name[][] INTERNED_ARGUMENTS
1759             = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT];
1760     static {
1761         for (BasicType type : BasicType.ARG_TYPES) {
1762             int ord = type.ordinal();
1763             for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) {
1764                 INTERNED_ARGUMENTS[ord][i] = new Name(i, type);
1765             }
1766         }
1767     }
1768 
1769     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
1770 
1771     static LambdaForm identityForm(BasicType type) {
1772         int ord = type.ordinal();
1773         LambdaForm form = LF_identity[ord];
1774         if (form != null) {
1775             return form;
1776         }
1777         createFormsFor(type);
1778         return LF_identity[ord];
1779     }
1780 
1781     static LambdaForm zeroForm(BasicType type) {
1782         int ord = type.ordinal();
1783         LambdaForm form = LF_zero[ord];
1784         if (form != null) {
1785             return form;
1786         }
1787         createFormsFor(type);
1788         return LF_zero[ord];
1789     }
1790 
1791     static NamedFunction identity(BasicType type) {
1792         int ord = type.ordinal();
1793         NamedFunction function = NF_identity[ord];
1794         if (function != null) {
1795             return function;
1796         }
1797         createFormsFor(type);
1798         return NF_identity[ord];
1799     }
1800 
1801     static NamedFunction constantZero(BasicType type) {
1802         int ord = type.ordinal();
1803         NamedFunction function = NF_zero[ord];
1804         if (function != null) {
1805             return function;
1806         }
1807         createFormsFor(type);
1808         return NF_zero[ord];
1809     }
1810 
1811     private static final @Stable LambdaForm[] LF_identity = new LambdaForm[TYPE_LIMIT];
1812     private static final @Stable LambdaForm[] LF_zero = new LambdaForm[TYPE_LIMIT];
1813     private static final @Stable NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT];
1814     private static final @Stable NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT];
1815 
1816     private static synchronized void createFormsFor(BasicType type) {
1817         final int ord = type.ordinal();
1818         LambdaForm idForm = LF_identity[ord];
1819         if (idForm != null) {
1820             return;
1821         }
1822         char btChar = type.basicTypeChar();
1823         boolean isVoid = (type == V_TYPE);
1824         Class<?> btClass = type.btClass;
1825         MethodType zeType = MethodType.methodType(btClass);
1826         MethodType idType = (isVoid) ? zeType : zeType.appendParameterTypes(btClass);
1827 
1828         // Look up symbolic names.  It might not be necessary to have these,
1829         // but if we need to emit direct references to bytecodes, it helps.
1830         // Zero is built from a call to an identity function with a constant zero input.
1831         MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic);
1832         MemberName zeMem = null;
1833         try {
1834             idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, NoSuchMethodException.class);
1835             if (!isVoid) {
1836                 zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic);
1837                 zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, NoSuchMethodException.class);
1838             }
1839         } catch (IllegalAccessException|NoSuchMethodException ex) {
1840             throw newInternalError(ex);
1841         }
1842 
1843         NamedFunction idFun;
1844         LambdaForm zeForm;
1845         NamedFunction zeFun;
1846 
1847         // Create the LFs and NamedFunctions. Precompiling LFs to byte code is needed to break circular
1848         // bootstrap dependency on this method in case we're interpreting LFs
1849         if (isVoid) {
1850             Name[] idNames = new Name[] { argument(0, L_TYPE) };
1851             idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT);
1852             idForm.compileToBytecode();
1853             idFun = new NamedFunction(idMem, SimpleMethodHandle.make(idMem.getInvocationType(), idForm));
1854 
1855             zeForm = idForm;
1856             zeFun = idFun;
1857         } else {
1858             Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) };
1859             idForm = new LambdaForm(idMem.getName(), 2, idNames, 1);
1860             idForm.compileToBytecode();
1861             idFun = new NamedFunction(idMem, SimpleMethodHandle.make(idMem.getInvocationType(), idForm));
1862 
1863             Object zeValue = Wrapper.forBasicType(btChar).zero();
1864             Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) };
1865             zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1);
1866             zeForm.compileToBytecode();
1867             zeFun = new NamedFunction(zeMem, SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm));
1868         }
1869 
1870         LF_zero[ord] = zeForm;
1871         NF_zero[ord] = zeFun;
1872         LF_identity[ord] = idForm;
1873         NF_identity[ord] = idFun;
1874 
1875         assert(idFun.isIdentity());
1876         assert(zeFun.isConstantZero());
1877         assert(new Name(zeFun).isConstantZero());
1878     }
1879 
1880     // Avoid appealing to ValueConversions at bootstrap time:
1881     private static int identity_I(int x) { return x; }
1882     private static long identity_J(long x) { return x; }
1883     private static float identity_F(float x) { return x; }
1884     private static double identity_D(double x) { return x; }
1885     private static Object identity_L(Object x) { return x; }
1886     private static void identity_V() { return; }
1887     private static int zero_I() { return 0; }
1888     private static long zero_J() { return 0; }
1889     private static float zero_F() { return 0; }
1890     private static double zero_D() { return 0; }
1891     private static Object zero_L() { return null; }
1892 
1893     /**
1894      * Internal marker for byte-compiled LambdaForms.
1895      */
1896     /*non-public*/
1897     @Target(ElementType.METHOD)
1898     @Retention(RetentionPolicy.RUNTIME)
1899     @interface Compiled {
1900     }
1901 
1902     /**
1903      * Internal marker for LambdaForm interpreter frames.
1904      */
1905     /*non-public*/
1906     @Target(ElementType.METHOD)
1907     @Retention(RetentionPolicy.RUNTIME)
1908     @interface Hidden {
1909     }
1910 
1911     private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
1912     static {
1913         if (debugEnabled())
1914             DEBUG_NAME_COUNTERS = new HashMap<>();
1915         else
1916             DEBUG_NAME_COUNTERS = null;
1917     }
1918 
1919     // Put this last, so that previous static inits can run before.
1920     static {
1921         if (USE_PREDEFINED_INTERPRET_METHODS)
1922             computeInitialPreparedForms();
1923         NamedFunction.initializeInvokers();
1924     }
1925 
1926     // The following hack is necessary in order to suppress TRACE_INTERPRETER
1927     // during execution of the static initializes of this class.
1928     // Turning on TRACE_INTERPRETER too early will cause
1929     // stack overflows and other misbehavior during attempts to trace events
1930     // that occur during LambdaForm.<clinit>.
1931     // Therefore, do not move this line higher in this file, and do not remove.
1932     private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
1933 }
--- EOF ---